go - 如何使用 Golang 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)
}
}
解决方案
问题是,当您启动回显服务器时,代码不会继续执行。
为了同时使用它们,您需要将它们中的每一个分离到不同的线程中,并停止您的程序以完成并停止一切。
最简单的方法是将 web server 和 telegram bot 分开,分别启动:
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()
}
但是如果最后一个停止了,你的整个程序和 echo 服务器也会停止。所以你必须恢复任何恐慌,不要让它停止。
推荐阅读
- android - 即使没有附加观察者,如何触发 LiveData SwitchMap
- css - 如何将 ng-5 范围滑块标签以角度放置到范围滑块指针中?
- asp.net-mvc-4 - 单层 MVC 路由
- php - 使用 get 方法更新数据
- r - 如何在 R 输出中获取科学计数法
- perl - 在 Perl 中使用 Mojolicious 通过 WebSocket 实现 Stomp 协议
- asp.net-mvc - 权限不足,无法完成操作使用 Azure Active Directory Graph Client API 添加新用户
- jsf-2.2 - 传递 Managedbean 属性
- python - 在 Python3 中使用请求下载图像
- office-js - Office Web 加载项 - 保存设置时出现内部错误