首页 > 解决方案 > 如何使用 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)
    }
}

标签: gotelegram-botgo-echo

解决方案


问题是,当您启动回显服务器时,代码不会继续执行。

为了同时使用它们,您需要将它们中的每一个分离到不同的线程中,并停止您的程序以完成并停止一切。

最简单的方法是将 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 服务器也会停止。所以你必须恢复任何恐慌,不要让它停止。


推荐阅读