iT邦幫忙

2021 iThome 鐵人賽

DAY 20
0
Software Development

用 PHP 打造專屬於自己的 Telegram 聊天機器人吧!系列 第 20

【PHP Telegram Bot】Day20 - sendMessage:發送和轉換 Markdown 訊息

今天先來點輕鬆的,先來看看各種 sendMessage 的功能,最後來轉換使用者發送的 Markdown 文字

sendMessage

https://core.telegram.org/bots/api#sendmessage
https://ithelp.ithome.com.tw/upload/images/20210929/20132916SZ9g5d681l.png
https://ithelp.ithome.com.tw/upload/images/20210929/201329164edq2AVs1B.png

參數 說明
chat_id 這格可以填群組和頻道的 id 或 @username,但是私訊的話就只能填 user_id
text 要發送的文字放在這裡,最多可以 4096 個字
parse_mode 這個可以解析 Markdown 或是 HTML 語法
entities 看起來是可以替代 parse_mode,但我一直沒試成功,有高手會用的話留言教我一下
disable_web_page_preview 設成 true 的話,機器人發出去的連結就不會有預覽,會比較不洗板
disable_notification true 會關閉這則訊息的通知,只有在頻道能使用
reply_to_message_id 設定要回覆哪則訊息
allow_sending_without_reply 設定為 true 時,就算被回覆的訊息不存在也會發送訊息,否則會出現 Bad Request: replied message not found
reply_markup 這個可以讓訊息出現按紐,或是下方出現選項,像這樣。這個之後會再詳細講

發送 Markdown 訊息

不知道你還有沒有留著之前的機器人程式,如果有的話就把它打開來,把之前寫的東西都先註解掉,留下上方的函式

沒留著的話就重寫一邊吧,多練習是好事~
https://ithelp.ithome.com.tw/upload/images/20210929/20132916dg9l1b11Ph.png
之後打出像這樣的程式,chat_id 填你的 uid,parse_mode 填上 MarkdownV2,response 可以偷懶不打,那個只是我想看伺服器回傳的訊息
https://ithelp.ithome.com.tw/upload/images/20210929/20132916hECs1khFUn.png
官方的範例拿來玩玩
https://ithelp.ithome.com.tw/upload/images/20210929/20132916OVRrvAcFQc.png
貼進 text,並按下執行程式
https://ithelp.ithome.com.tw/upload/images/20210929/20132916MUjHUewp3Y.png
PHP 的字串本身就可以打成多行,但是前面的空白會留在字串裡
https://ithelp.ithome.com.tw/upload/images/20210929/20132916CctNqlqGdQ.png
加上 preg_replace 就能保持程式碼美觀又能去掉前面的空白啦
https://ithelp.ithome.com.tw/upload/images/20210929/20132916ObPnJWTw5w.png
這樣好多了
https://ithelp.ithome.com.tw/upload/images/20210929/20132916FWs7odAE2S.png
另外的 HTML 就交給你自己玩玩啦


轉換使用者輸入的 Markdown

接著來把使用者的輸入轉換然後發送回去

來到 processMessage 這裡

可以看到官方已經幫我們把使用者輸入的文字,還有訊息和聊天室的 id 從陣列中找出來了
https://ithelp.ithome.com.tw/upload/images/20210929/20132916JE2brPIzVp.png
接著把下方一堆 if else 註解掉(選起來按 Ctrl + /),把剛剛寫的東西貼過來

填上官方幫你找好的變數,你也可以加上 reply_to_message_id 那些其他參數
https://ithelp.ithome.com.tw/upload/images/20210929/20132916YqdWUugjVu.png
之後要記得把 Long Polling 的那坨程式取消註解(選起來按 Ctrl + /
https://ithelp.ithome.com.tw/upload/images/20210929/20132916fqj0RcOewM.png
最後執行程式,你就可以發送文字讓機器人轉換啦
https://ithelp.ithome.com.tw/upload/images/20210929/201329160pvxCsM6QS.png


上一篇
【PHP Telegram Bot】Day19 - 基礎(8):迴圈、Xdebug
下一篇
【PHP Telegram Bot】Day21 - sendPhoto:三種發送圖片的方式
系列文
用 PHP 打造專屬於自己的 Telegram 聊天機器人吧!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言