【问题标题】:Telegram can get chat by id, can't by @name: Chat not foundTelegram 可以通过 id 进行聊天,不能通过 @name:Chat not found
【发布时间】:2019-08-22 02:48:15
【问题描述】:

所以我使用@BotFather 制作了一个机器人,并从我的帐户中向它发送了消息。然后我使用@userinfobot 找到了我的帐户 ID 并发送了这个请求:

https://api.telegram.org/botTOKEN/sendMessage?chat_id=id&text=test 它工作正常ok:true

但是,如果我尝试使用 @username 而不是 id:

https://api.telegram.org/botTOKENg/sendMessage?chat_id=@username&text=test

我收到一个错误:

{
    "ok": false,
    "error_code": 400,
    "description": "Bad Request: chat not found"
}

查看我过去的代码,@ 方法以前对我有用。情况有变化吗?

【问题讨论】:

    标签: telegram telegram-bot python-telegram-bot


    【解决方案1】:

    你必须使用id,你不能使用用户名。

    将用户名作为参数仅适用于公共频道。

    看看Telegram Bot API documentation

    说明
    目标频道的目标聊天或用户名的唯一标识符(格式为@channelusername

    【讨论】:

    • 我看了看,它说你可以传递一个@username 字符串。我之前向这样的用户发送消息。
    • 不,您确实读错了@parsecer“目标聊天的唯一标识符”“目标聊天的唯一标识符”。
    【解决方案2】:

    您不能使用您应该使用机器人更新的用户名发送消息并获取 from_user 或 effective_user 然后访问 id (chat_id)

    • 您无法向从未使用过您的机器人的用户发送消息。

    用户在您的机器人中执行某些操作后,您现在可以找到并发送您想要的所有内容

    import requests
    from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
    
    def pure_api(chat_id, text):
        # don't forget to set bot + TOKEN
        r = requests.get(f"https://api.telegram.org/botTOKEN/sendMessage?chat_id={chat_id}&text={text}")
        print(r.json())
    
    def start(bot, update):
        user_id = update.effective_user.id
        print(user_id)
        bot.send_message(user_id, "any message you want")
        # or 
        update.message.reply_text("any message you want")
        pure_api(user_id, "any message you want")
    
    
    def main():
        """Start the bot."""
        updater = Updater(TOKEN)
        dp = updater.dispatcher
        dp.add_handler(CommandHandler("start", start))
        updater.start_polling()
        updater.idle()
    
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

      【解决方案3】:

      您需要更改:chat_id = @myname from a number de id。 例如:chat_id = 43672587。 你得到的这个数字。 1.- 输入电报 2.- 搜索@userinfobot 并输入 3.-在自动你得到你的ID

      【讨论】:

      猜你喜欢
      • 2017-04-15
      • 2018-01-28
      • 2015-11-12
      • 2013-05-15
      • 2018-09-04
      • 2019-08-01
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多