首页 > 解决方案 > 在 python-telegram-bot 中查找 chat_id

问题描述

我试图用python在电报中创建一个机器人,但我找不到chat_id。我应该怎么办?

我的代码:

from telegram.ext import Updater, CommandHandler
from telegram import ReplyKeyboardMarkup

updater = Updater(Token)
def start(update, _) :
    update.message.reply_text('Hello {}'.format(update.message.chat.first_name))

def service_keyboards(bot,update) :
    chat_id = update.message.chat_id
    keyboard = [['Send Video'], ['Send Music']]
    bot.sendMessage(chat_id, 'Plese choose an item.', reply_markup = ReplyKeyboardMarkup(keyboard))

start_command = CommandHandler('start' , start)
service_command = CommandHandler('service' , service_keyboards)
updater.dispatcher.add_handler(start_command)
updater.dispatcher.add_handler(service_command)
updater.start_polling()
updater.idle()

错误:

没有注册错误处理程序,记录异常。回溯(最近一次调用):文件“c:\users\Ghazal\appdata\local\programs\python\python38\lib\site-packages\telegram\ext\dispatcher.py”,第 442 行,在 process_update handler.handle_update (更新、自我、检查、上下文)文件“c:\users\Ghazal\appdata\local\programs\python\python38\lib\site-packages\telegram\ext\handler.py”,第 160 行,在 handle_update 中返回 self .callback(update, context) 文件“”,第 9 行,在 start chat_id = update.message.chat_id AttributeError: 'CallbackContext' object has no attribute 'message'

标签: pythontelegramtelegram-botpython-telegram-bot

解决方案


命令处理程序函数(在您的情况下start是函数)接受两个参数,第一个是Update,第二个是CallbackContext

您在函数中放错了更新参数。它应该是第一位的:

def echo(update: Update, _: CallbackContext) -> None:
    """Echo the user message."""
    update.message.reply_text(str(update.message.chat_id) + ": " + 
update.message.text)

您的错误消息清楚地表明您正在尝试访问 CollbackContex 的 message 属性。而 CallbackContext 没有。

请参阅这些示例以了解有关 python 中的电报机器人库的更多信息。


推荐阅读