python-在频道中出现电报机器人错误

python-telegram-bot error when in Channel

我刚刚创建了我的第一个 bot,它在组中工作得很好,当我向它发送消息时,但是,当我将它添加到频道并授予它所有权限时,它不起作用。 echo message函数报错caused error 'NoneType' object has no attribute 'text'.

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import MessageEntity, InlineQueryResultArticle, InputTextMessageContent

def echo(update, context): # this is from the documentation
    context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)

def error(update, context):
    print(f'Error {update} caused error {context.error}')

def main():
    updater = Updater(API)
    dp = updater.dispatcher
    
    #Echo message
    echo_handler = MessageHandler(Filters.text & (~Filters.command), echo)
    dp.add_handler(echo_handler)

    #Handle errors
    dp.add_error_handler(error)

    updater.start_polling()
    updater.idle()

main()

对于频道帖子,它是 update.channel_post 而不是 update.message.text。或者,如果您不想区分频道帖子、消息和已编辑的 messages/channel 帖子,可以使用 update.effective_message。

def echo(update, context):
    context.bot.send_message(
    chat_id=update.effective_chat.id, text=update.effective_message)