繁体   English   中英

python-telegram-bot 中的 chat_id 错误

[英]chat_id Eror in python-telegram-bot

我想在电报机器人中制作键盘,但找不到chat_id 如何解决?

代码:

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

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

def service_keyboards(bot,update) :
    chat_id = update.effective_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 行,开始 chat_id = update.message.chat_id AttributeError: 'CallbackContext' object 没有属性 'message'

您可以从传入消息的 JSON 有效负载中获取chat_id

def get_chat_id(update, context):
  chat_id = -1

  if update.message is not None:
    # from a text message
    chat_id = update.message.chat.id
  elif update.callback_query is not None:
    # from a callback message
    chat_id = update.callback_query.message.chat.id

return chat_id

chat_id = get_chat_id(update, context)
bot.sendMessage(chat_id, 'etc...'

这就是我编码我的机器人的方式:

def start (update, context):
    user = update.message.from_user
    chat_id = user['id']
    ##foo
 
def service_keyboards (update, context):
    user = update.message.from_user
    chat_id = user['id']
    ##foo

试试这个,让我知道它是否有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM