telegram bot api
v5.5.1
所有方法都是相当自我解释的,阅读Godoc页面应解释一切。如果不清楚,请打开问题或提交拉动请求。
网站上有更多教程和高级信息,go-telegram-bot-api.dev。
该项目的范围只是为API提供包装器,而没有任何其他功能。还有其他项目可以用插件和命令处理程序创建一些东西,而无需自己设计所有这些项目。
如果您想提出问题或讨论发展,请加入开发小组。
首先,确保已安装库,并通过运行go get -u github.com/go-telegram-bot-api/telegram-bot-api/v5进行最新。
这是一个非常简单的机器人,仅显示任何获得的更新,然后将其回复到该聊天。
package main
import (
"log"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
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 := bot . GetUpdatesChan ( u )
for update := range updates {
if update . Message != nil { // If we got a message
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 )
}
}
}如果您需要使用Webhooks(如果您想在Google App Engine上运行),则可以使用略有不同的方法。
package main
import (
"log"
"net/http"
"github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
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 )
wh , _ := tgbotapi . NewWebhookWithCert ( "https://www.example.com:8443/" + bot . Token , "cert.pem" )
_ , err = bot . Request ( wh )
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 )
}
}如果需要,您可能会生成一个自签名的证书,因为这需要HTTPS / TLS。上面的示例告诉电报,这是您的证书,即使没有正确签名,也应该信任它。
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3560 -subj "//O=OrgCN=Test" -nodes
现在,让我们加密,您可能希望在那里生成免费的TLS证书。