[Go] Telegram Bot 進階篇

程式語言:Go
Package:github.com/go-telegram-bot-api/telegram-bot-api
官方介紹
官方 API
telegram-bot-api GitHub

功能:實現各式進階用法

送出訊息

  1. // 送出訊息
  2. func (t *TeleBot) sendMessage(chatID int64, m string) {
  3. msg := tgbotapi.NewMessage(chatID, m)
  4. t.botAPI.Send(msg)
  5. }

建立下拉式鍵盤選單

  • location & contact 只能使用在 private chat
    在其餘 chat 使用,會導致無法顯示
  1. func (t *TeleBot) creatReplyKeyboardMarkup(chatID int64) {
  2. msg := tgbotapi.NewMessage(chatID, "ReplyKeyboardMarkup")
  3. msg.ReplyMarkup = tgbotapi.ReplyKeyboardMarkup{
  4. Keyboard: [][]tgbotapi.KeyboardButton{
  5. tgbotapi.NewKeyboardButtonRow(
  6. tgbotapi.NewKeyboardButton("button(1,1)"),
  7. tgbotapi.NewKeyboardButtonLocation("location(1,2)"),
  8. tgbotapi.NewKeyboardButtonContact("contact(1,3)"),
  9. ),
  10. tgbotapi.NewKeyboardButtonRow(
  11. tgbotapi.NewKeyboardButton("button(2,1)"),
  12. tgbotapi.NewKeyboardButtonLocation("location(2,2)"),
  13. tgbotapi.NewKeyboardButtonContact("contact(2,3)"),
  14. ),
  15. },
  16. }
  17.  
  18. t.botAPI.Send(msg)
  19. }

移除下拉式鍵盤選單

  1. func (t *TeleBot) removeReplyKeyboardMarkup(chatID int64) {
  2. msg := tgbotapi.NewMessage(chatID, "remove ReplyKeyboardMarkup")
  3. msg.ReplyMarkup = tgbotapi.ReplyKeyboardRemove{
  4. RemoveKeyboard: true,
  5. }
  6. t.botAPI.Send(msg)
  7. }

建立一次性鍵盤選單並調整為最佳化尺寸


  1. func (t *TeleBot) creatReplyKeyboardMarkupOnetimeResize(chatID int64) {
  2. msg := tgbotapi.NewMessage(chatID, "ReplyKeyboardMarkupOneTimeSize")
  3. msg.ReplyMarkup = tgbotapi.ReplyKeyboardMarkup{
  4. Keyboard: [][]tgbotapi.KeyboardButton{
  5. tgbotapi.NewKeyboardButtonRow(
  6. tgbotapi.NewKeyboardButton("button(1,1)"),
  7. tgbotapi.NewKeyboardButtonLocation("location(1,2)"),
  8. tgbotapi.NewKeyboardButtonContact("contact(1,3)"),
  9. ),
  10. tgbotapi.NewKeyboardButtonRow(
  11. tgbotapi.NewKeyboardButton("button(2,1)"),
  12. tgbotapi.NewKeyboardButtonLocation("location(2,2)"),
  13. tgbotapi.NewKeyboardButtonContact("contact(2,3)"),
  14. ),
  15. },
  16. OneTimeKeyboard: true,
  17. ResizeKeyboard: true,
  18. }
  19.  
  20. t.botAPI.Send(msg)
  21. }

