只要覺得有什麼可以改進的就動手做,我想這就是工程師的浪漫吧
我就在想除了網站是不是可以和聊天機器下做點什麼,因為公司是使用Telegram,我自己是只使用過LINE Bot,所以當下開始研究Telegram Bot的資料,一開始我以LINE Bot的方式去思考,結果發現原來有更好的方法,真的是讓我開了眼界!
先講LINE Bot我所習慣的流程,
- 到LINE DEV 申請一個新的Channel,並紀錄channel secret
- 安裝 line-bot-sdk-python
- 使用Python API 框架(現在我自己比較喜歡FastAPI,但也使用過Django、Flask)
- 本機測試需安裝ngrok,產生對應API port的HTTPS網址
- 在LINE DEV Channel 設定ngrok產生的網址於webhook
- 接下來就可以開始測試了
我以LINE Bot的流程去操作Telegram Bot
- 申請Bot Token(等同LINE DEV 申請一個Channel
- 到Telegram搜尋 @BotFather 並加入
2. 輸入 /start
點擊 /newbot
就會進入麻煩的取名環節,記得最後一定要加Bot或是_bot
ex: 我是測試Bot or 我是測試_bot
名稱不能重複而且我自己測試是不支援 —
終於成功取好名後就會得到這個Bot的Token
- 建置API server(接收webhook 及發訊息
- 我自己是使用Python FastAPI建置,任何API 框架皆可
main.py
只節錄一點code
from fastapi import FastAPI
app = FastAPI()
@app.post("/bot/callback")
async def say_hello(request: Request):
client_host = request.client.host
print(await request.body())
return {"client_host": client_host}
2. 再來重要的是要讓telegram 設定webhook url發送到你的電腦,這時候就需要使用Ngrok,fastAPI預設是使用8000 port所以就在terminal 中輸入
./ngrok http 8000
然後就會複製裡面的https的URL
3.綁定telegram bot webhoook
可以使用Curl 或者是Postman又或者是直接貼在瀏覽器上
網址是
https://api.telegram.org/bot{my_bot_token}/setWebhook?url={url_to_send_updates_to}
這樣就設定好webhook了
可以透過這個網址檢查
https://api.telegram.org/bot{my_bot_token}/getWebhookInfo
- 設定好後就將API啟動,並在Telegram中說話,然後看API console
{"update_id": XXXXXXXXXX,\n"message": {"message_id": 17,"from": {"id": XXXXXXXXXX,"is_bot": false,"first_name": "Morris","last_name": "Lin","username": "XXXXXXXXXX","language_code": "en"},"chat": {"id": XXXXXXXXX,"first_name": "Morris","last_name": "Lin","username": "XXXXXXXXX","type": "private"},"date": 1642155727,"text": "hihi bot webhook test"}
這樣就是我之前在做Bot的前置作業,通常可以收到訊息後就可以開始做機器人的邏輯跟回覆,但是就在我開始準備製作時,發現了一個很猛的工具
python-telegram-bot
很霸氣開宗明義就講明了,我們就來實驗看看好了。
我們從它的example 隨便找一個來測看看,
我節錄一下echobot.py
def main() -> None:
"""Start the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater("你的Token")
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# on different commands - answer in Telegram
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("help", help_command))
# on non command i.e message - echo the message on Telegram
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
只需你的token,啟動之後,不用設定webhook,馬上就可以用
對我來說真的是學到了新東西
接下來就開始要來研究這個真的讓人無法拒絕的wrapper