Telegram Bot โดย Nodejs พร้อมการ Deploy ขึ้น Heroku

Mine ArithmeticOp
3 min readFeb 9, 2019

--

วิธีการสร้าง bot telegram เบื้องต้น โดย nodejs และ deploy ขึ้น heroku

ขั้นตอนสร้าง telegram bot

  1. แอดเพื่อน BotFather
  2. ลองพิมพ์ /start ลงไปในช่องแชท BotFather จะเป็นการแสดง command ต่างๆ ที่ใช้งานได้
  3. พิมพ์ /newbot เพื่อสร้าง bot ของเรา หลังจากนั้น BotFather จะตอบกลับมาว่า “Alright, a new bot. How are we going to call it? Please choose a name for your bot.”
  4. ให้เราใส่ชื่อ bot ที่เราต้องการลงไป โดยในชื่อต้องลงท้ายด้วย “bot” เช่น “netpie_bot”
  5. หลังจากสร้าง bot สำหรับผ่าน BotFather เราก็จะได้รับ token สำหรับใช้งาน http api มา

การใช้งาน telegram bot

สามารถดู api manual ได้ที่นี่

  1. รู้จักคำสั่งหลักที่ให้ bot สามารถส่งข้อความกลับมายังผู้ใช้ได้คือ sendMessage

โดย Parameter หลัก สำหรับใช้ส่งข้อความคือ

  • chat_id คือ id ของห้องแชทระหว่างเรากับบอท
  • text คือข้อความที่บอทจะส่งไปยังผู้ใช้

แต่เราจะหา chat_id ได้อย่างไรกันล่ะ มาดูกันต่อเลย

2. การสร้าง Server เพื่อให้บอทของเราสามารถรับข้อความจากห้องแชทได้

ในที่นี้เราจะใช้ภาษา Nodejs ในการสร้างนะครับ โดยใช้ module restify เพื่อทำ webhook

ไฟล์ bot.js // การทำ rest เพื่อรอรับข้อความจากผู้ใช้const restify = require('restify');
const PORT = process.env.PORT || 6000;
const server = restify.createServer();
server.use(restify.plugins.bodyParser());
server.post('/bot', respond);
function respond (req, res, next) {
console.log(req.body);
}
server.listen(PORT, () => {
console.log(`${server.name} listening at ${server.url}`);
});

เท่านี้เราก็จะได้ server เพื่อรอรับข้อมูลจากผู้ใช้แล้ว

แต่ก่อนที่ข้อความจะส่งมายัง server ได้นั้น เราต้อง setWebhook ให้กับ telegram ก่อน ซึ่งสามารถ set ได้ตาม format ดังนี้

curl -F "url=https://<YOURDOMAIN.EXAMPLE>/<WEBHOOKLOCATION>" https://api.telegram.org/bot<YOURTOKEN>/setWebhook

ตัวอย่างการใช้งาน format เช่น

curl -F "url=https://61f52bda.ngrok.io/bot" https://api.telegram.org/bot708341170:ABFFTAAtdTqQoaTlhB-eqLsyFrta1r1nxcc/setWebhook

3. การใช้งาน ngrok เพื่อเปิดช่องสาธารณะอย่างง่าย ให้เครื่องที่ไม่ได้อยู่ใน local ส่งข้อมูลมายังเราได้ อ่านวิธีการใช้งานได้ที่นี่

4. เมื่อเราเขียนโค้ด restify เบื้องต้น, ติดตั้ง webhook และเปิด ngrok เรียบร้อยแล้ว

มาลองส่งข้อความจาก telegram แล้วมาดู log กัน

ลองส่งข้อความใน telegram

ตัวอย่างข้อความจาก log

{ update_id: 123456789,
message:
{ message_id: 123,
from:
{ id: 123456789,
is_bot: false,
first_name: 'Mine',
last_name: 'ArithmeticOp',
language_code: 'en' },
chat:
{ id: 123456789,
first_name: 'Mine',
last_name: 'ArithmeticOp',
type: 'private' },
date: 1549699597,
text: 'hello' } }

5. ปรับโค้ดให้ใช้งานกับ sendMessage ที่เป็น telegram api

ในส่วนนี้เราจะนำ restler มาใช้เพื่อส่ง rest ไปยัง telegram กัน

ถ้าหาก node ต่ำกว่า version 8 สามารถใช้

npm install restler 

แต่หากใช้ node สูงกว่า 8 แนะนำให้ใช้โค้ดจาก github ผมนะครับ

วิธีใช้ให้ปรับ package.json ดังนี้

"dependencies": {
"restify": "^7.6.0",
"restler": "https://github.com/ArithmeticOp/restler.git"
}

แล้วทำการ npm install ก็จะสามารถใช้งาน restler ได้แล้วครับ

ไฟล์ bot.js // ที่มีการเพิ่ม sendMessage เข้าไปconst restify = require('restify');
const PORT = process.env.PORT || 6000;
const server = restify.createServer();
const rest = require('restler');
server.use(restify.plugins.bodyParser());
server.post('/bot', respond);
function respond (req, res, next) {
const body = req.body;
const message = body.message;
const chat_id = message.from.id;
let messageOut = 555;

rest.post('https://api.telegram.org/bot708341170:ABFFTAAtdTqQoaTlhB-eqLsyFrta1r1nxcc/sendMessage', {
data: {
chat_id: chat_id,
text: messageOut,
},
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).on('complete', function (data, response) {
console.log(response.statusCode);
console.log(data);
});
}
server.listen(PORT, () => {
console.log(`${server.name} listening at ${server.url}`);
});

เพียงเท่านี้ หลังจากที่เราส่งข้อความมายัง bot ของเรา

bot ของเราก็จะส่งข้อความตอบกลับว่า 555 มายังเราได้แล้วครับ

ตัวอย่างการตอบกลับของ bot

ตัวอย่าง log statusCode และ data ที่ได้จาก emit complete ของ restler

200
{ ok: true,
result:
{ message_id: 123,
from:
{ id: 123456789,
is_bot: true,
first_name: 'mine',
username: 'netpie_bot' },
chat:
{ id: 123456789,
first_name: 'Mine',
last_name: 'ArithmeticOp',
type: 'private' },
date: 1549701633,
text: '555' } }

การ Deploy Heroku

  1. ติดตั้งสำหรับ MacOS
brew install heroku/brew/heroku

2. รันและติดตั้งสำหรับ CLI

heroku autocomplete

3. สร้าง heroku

heroku create

หลังจากสร้าง heroku เรียบร้อยแล้ว เราจะได้ url heroku ที่เราสามารถใช้ได้

https://heli-copter-12345.herokuapp.com/

4. Deploy โค้ดขึ้น heroku

git add .git commitgit push heroku master

ถ้าหากต้องการ deploy โดยใช้ branch อื่น ให้ใช้

git push heroku <branchname>:master

เท่านี้ telegram bot ของเราก็จะอยู่บน heroku เรียบร้อย โดยไม่ต้องเปิด ngrok แล้ว

ดังนั้นมาเปลี่ยน webHook ให้ชี้มาที่ heroku ของเรากันเถอะ

curl -F "url=https://heli-copter-12345.herokuapp.com/bot" https://api.telegram.org/bot708341170:ABFFTAAtdTqQoaTlhB-eqLsyFrta1r1nxcc/setWebhook

หมายเหตุ : เหตุผลที่ผม fork restler มาปรับเอง เนื่องจาก restler ตัว master ไม่รองรับการส่งรูปภาพผ่านแชท เมื่อ node version > 8

--

--