建立聊天選單


  1. func (t *TeleBot) creatInlineKeyboardMarkup(chatID int64) {
  2. msg := tgbotapi.NewMessage(chatID, "inlineButton")
  3. str := "cmd"
  4. msg.ReplyMarkup = tgbotapi.NewInlineKeyboardMarkup(
  5. tgbotapi.NewInlineKeyboardRow(
  6. tgbotapi.NewInlineKeyboardButtonData("text(1,1)", "callback_data"),
  7. tgbotapi.NewInlineKeyboardButtonURL("url(1,3)", "https://core.telegram.org/bots/api#inlinekeyboardmarkup"),
  8. tgbotapi.NewInlineKeyboardButtonSwitch("switch_inline_query(1,3)", "cmd"),
  9. tgbotapi.InlineKeyboardButton{
  10. Text: "switch_inline_query_current_chat(1,4)",
  11. SwitchInlineQueryCurrentChat: &str,
  12. },
  13. ),
  14. tgbotapi.NewInlineKeyboardRow(
  15. tgbotapi.NewInlineKeyboardButtonData("text(2,1)", "callback_data"),
  16. tgbotapi.NewInlineKeyboardButtonURL("url(2,2)", "https://core.telegram.org/bots/api#inlinekeyboardmarkup"),
  17. tgbotapi.NewInlineKeyboardButtonSwitch("switch_inline_query(2,3)", "cmd"),
  18. tgbotapi.InlineKeyboardButton{
  19. Text: "switch_inline_query_current_chat(2,4)",
  20. SwitchInlineQueryCurrentChat: &str,
  21. },
  22. ),
  23. )
  24.  
  25. t.botAPI.Send(msg)
  26. }

送出強迫回覆訊息


  1. func (t *TeleBot) sendForceReply(chatID int64) {
  2. msg := tgbotapi.NewMessage(chatID, "ForceReply")
  3.  
  4. msg.ReplyMarkup = tgbotapi.ForceReply{
  5. ForceReply: true,
  6. }
  7.  
  8. t.botAPI.Send(msg)
  9. }

送出 Markdown 格式


  1. func (t *TeleBot) sendMarkdown(chatID int64) {
  2.  
  3. markdown := `*bold text*"
  4. _italic text_"
  5. [inline URL](http://www.example.com/)"
  6. [inline mention of a user](tg://user?id=123456789)`
  7. markdown += "`inline fixed-width code`\n"
  8. markdown += "```block_language\npre-formatted fixed-width code block```"
  9. msg := tgbotapi.NewMessage(chatID, markdown)
  10. msg.ParseMode = tgbotapi.ModeMarkdown
  11. t.botAPI.Send(msg)
  12. }

送出 HTML 格式


  1. func (t *TeleBot) sendHTML(chatID int64) {
  2. htmlT := `<b>bold</b>, <strong>bold</strong>
  3. <i>italic</i>, <em>italic</em>
  4. <a href="http://www.example.com/">inline URL</a>
  5. <a href="tg://user?id=123456789">inline mention of a user</a>
  6. <code>inline fixed-width code</code>
  7. <pre>pre-formatted fixed-width code block</pre>`
  8. msg := tgbotapi.NewMessage(chatID, htmlT)
  9. msg.ParseMode = tgbotapi.ModeHTML
  10. t.botAPI.Send(msg)
  11. }

送出照片


  1. func (t *TeleBot) sendPhoto(chatID int64) {
  2. msg := tgbotapi.NewPhotoShare(chatID, "https://www.logaster.com/blog/wp-content/uploads/2013/06/jpg.png")
  3. msg.Caption = "caption"
  4.  
  5. t.botAPI.Send(msg)
  6. }

