【问题标题】:Telegram Bot API Python - telegram.error.BadRequest: Chat not foundTelegram Bot API Python - telegram.error.BadRequest:找不到聊天
【发布时间】:2022-01-24 21:53:29
【问题描述】:

我想创建一个机器人来将我的文本发布到频道... 谁能帮我写代码?

这是我尝试过的代码:

import telegram

token = "5002307835:AAGOu4f******************"
chat_id = "1382******"


bot = telegram.Bot(token)


def send_message(message):
    return bot.send_message(chat_id,message)


send_message("HI")

但我收到此错误:telegram.error.BadRequest: Chat not found

我也试过了:chat_id = "-1382******"chat_id = -1382******chat_id = 1382******

【问题讨论】:

  • 你使用的是哪个模块?
  • 我正在使用 Telegram 模块。
  • 假设您使用的是python-telegram-bot,您似乎使用的是旧格式,see

标签: python telegram telegram-bot python-telegram-bot py-telegram-bot-api


【解决方案1】:

在没有" "的情况下使用它

例如

import telegram

chat_id = 1382******
token = "TOKEN"

如果不起作用,请尝试使用- 而不是"",它会起作用!

例如

import telegram
    
chat_id = -1382******
 token = "TOKEN"

【讨论】:

  • 感谢您的回复,但同样的错误弹出...
【解决方案2】:

频道 ID 通常以 -100 开头,所以

chat_id = -1001382******

将其设为整数

您还可以获取频道 ID,以普通用户身份在频道中发送消息并使用机器人进行处理。在 message.chat.id 你会看到正确的 id 或者只是将频道消息转发给机器人https://t.me/nguLikJSONbot

【讨论】:

    【解决方案3】:

    首先,你应该是一个频道的管理员,然后向它发送消息。 要将带有标题的文本、文件或照片发送给特定用户,目标用户应该是您的机器人的成员,然后将 chat_id 更改为电报中的用户 id。

    import telegram
    
    token = "5002307835:AAGOu4f******************"
    
    # "@{0}".format("botfather") ==> @botfather
    chat_id = "@{0}".format("your_channel_name")
    # For sending message to a specific user
    # chat_id = 18558...    
    
    bot = telegram.Bot(token)
    
    
    def send_message(message):
        return bot.send_message(chat_id, message)
    
    your_msg = "Hello"
    send_message(your_msg)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-01
      • 2021-06-20
      • 2020-04-14
      • 2019-10-01
      • 2021-04-03
      • 2019-05-23
      • 2016-12-05
      • 2018-01-28
      相关资源
      最近更新 更多