我想将“telegram bot”与“echo框架”一起使用(当服务器启动时,echo和telegram bot一起工作)。我使用了下面的代码,但是当我运行该代码时,电报机器人没有启动。
我的main.go:
package main
import (
"database/sql"
"log"
"net/http"
"strings"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/labstack/echo"
_ "github.com/mattn/go-sqlite3"
)
func main() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
_ = e.Start(":1323")
db, err := sql.Open("sqlite3", "./criticism.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
bot, err := tgbotapi.NewBotAPI("")
if err != nil {
log.Fatal(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 {
continue
}
gp_msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Hi")
bot.Send(gp_msg)
}
}
最佳答案
问题是,当您启动回显服务器时,代码不会再继续。
为了使用它们,您需要将它们分成不同的线程,并停止您的程序以完成并停止一切。
最简单的方法是将网络服务器和电报机器人分开并分别启动:
func StartEcho() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
_ = e.Start(":1323")
}
func StartBot() {
bot, err := tgbotapi.NewBotAPI("")
if err != nil {
log.Fatal(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 {
continue
}
gp_msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Hi")
bot.Send(gp_msg)
}
}
然后给他们打电话:
func main() {
# Start the echo server in a separate thread
go StartEcho()
db, err := sql.Open("sqlite3", "./criticism.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
# Start the bot in a separate thread
go StartBot()
# To stop the program to finish and close
select{}
# You can also use https://golang.org/pkg/sync/#WaitGroup instead.
}
或者您可以只在主线程中运行最后一个:
func main() {
# Start the echo server in a separate thread
go StartEcho()
db, err := sql.Open("sqlite3", "./criticism.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
# Start the bot
StartBot()
}
但是如果最后一个停止,您的整个程序和回显服务器也会随之停止。所以你必须恢复任何 panic 并且不要让它停止。
关于go - 如何与 Golang echo 框架和 Telegram 机器人配合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59247645/