python - 在 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'
解决方案
命令处理程序函数(在您的情况下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 中的电报机器人库的更多信息。
推荐阅读
- angularjs - 如何在 UI 引起的范围变量更改时重新加载指令的模板
- javascript - Angular/RxJS JSON 合并问题
- r - 部署应用程序时添加文件夹以在 RStudio Connect 中发布文件
- sql-server - 如何比较来自同一列和不同行但同一表的值?
- java - Spring Boot 执行器 + Kubernetes + 身份验证
- django - 如何将 Wagtail 表单用于无头 CMS?(没有模板)
- tcl - 如何循环直到我没有得到任何列出的选项作为提示
- javascript - 无法返回递归函数的最后结果
- python - 为什么我的代码没有退出无限循环?(Python)
- r - 计算时间序列中多年平均年增长率的函数