问题描述
我的电报机器人在个人聊天中回答,但不在群聊中回答。我找不到问题所在。 我的代码片段:
@app.route('/{}'.format(TOKEN),methods=['POST'])
def respond():
# retrieve the message in JSON and then transform it to Telegram object
update = telegram.Update.de_json(request.get_json(force=True),bot)
# get the chat_id to be able to respond to the same user
chat_id = update.message.chat.id
# Telegram understands UTF-8,so encode text for unicode compatibility
text = update.message.text
if text == '/start':
response = send_welcome()
bot.sendMessage(chat_id=chat_id,text=response)
elif 'discord' in text.split():
response = send_discord()
bot.sendMessage(chat_id=chat_id,text=response)
elif 'edeka' in text.split():
response = send_edeka()
bot.sendMessage(chat_id=chat_id,text=response)
elif 'random' in text.split():
response = send_random()
bot.sendMessage(chat_id=chat_id,text=response)
elif 'metro' in text.split():
response = send_metro()
bot.sendMessage(chat_id=chat_id,text=response)
elif text == '/help':
response = send_help()
bot.sendMessage(chat_id=chat_id,text=response)
elif text == 'Good bot':
response = 'Önemli degil kanka'
bot.sendMessage(chat_id=chat_id,text=response)
return 'ok'
我在 heroku 中收到 text.split() 的错误消息,但仅来自群聊。
解决方法
# get the chat_id to be able to respond to the same user
chat_id = update.message.chat.id
这是来自发送消息的人。因此,如果有人在群聊中针对您的机器人,您将回复他的个人 ID。
考虑使用
chat_id = update.message.from.id
这是发送消息的聊天,在这种情况下,它可能是您要回复的群聊。
为了更好地了解不同的 ID,请查看例如 this answer