使用golang实现telegram机器人

491次阅读
没有评论

共计 2226 个字符,预计需要花费 6 分钟才能阅读完成。

使用golang实现telegram机器人,这里提供简单的demo,可以根据内容开发适合的telegram机器人程序,例如抽奖或者群组加群验证机器人

telegram 的机器人接口很开放,使用简单,100%开放无限制,相对微信服务号、公众号好很多。用来做一些小应用也很方便。下面是使用golang sdk 开发telegram 机器人的经验。

telegram-bot-api

telegram-bot-api https://github.com/go-telegram-bot-api/telegram-bot-api197 是目前较好的sdk,使用方便。

获取机器人

机器人账号的获取直接跟BotFather 对话,token的或取、快捷命令的设置、机器人的信息设置等均可通过与BotFather 的对话完成。

使用golang实现telegram机器人

http poll 或 webhook

http poll 是客户端向telegram 服务器定时不断的请求,使用简单,一般用于测试,在本地机器即可完成。老外们的经验说,这种模式经常卡,导致业务处理延迟。

webhook 是telegram 服务器主动发消息到自己指定的网址,一般用于真实环境,而且对外需要HTTPS / TLS 协议,用户延迟小、并发高。

http poll 模式

package main

import (
  "log"

  "github.com/go-telegram-bot-api/telegram-bot-api"
)

func main() {
  bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
  if err != nil {
    log.Panic(err)
  }

  bot.Debug = true

  log.Printf("Authorized on account %s", bot.Self.UserName)

  u := tgbotapi.NewUpdate(0)
  u.Timeout = 60

  updates, err := bot.GetUpdatesChan(u)

  for update := range updates {
    if update.Message == nil { // ignore any non-Message Updates
      continue
    }

    log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)

    msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
    msg.ReplyToMessageID = update.Message.MessageID

    bot.Send(msg)
  }
}

 

webhook 模式

package main

import (
  "log"
  "net/http"

  "github.com/go-telegram-bot-api/telegram-bot-api"
)

func main() {
  bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
  if err != nil {
    log.Fatal(err)
  }

  bot.Debug = true

  log.Printf("Authorized on account %s", bot.Self.UserName)

  _, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
  if err != nil {
    log.Fatal(err)
  }
  info, err := bot.GetWebhookInfo()
  if err != nil {
    log.Fatal(err)
  }
  if info.LastErrorDate != 0 {
    log.Printf("Telegram callback failed: %s", info.LastErrorMessage)
  }
  updates := bot.ListenForWebhook("/" + bot.Token)
  go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)

  for update := range updates {
    log.Printf("%+v\n", update)
  }
}

 

 

可以使用自签名的证书;也可以使用前端代理,证书让前端处理,比如 Caddy、nginx ;也可以使用 Let’s Encrypt 。区别在于生成 WebhookConfig 的方式:

 

Go: 使用自签名证书
1
2
tgbotapi.NewWebhookWithCert("https://example.com/"+bot.Token, "cert.pem")
tgbotapi.NewWebhook("https://example.com/"+bot.Token)

 

相关项目

正文完
 
admin
版权声明:本站原创文章,由 admin 2021-09-20发表,共计2226字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码