針對聊天選單做出回覆


  1. // demo 聊天選單
  2. var replyMarkup = tgbotapi.NewInlineKeyboardMarkup(
  3. ...
  4. tgbotapi.NewInlineKeyboardRow(
  5. tgbotapi.NewInlineKeyboardButtonData("callback_data", "callback_data"),
  6. tgbotapi.NewInlineKeyboardButtonData("callback_data_alert", "callback_data_alert"),
  7. ),
  8. tgbotapi.NewInlineKeyboardRow(
  9. tgbotapi.NewInlineKeyboardButtonData("edited text(也可改 markup)", "edited_text"),
  10. ),
  11. tgbotapi.NewInlineKeyboardRow(
  12. tgbotapi.NewInlineKeyboardButtonData("edited reply markup", "edited_reply_markup"),
  13. ),
  14. )
  15.  
  16. // 回覆空訊息,表示已處理 CallbackQuery
  17. func (t *TeleBot) emptyAnswer(CallbackQueryID string) {
  18. configAlert := tgbotapi.NewCallback(CallbackQueryID, "")
  19. t.botAPI.AnswerCallbackQuery(configAlert)
  20. }
  21.  
  22. // 送出對應的 CallbackQuery 回覆 & 對應指令的動作
  23. func (t *TeleBot) sendAnswerCallbackQuery() {
  24. for update := range t.updates {
  25. if update.Message == nil && update.CallbackQuery == nil {
  26. continue
  27. }
  28.  
  29. if update.Message != nil {
  30. switch update.Message.Text {
  31. case "/demo":
  32. t.demo(update.Message.Chat.ID)
  33. }
  34. }
  35.  
  36. if update.CallbackQuery != nil {
  37. chatID := update.CallbackQuery.Message.Chat.ID
  38. switch update.CallbackQuery.Data {
  39. case "ReplyKeyboardMarkup":
  40. go t.creatReplyKeyboardMarkup(chatID)
  41. go t.emptyAnswer(update.CallbackQuery.ID)
  42. ...
  43. case "callback_data":
  44. config := tgbotapi.NewCallback(update.CallbackQuery.ID, "callbackAnswer")
  45. go t.botAPI.AnswerCallbackQuery(config)
  46. case "callback_data_alert":
  47. configAlert := tgbotapi.NewCallbackWithAlert(update.CallbackQuery.ID, "callbackAnswerAlert")
  48. go t.botAPI.AnswerCallbackQuery(configAlert)
  49. case "edited_text":
  50. editText := tgbotapi.NewEditMessageText(
  51. update.CallbackQuery.Message.Chat.ID,
  52. update.CallbackQuery.Message.MessageID,
  53. "edited text(有改到)",
  54. )
  55.  
  56. replyMarkup.InlineKeyboard[7][0].Text = "edited text(也可改 markup) 已修改"
  57.  
  58. editText.ReplyMarkup = &replyMarkup
  59.  
  60. go t.botAPI.Send(editText)
  61. go t.emptyAnswer(update.CallbackQuery.ID)
  62. case "edited_reply_markup":
  63. replyMarkup.InlineKeyboard[8][0].Text = "edited reply markup 已修改"
  64.  
  65. editReplyMarkup := tgbotapi.NewEditMessageReplyMarkup(
  66. update.CallbackQuery.Message.Chat.ID,
  67. update.CallbackQuery.Message.MessageID,
  68. replyMarkup,
  69. )
  70.  
  71. go t.botAPI.Send(editReplyMarkup)
  72. go t.emptyAnswer(update.CallbackQuery.ID)
  73. }
  74.  
  75. }
  76. }
  77. }

