Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

How to nest a conversation with in another command telegram-bot-python

$
0
0
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ConversationHandlerTOKEN = "TOKEN"BOT_USERNAME = "BOT"# Use a set to keep track of registered usersregistered_users = set()async def start_command(update, context):    user = update.message.from_user    # Check if the user is already registered    if user.id in registered_users:        await context.bot.send_message(chat_id=update.effective_chat.id,                                       text=f"Welcome back, {user.first_name}!")    else:        await context.bot.send_message(chat_id=update.effective_chat.id, text="Let's make your account.")        return await start(update, context)async def error(update, context):    print(f'Update {update} caused error {context.error}')# StatesFIRST, SECOND = range(2)async def start(update, context) -> int:    await update.message.reply_text("Hello! This is a conversation bot. What's your name?")    return FIRSTasync def get_name(update, context) -> int:    user_name = update.message.text    context.user_data['name'] = user_name    await update.message.reply_text(f"Nice to meet you, {user_name}! What's your age?")    return SECONDasync def get_age(update, context) -> int:    user_age = update.message.text    await update.message.reply_text(f"Thanks for sharing! Your age is {user_age}.")    return ConversationHandler.ENDasync def cancel(update, context) -> int:    await update.message.reply_text("Conversation canceled.")    return ConversationHandler.ENDconv_handler = ConversationHandler(    entry_points=[CommandHandler('start', start)],    states={        FIRST: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_name)],        SECOND: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_age)],    },    fallbacks=[CommandHandler('cancel', cancel)],)if __name__ == "__main__":    print("Starting Bot")    app = Application.builder().token(TOKEN).build()    app.add_handler(CommandHandler('start', start_command))    app.add_handler(conv_handler)    app.add_error_handler(error)    print("Polling...")    app.run_polling(poll_interval=3)`

I want to start the conversation from my start_command after checking if user has registered already or not. The problem I am having is I am unable to figure out how to start the conv_handler and keep the states changing until the conversation is finished within the command start_command.

I looked at the documentation and could not find anything about nested conversation handlers inside other commands or functions. I am able to start on its own by giving its own command but I want to achieve this by making in initiate the start_command function.


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>