【问题标题】:Telegram bot does nothing after one reply电报机器人在一次回复后什么都不做
【发布时间】:2018-10-01 01:51:05
【问题描述】:

我是 python 新手,正在尝试在电报上创建一个对话机器人,询问用户的性别和年龄。但是,我的机器人在获得用户年龄后没有做任何事情。 我的性别和年龄函数:

def gender(bot, update):
# Get gender from user
user = update.message.from_user
logger.info("Gender of %s: %s", user.first_name, update.message.text)
update.message.reply_text(
    "<TEXT>",
reply_markup=ReplyKeyboardRemove())

def age(bot, update):
# Get age from user
user = update.message.from_user
logger.info("Age of %s: %s", user.first_name, update.message.text)
update.message.reply_text(
        "<TEXT>"
)
return ConversationHandler.END

def skip_age(bot, update):
# /skip command
user = update.message.from_user
logger.info("User %s did not specify age", user.first_name)
update.message.reply_text(
    "<TEXT>"
)
return ConversationHandler.END

主函数中的命令处理程序和消息处理程序:

 conv_handler = ConversationHandler(
    entry_points=[CommandHandler('chat', chat)],

    states={
        GENDER: [RegexHandler('^(Boy|Girl|Other)$', gender)],

        AGE: [MessageHandler(Filters.text, age),
            CommandHandler('skip', skip_age)]
    },

    fallbacks=[CommandHandler('cancel', cancel)]
)

dispatcher.add_handler(conv_handler)

bot的日志(将日志中的token重命名):

2018-09-30 21:20:33,977 - __main__ = INFO - Gender of Jan: Boy
2018-09-30 21:29:00,826 - telegram.vendor.ptb_urllib3.urllib3.connectionpool = WARNING - Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(<telegram.vendor.ptb_urllib3.urllib3.connectionpool.HTTPSConnectionPool object at 0x7fafec6b5ef0>, 'Connect timed out. (connect timeout=5.0)')': /bot<TOKEN>/getUpdates

完整代码的py文件链接:https://github.com/TryingOutSomething/testing/blob/master/testing.py

【问题讨论】:

    标签: python telegram-bot python-telegram-bot


    【解决方案1】:

    您没有将函数添加到处理程序中。

    在第 109 行,你有这个:

    # Help command
    help_command = CommandHandler('help', help)
    dispatcher.add_handler(help_command)
    

    即添加函数help作为handler,来处理命令。您还需要将函数添加为处理程序,您只需复制粘贴这些行并将'help' 替换为您写入机器人的内容,并将help 替换为您想要的函数名称。

    例子:

    # Ask my age command
    the_age_command = CommandHandler('age', age)
    dispatcher.add_handler(the_age_command)
    

    【讨论】:

    • 感谢您的建议,它让我意识到我的错误在哪里!原来我在gender函数后没有返回AGE
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2020-12-16
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多