telegtam 機器人配置

telegram有兩種api,這裏採用botapi,系統:centos6.x 語言:java
首先下載telegram pc版本,然後創建一個bot
https://telegram.me/botfather
它會提示你用telegram打開。然後你就打開了botfarther的聊天對話框。輸入
/newbot
回車發送。botfarther會反饋
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
輸入你要創建的bot名字。例如test_bot,回車發送
它會反饋
Good. Now let’s choose a username for your bot. It must end in bot. Like this, for example: TetrisBot or tetris_bot.
我再輸入 TestBot。這是這個機器人的名字。
它會反饋
Sorry, this username is already taken. Please try something different.
這名字已經被用了。我們換一個
GZ_Test_Bot
它會反饋
BotFather, [16.02.17 14:23]
Done! Congratulations on your new bot. You will find it at t.me/Gz_David_Bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you’ve finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.
Use this token to access the HTTP API:
xxx:xxx
For a description of the Bot API, see this page: https://core.telegram.org/bots/api
這裏它生成了api token。我們記下它。以後api請求都會用到。如果需要幫助,輸入 /help
輸入/token 可以重新生成一個token。
/revoke 可以撤銷一個token
我們需要用這個bot來發送消息,首先需要創建一個group,加入一些人,同時將這個bot也加進去。然後在這個group中發送消息。類似 /hello @GZ_David_Bot
然後訪問
https://api.telegram.org/bot(token)/getUpdates 這個請求是請求bot相關的消息,如果返回一個帶消息的json說明bot創建成功
接下來就是要定製bot的命令,根據用戶輸入的命令做出不同的響應
要定製命令首先要能收到bot相關的消息,官方api提供了兩種方法getUpdates(拉取)和setWebHook(推送)
爲了方便開發和消息的實時性,採用第二種setWebHook
要說的是,服務必須是https的具體可見https://core.telegram.org/bots/api
setWebHook很簡單,在服務器執行crul https://api.telegram.org/bot(token)/setWebHook?url=https://you.domain.com/xxx
如果設置成功,會返回一個json消息體是hook was set
現在就可以去telegram跟bot的發消息了,正常的話,這邊會收到消息(前提是這邊寫好了服務)
但是在這裏我遇到一個問題,無論如何我都收不到消息,之後用getUpdates嘗試發現確實有消息
於是https://api.telegram.org/bot(token)/getWebHookInfo返回結果顯示證書配置不正確
我這裏的服務器是tomcat+nginx,證書是買的公共證書,理論上不會有問題,於是去谷歌一下發現端倪
https://www.cubewebsites.com/blog/guides/fix-telegram-webhooks-not-working/
上面說需要把用到的證書合併成一個,找老大確認後發現確實可以收到消息了
但是新問題又來了,接收到的消息體是空的,嘗試很多遍都是空的,谷歌上也有同樣的提問,但是一直沒找到合適的解決方案
仔細查看官方api後發現參數是post過來的,猜測會不會是接參的方法不對,所示直接用輸入流讀取參數算了,經嘗試發現確實好使
如此一來,能收到消息了,就識別消息內容開發不同的邏輯就好了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章