完整程式碼

  1. package main
  2.  
  3. import (
  4. "log"
  5.  
  6. "github.com/go-telegram-bot-api/telegram-bot-api"
  7. )
  8.  
  9. type TeleBot struct {
  10. botAPI *tgbotapi.BotAPI
  11. updates tgbotapi.UpdatesChannel
  12. }
  13.  
  14. // 送出訊息
  15. func (t *TeleBot) sendMessage(chatID int64, m string) {
  16. msg := tgbotapi.NewMessage(chatID, m)
  17. t.botAPI.Send(msg)
  18. }
  19.  
  20. // 建立下拉式鍵盤選單
  21. func (t *TeleBot) creatReplyKeyboardMarkup(chatID int64) {
  22. msg := tgbotapi.NewMessage(chatID, "ReplyKeyboardMarkup")
  23. msg.ReplyMarkup = tgbotapi.ReplyKeyboardMarkup{
  24. Keyboard: [][]tgbotapi.KeyboardButton{
  25. tgbotapi.NewKeyboardButtonRow(
  26. tgbotapi.NewKeyboardButton("button(1,1)"),
  27. tgbotapi.NewKeyboardButtonLocation("location(1,2)"),
  28. tgbotapi.NewKeyboardButtonContact("contact(1,3)"),
  29. ),
  30. tgbotapi.NewKeyboardButtonRow(
  31. tgbotapi.NewKeyboardButton("button(2,1)"),
  32. tgbotapi.NewKeyboardButtonLocation("location(2,2)"),
  33. tgbotapi.NewKeyboardButtonContact("contact(2,3)"),
  34. ),
  35. },
  36. }
  37.  
  38. t.botAPI.Send(msg)
  39. }
  40.  
  41. // 移除下拉式鍵盤選單
  42. func (t *TeleBot) removeReplyKeyboardMarkup(chatID int64) {
  43. msg := tgbotapi.NewMessage(chatID, "remove ReplyKeyboardMarkup")
  44. msg.ReplyMarkup = tgbotapi.ReplyKeyboardRemove{
  45. RemoveKeyboard: true,
  46. }
  47. t.botAPI.Send(msg)
  48. }
  49.  
  50. // 建立一次性鍵盤選單並調整為最佳化尺寸
  51. func (t *TeleBot) creatReplyKeyboardMarkupOnetimeResize(chatID int64) {
  52. msg := tgbotapi.NewMessage(chatID, "ReplyKeyboardMarkupOneTimeSize")
  53. msg.ReplyMarkup = tgbotapi.ReplyKeyboardMarkup{
  54. Keyboard: [][]tgbotapi.KeyboardButton{
  55. tgbotapi.NewKeyboardButtonRow(
  56. tgbotapi.NewKeyboardButton("button(1,1)"),
  57. tgbotapi.NewKeyboardButtonLocation("location(1,2)"),
  58. tgbotapi.NewKeyboardButtonContact("contact(1,3)"),
  59. ),
  60. tgbotapi.NewKeyboardButtonRow(
  61. tgbotapi.NewKeyboardButton("button(2,1)"),
  62. tgbotapi.NewKeyboardButtonLocation("location(2,2)"),
  63. tgbotapi.NewKeyboardButtonContact("contact(2,3)"),
  64. ),
  65. },
  66. OneTimeKeyboard: true,
  67. ResizeKeyboard: true,
  68. }
  69.  
  70. t.botAPI.Send(msg)
  71. }
  72.  
  73. // 建立聊天選單
  74. func (t *TeleBot) creatInlineKeyboardMarkup(chatID int64) {
  75. msg := tgbotapi.NewMessage(chatID, "inlineButton")
  76. str := "cmd"
  77. msg.ReplyMarkup = tgbotapi.NewInlineKeyboardMarkup(
  78. tgbotapi.NewInlineKeyboardRow(
  79. tgbotapi.NewInlineKeyboardButtonData("text(1,1)", "callback_data"),
  80. tgbotapi.NewInlineKeyboardButtonURL("url(1,3)", "https://core.telegram.org/bots/api#inlinekeyboardmarkup"),
  81. tgbotapi.NewInlineKeyboardButtonSwitch("switch_inline_query(1,3)", "cmd"),
  82. tgbotapi.InlineKeyboardButton{
  83. Text: "switch_inline_query_current_chat(1,4)",
  84. SwitchInlineQueryCurrentChat: &str,
  85. },
  86. ),
  87. tgbotapi.NewInlineKeyboardRow(
  88. tgbotapi.NewInlineKeyboardButtonData("text(2,1)", "callback_data"),
  89. tgbotapi.NewInlineKeyboardButtonURL("url(2,2)", "https://core.telegram.org/bots/api#inlinekeyboardmarkup"),
  90. tgbotapi.NewInlineKeyboardButtonSwitch("switch_inline_query(2,3)", "cmd"),
  91. tgbotapi.InlineKeyboardButton{
  92. Text: "switch_inline_query_current_chat(2,4)",
  93. SwitchInlineQueryCurrentChat: &str,
  94. },
  95. ),
  96. )
  97.  
  98. t.botAPI.Send(msg)
  99. }
  100.  
  101. // 送出強迫回覆訊息
  102. func (t *TeleBot) sendForceReply(chatID int64) {
  103. msg := tgbotapi.NewMessage(chatID, "ForceReply")
  104.  
  105. msg.ReplyMarkup = tgbotapi.ForceReply{
  106. ForceReply: true,
  107. }
  108.  
  109. t.botAPI.Send(msg)
  110. }
  111.  
  112. // demo 聊天選單
  113. var replyMarkup = tgbotapi.NewInlineKeyboardMarkup(
  114. tgbotapi.NewInlineKeyboardRow(
  115. tgbotapi.NewInlineKeyboardButtonData("ReplyKeyboardMarkup", "ReplyKeyboardMarkup"),
  116. tgbotapi.NewInlineKeyboardButtonData("removeReplyKeyboardMarkup", "removeReplyKeyboardMarkup"),
  117. ),
  118. tgbotapi.NewInlineKeyboardRow(
  119. tgbotapi.NewInlineKeyboardButtonData("ReplyKeyboardMarkupOneTimeSize", "ReplyKeyboardMarkupOneTimeSize"),
  120. ),
  121. tgbotapi.NewInlineKeyboardRow(
  122. tgbotapi.NewInlineKeyboardButtonData("InlineKeyboardMarkup", "InlineKeyboardMarkup"),
  123. ),
  124. tgbotapi.NewInlineKeyboardRow(
  125. tgbotapi.NewInlineKeyboardButtonData("ForceReply", "ForceReply"),
  126. ),
  127. tgbotapi.NewInlineKeyboardRow(
  128. tgbotapi.NewInlineKeyboardButtonData("Markdown_HTML", "Markdown_HTML"),
  129. ),
  130. tgbotapi.NewInlineKeyboardRow(
  131. tgbotapi.NewInlineKeyboardButtonData("Photo", "Photo"),
  132. ),
  133. tgbotapi.NewInlineKeyboardRow(
  134. tgbotapi.NewInlineKeyboardButtonData("callback_data", "callback_data"),
  135. tgbotapi.NewInlineKeyboardButtonData("callback_data_alert", "callback_data_alert"),
  136. ),
  137. tgbotapi.NewInlineKeyboardRow(
  138. tgbotapi.NewInlineKeyboardButtonData("edited text(也可改 markup)", "edited_text"),
  139. ),
  140. tgbotapi.NewInlineKeyboardRow(
  141. tgbotapi.NewInlineKeyboardButtonData("edited reply markup", "edited_reply_markup"),
  142. ),
  143. )
  144.  
  145. // demo 指令用
  146. func (t *TeleBot) demo(chatID int64) {
  147. msg := tgbotapi.NewMessage(chatID, "inlineButton")
  148. msg.ReplyMarkup = replyMarkup
  149.  
  150. t.botAPI.Send(msg)
  151. }
  152.  
  153. // 回覆空訊息,表示已處理 CallbackQuery
  154. func (t *TeleBot) emptyAnswer(CallbackQueryID string) {
  155. configAlert := tgbotapi.NewCallback(CallbackQueryID, "")
  156. t.botAPI.AnswerCallbackQuery(configAlert)
  157. }
  158.  
  159. // 送出對應的 CallbackQuery 回覆 & 對應指令的動作
  160. func (t *TeleBot) sendAnswerCallbackQuery() {
  161. for update := range t.updates {
  162. if update.Message == nil && update.CallbackQuery == nil {
  163. continue
  164. }
  165.  
  166. if update.Message != nil {
  167. switch update.Message.Text {
  168. case "/demo":
  169. t.demo(update.Message.Chat.ID)
  170. }
  171. }
  172.  
  173. if update.CallbackQuery != nil {
  174. chatID := update.CallbackQuery.Message.Chat.ID
  175. switch update.CallbackQuery.Data {
  176. case "ReplyKeyboardMarkup":
  177. go t.creatReplyKeyboardMarkup(chatID)
  178. go t.emptyAnswer(update.CallbackQuery.ID)
  179. case "removeReplyKeyboardMarkup":
  180. go t.removeReplyKeyboardMarkup(chatID)
  181. go t.emptyAnswer(update.CallbackQuery.ID)
  182. case "ReplyKeyboardMarkupOneTimeSize":
  183. go t.creatReplyKeyboardMarkupOnetimeResize(chatID)
  184. go t.emptyAnswer(update.CallbackQuery.ID)
  185. case "InlineKeyboardMarkup":
  186. go t.creatInlineKeyboardMarkup(chatID)
  187. go t.emptyAnswer(update.CallbackQuery.ID)
  188. case "ForceReply":
  189. go t.sendForceReply(chatID)
  190. go t.emptyAnswer(update.CallbackQuery.ID)
  191. case "Markdown_HTML":
  192. go t.sendMarkdown(chatID)
  193. go t.sendHTML(chatID)
  194. go t.emptyAnswer(update.CallbackQuery.ID)
  195. case "Photo":
  196. go t.sendPhoto(chatID)
  197. go t.emptyAnswer(update.CallbackQuery.ID)
  198. case "callback_data":
  199. config := tgbotapi.NewCallback(update.CallbackQuery.ID, "callbackAnswer")
  200. go t.botAPI.AnswerCallbackQuery(config)
  201. case "callback_data_alert":
  202. configAlert := tgbotapi.NewCallbackWithAlert(update.CallbackQuery.ID, "callbackAnswerAlert")
  203. go t.botAPI.AnswerCallbackQuery(configAlert)
  204. case "edited_text":
  205. editText := tgbotapi.NewEditMessageText(
  206. update.CallbackQuery.Message.Chat.ID,
  207. update.CallbackQuery.Message.MessageID,
  208. "edited text(有改到)",
  209. )
  210.  
  211. replyMarkup.InlineKeyboard[7][0].Text = "edited text(也可改 markup) 已修改"
  212.  
  213. editText.ReplyMarkup = &replyMarkup
  214.  
  215. go t.botAPI.Send(editText)
  216. go t.emptyAnswer(update.CallbackQuery.ID)
  217. case "edited_reply_markup":
  218. replyMarkup.InlineKeyboard[8][0].Text = "edited reply markup 已修改"
  219.  
  220. editReplyMarkup := tgbotapi.NewEditMessageReplyMarkup(
  221. update.CallbackQuery.Message.Chat.ID,
  222. update.CallbackQuery.Message.MessageID,
  223. replyMarkup,
  224. )
  225.  
  226. go t.botAPI.Send(editReplyMarkup)
  227. go t.emptyAnswer(update.CallbackQuery.ID)
  228. }
  229.  
  230. }
  231. }
  232. }
  233.  
  234. // 送出 markdown 格式
  235. func (t *TeleBot) sendMarkdown(chatID int64) {
  236.  
  237. markdown := `*bold text*"
  238. _italic text_"
  239. [inline URL](http://www.example.com/)"
  240. [inline mention of a user](tg://user?id=123456789)`
  241. markdown += "`inline fixed-width code`\n"
  242. markdown += "```block_language\npre-formatted fixed-width code block```"
  243. msg := tgbotapi.NewMessage(chatID, markdown)
  244. msg.ParseMode = tgbotapi.ModeMarkdown
  245. t.botAPI.Send(msg)
  246. }
  247.  
  248. // 送出 HTML 格式
  249. func (t *TeleBot) sendHTML(chatID int64) {
  250. htmlT := `<b>bold</b>, <strong>bold</strong>
  251. <i>italic</i>, <em>italic</em>
  252. <a href="http://www.example.com/">inline URL</a>
  253. <a href="tg://user?id=123456789">inline mention of a user</a>
  254. <code>inline fixed-width code</code>
  255. <pre>pre-formatted fixed-width code block</pre>`
  256. msg := tgbotapi.NewMessage(chatID, htmlT)
  257. msg.ParseMode = tgbotapi.ModeHTML
  258. t.botAPI.Send(msg)
  259. }
  260.  
  261. // 送出照片
  262. func (t *TeleBot) sendPhoto(chatID int64) {
  263. msg := tgbotapi.NewPhotoShare(chatID, "https://www.logaster.com/blog/wp-content/uploads/2013/06/jpg.png")
  264. msg.Caption = "caption"
  265.  
  266. t.botAPI.Send(msg)
  267. }
  268.  
  269. func main() {
  270. bot, err := tgbotapi.NewBotAPI("595702885:AAFIXbar3bl-a0H0YyWiKOvbX_u9X6s0FPs")
  271. if err != nil {
  272. log.Fatal(err)
  273. }
  274. bot.Debug = true
  275.  
  276. teleBot := TeleBot{
  277. botAPI: bot,
  278. }
  279.  
  280. u := tgbotapi.NewUpdate(0)
  281. u.Timeout = 60
  282.  
  283. teleBot.updates, err = bot.GetUpdatesChan(u)
  284. teleBot.sendAnswerCallbackQuery()
  285. }

留言