CommandHandler在Telegram机器人程序库中不工作

2024-04-24 16:16:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用来自python-telegram-bot==7.0.1CommandHandler,但是它没有做任何我期望的事情。在

实际上,我无法得到任何状态:

# -*- coding: utf-8 -*-

from __future__ import unicode_literals, division, print_function
import logging
import telegram
from telegram.ext import CommandHandler, CallbackQueryHandler, MessageHandler, ConversationHandler, RegexHandler
from telegram.ext import Updater, Filters

# Set up Updater and Dispatcher

updater = Updater(TOKEN)
updater.stop()
dispatcher = updater.dispatcher

# Add logging

logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.WARNING)

TIME, NOTIME = range(2)


def whiteboard(bot, update):
    print(1)
    bot.sendMessage(text="Send update", chat_id=update.message.chat.id)
    bot.sendMessage(text=update.message.text, chat_id=update.message.chat.id)
    print(type(TIME))
    return TIME


def whiteboard_update(bot, update):
    print(2)
    bot.sendMessage(text=update.message.text, chat_id=update.message.chat.id)
    return TIME


def cancel(bot, update):
    print(3)
    bot.sendMessage(text=update.message.text, chat_id=update.message.chat.id)
    bot.sendMessage(text="Это не время, а что то еще...", chat_id=update.message.chat.id)
    return NOTIME


def error(bot, update, error):
    logging.critical('Update "%s" caused error "%s"' % (update, error))


def main():

    whiteboard_handler = CommandHandler("whiteboard", whiteboard)
    dispatcher.add_handler(whiteboard_handler)

    conv_handler = ConversationHandler(
        entry_points=[CommandHandler("whiteboard", whiteboard)],
        states={
            TIME: [RegexHandler('^[0-9]+:[0-5][0-9]$', whiteboard_update), CommandHandler('cancel', cancel)],
            NOTIME: [MessageHandler(Filters.text, cancel), CommandHandler('cancel', cancel)]
        },
        fallbacks=[CommandHandler('cancel', cancel)],
        )
    dispatcher.add_handler(conv_handler)

    # log all errors
    updater.dispatcher.add_error_handler(error)

    # Poll user actions

    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()

所以,/whiteboard返回它必须返回的内容,但是任何文本和/或时间(例如1:11)都不能让我找到所需的函数。在


Tags: textimportidmessageloggingbotchatupdate
1条回答
网友
1楼 · 发布于 2024-04-24 16:16:54

只执行任何组中可执行的第一个处理程序,而不执行同一组的其他处理程序

在您的示例中,commandHandler和conversationHandler位于同一组中,当用户键入命令时,只执行commandHandler,而不执行conversationHandler(每个组只执行一个处理程序(如果它们被触发的话),顺序是您编写命令的顺序)。在

如果要同时运行这两个程序,可以将它们分成两个不同的组:

 dispatcher.add_handler(whiteboard_handler, -1)

添加'-1'作为参数,说明它属于前一组处理程序。在

或者,如果不想将它们分成两个组,可以使用flow control,但到目前为止,它应该只在主分支中合并。要使用它,必须引发“DispatcherHandlerContinue”异常

相关问题 更多 >