Telegram Bot 開發起手式

最近這陣子看到了聊天機器人這篇文章,可以透過程式的撰寫,來跟使用者互動,我覺得還蠻有趣的,剛好這陣子有一點時間就來嘗試了。 目前可以撰寫 Bot 的平台蠻多的,像是:Facebook MessagerLine BotTelegram BotSlack Bot ...etc,我想應該還有一些其他相關的 Bot 服務,而因為我現在有使用 Telegram 通訊軟體,所以這次選擇使用 Telegram Bot 做為開發 Bot 的選擇。

事前準備

首先,開發 Telegram Bot 最好可以申請一個 Telegram 的帳號,在之後也比較易於方便測試,接著:

  • 你需要加入 @BotFather 這個機器人,之後需要申請 Token
  • 選擇你所需要開發的語言(大部分都有包裝好的 API library 可以使用)。

我選擇使用 Node.js 來開發 Bot,並使用 node-telegram-bot-api 這個經過包裝後的 API 來方便開發 Bot。

如果有興趣可以參考這篇官方所提供的文章 Bots: An introduction for developers,還有在開發 Bot 也請搭配的官方所提供的 API 文件,寫的非常明白。

申請 Token

加入 @BotFather 後,你如果需要建立一個 bot,請輸入 /newbot 來建立一個新的機器人。

Bew Bot

在輸入框輸入 / 就會有提示有哪些 command 可以使用,如果不了解可以輸入 /help 可以顯示的更完整。

接著 @BotFather 會要求你輸入 Bot 的名稱,完成後就可以拿到 Token 囉!

Get Token

拿到 Token 你就可以建立你的 project 進行開發了。

開發 Telegram Bot

接下來,你需要建立一個新的專案來開發 Telegram Bot,前面提到了我使用 node-telegram-bot-api,所以在 command 下輸入來安裝:

$ npm install node-telegram-bot-api --save

安裝完成後,我們就嘗試來撰寫讓機器人發出 Hello World 的訊息吧!我們先查詢 node-telegram-bot-api 文件,了解如何使用這個 library。

// 建立一個 Bot
import TelegramBot from 'node-telegram-bot-api';
const token = 'Your Token';
const bot = new TelegramBot(token, { polling: true });

node-telegram-bot-api import 進來後,設定完 Token,就可以建立一個 Bot 了,接著我們再加入一些程式碼,讓 Bot 跟我們 say Hello!

import TelegramBot from 'node-telegram-bot-api';
const token = 'Your Token';
const bot = new TelegramBot(token, { polling: true });
bot.onText(/\/start/, message => {
console.log(message); // for debug
const chatId = message.chat.id;
bot.sendMessage(chatId, 'Hello World');
});

接著啟動你的 app 後就可以對 Bot 發出 /start 的 command,Bot 會回覆 Hello World

Demo Bot

bot.onText 這個 method,第一個參數是設定 Regular expression(正規表達式),接著後面的參數是 callback,裡面所帶的參數有 messagematch

當 match 到 Regular expression(這裡是 /start)時,在 message 這個參數你會得到一個 Object,內容大概像是:

{
message_id: 3,
from: {
id: 123456,
first_name: 'xxx',
last_name: 'xxx',
username: 'xxx'
},
chat: {
id: 123456,
first_name: 'xxx',
last_name: 'xxx',
username: 'xxx',
type: 'private'
},
date: 1234567890,
text: '/start',
entities: [ { type: 'bot_command', offset: 0, length: 0 } ]
}

接著要讓 Bot 回傳訊息,有提供 sendMessage 的 method 可以使用,第一個參數是 chatId,然後是要回傳的訊息 text,這兩個參數是 Required 的,當然還有其他的參數可以做回傳,可以參考官方的文件 API#sendMessage

這是一個非常簡單的範例,開發 Telegram Bot 相當的容易,官方提供的文件也非常的完整。

開發 Telegram Weather Bot 所遇到的問題

我使用 Yahoo Weather API 來開發了一個天氣查詢的 Bot,一開始我想到透過使用定位的方式取得使用者的位置,來做定位,在官方的 Changelog 中找到了:

April 9, 2016

  • Bots can request location and phone number from the user. The keyboard field in the object ReplyKeyboardMarkup now supports KeyboardButton, a new object that can have the fields request_location and request_contact.

所以可以取得使用者的位置是沒問題了,但是要怎麼取得這個定位的資料呢?

我看了 Available methods 好像都沒有找到,後來在 node-telegram-bot-api 的 source code 找到方法了:

class TelegramBot extends EventEmitter {
//
}

重點就是在 class TelegramBot extends EventEmitter 這段,這是 Nodejs 的 EventEmitter,當 Telegram Bot 接收到 Message 後,會 emit message,以下其中之一都可以 emit 一個 Event:

text, audio, document, photo, sticker, video, voice, contact, location, new_chat_participant, left_chat_participant, new_chat_title, new_chat_photo, delete_chat_photo, group_chat_created

所以,找到方法了,只要設定一個 Event listener 來 listen location,我就可以取得使用者的定位資料了。

bot.on('location', message => {
// Todo
});

這是我所開發的 Telegram Weather Bot,如果覺得不錯請給我一顆 Star 吧!XD,這個機器人我也 deploy 到 heroku 去了,所以可以和大家互動,歡迎調戲!

Link