vendredi 12 juin 2020

Design pattern for telegram bot

I am currently working on a telegram bot that is going to have many functions and is going to be quite complicated. I currently finished one feature of the bot and the code is already unmanageable.

For example, the conversation handler currently looks like this:

# BOT STATES
FIRST, SECOND, THIRD, FOURTH, FIFTH, SIXTH = range(6)
# Callback data
ONE, TWO, THREE, FOUR, CANCEL = range(5)


conv_handler = ConversationHandler(
    entry_points=[CommandHandler('start', self.start)],
    states={
        FIRST: [
            CallbackQueryHandler(
                self.one, pattern='^' + str(ONE) + '$'),
            CallbackQueryHandler(
                self.cancel, pattern='^' + str(CANCEL) + '$'),
        ],
        SECOND: [
            CallbackQueryHandler(
                self.two, pattern='^' + str(TWO) + '$'),
            # extra handler here
            CallbackQueryHandler(
                self.five, pattern='^' + str(THREE) + '$')
        ],
        THIRD: [
            MessageHandler(Filters.text, self.three)
        ],
        FIFTH: [
            MessageHandler(Filters.text, self.six)
        ],
        FOURTH: [
            MessageHandler(Filters.text, self.four)
        ],
        SIXTH: [
            MessageHandler(Filters.text, self.seven)
        ]

    },
    fallbacks=[CommandHandler('cancel', self.cancel)]
)

Where I have to keeping adding more callback data and more states for the bot as the bot gets more and more complicated.

I also have to keep adding more functions to the same .py file to handle use as callback functions:

def six(self, update, context):
    update.message.reply_text("Enter name")
    return SIXTH

Is there a better way to manage my code? Or a recommended design pattern that I can use to have a easier time managing my project?

Aucun commentaire:

Enregistrer un commentaire