【问题标题】:How to trigger telegram bot to send a message如何触发电报机器人发送消息
【发布时间】:2019-10-30 11:24:15
【问题描述】:

我不知道如何用电报机器人诱导(触发)本地服务器向频道发送消息。

例如,从网站向用户发送通知,用户已在该网站注册并连接了电报。我们将假设用户已经开始与 bot 对话并准备好接收来自它的消息。

我有一个单独的服务器,可以使用机器人向服务器发送请求,但我不明白如何在这个电报机器人服务器上接收和处理请求。

我正在使用 go telegram-bot-api 库,此时服务器使用长轮询方法而不是 webhook。因此它通过更新通道接收一些电报 API 事件。

我的代码只是 telegram-bot-api golang lib git repo 中示例的副本:

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)
    }
}

我希望我的机器人从第三方服务中被诱导(触发),从中获取一些数据,生成一条消息并通过聊天将其发送给用户。

此时我的实现是:bot通过更新通道从用户获取消息,处理并发送回复消息。

【问题讨论】:

  • 你尝试了什么?你能显示一些代码吗?我们不会为您编写机器人代码。

标签: go telegram-bot


【解决方案1】:

telegram-bot-api 使用 HTTP POST 请求将消息发送到 Telegram Bot API。

在此处查看更多信息:https://github.com/go-telegram-bot-api/telegram-bot-api/blob/master/bot.go#L71

您可以简单地在服务器逻辑中初始化另一个BotAPI 实例并使用它来异步发送消息。 它不会影响活动的长轮询或 webhook。

【讨论】:

    猜你喜欢
    • 2017-03-19
    • 2017-09-01
    • 2020-12-10
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 2018-02-25
    • 2019-12-31
    • 2017-05-11
    相关资源
    最近更新 更多