Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Having issues with processing user input in private chat#4656

Unanswered
YePererva asked this question inQ&A
Discussion options

Hello everyone,

I'm practicing in writing the bot for telegram group that functions on the following "algorythm'/conditions:

  • group is public, but each join requires approve of admin (to trigger request join event)
  • bot is already in group, as admin, with permission to add users via invite link
  • when new user requests to join the group (clicks "Apply to join the group"), bot should:
    • start a separate (private) chat with user, with asking to solve the riddle (a.k.a. captcha)
    • wait or user's input
    • compare it with expected result
      • if it is correct - approve
      • otherwise - decline
    • clear the private chat

I strugle with processing user input from the created private chat. My "bot" creates the private conversation with newcomer at join request, sends to the candidate the message, but doesn't accept the responce. The logging doesn't capture the fact that user is responding.

The currenc code is:

fromosimportgetenvfromenumimportEnumimportloggingfromtelegramimportUpdate,Botfromtelegram.extimportApplicationBuilder,CommandHandler,ChatJoinRequestHandler,ConversationHandler,MessageHandlerfromtelegram.extimportUpdater,ContextTypes,filterspassphrase=r"I want to join the channel"TOKEN=getenv('TELEGRAM_BOT_TOKEN')logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)classStates(Enum):WAITING_FOR_VERIFICATION=1asyncdefstart(update:Update,context:ContextTypes.DEFAULT_TYPE)->None:awaitupdate.message.reply_text(f'I am the bot, type me something!')# Processing user's join requestasyncdefjoin_request(update:Update,context:ContextTypes.DEFAULT_TYPE):logging.info(f"Captured attempt of user to join the group.\n\tUser :{update.effective_user.id}\n\tGroup:{update.effective_chat.id}")# sending user a private messageawaitcontext.bot.send_message(chat_id=update.effective_user.id,text=f"Dummy captcha. Just respond '{passphrase}' (without brackets) to this message"    )# Store chat join request details in context for later usecontext.user_data['join_request_chat_id']=update.effective_chat.idcontext.user_data['join_request_user_id']=update.effective_user.idreturnStates.WAITING_FOR_VERIFICATIONasyncdefverify_user_response(update:Update,context:ContextTypes.DEFAULT_TYPE):logging.info(f"Verification state triggered")logging.info(f"Update details:{update}")logging.info(f"Context user data:{context.user_data}")user_response=update.message.textlogging.info(f"Captured responce of user :{update.effective_user.id}\n\tResponce:{user_response}")ifuser_response==passphrase:# Approve join request using stored detailsawaitcontext.bot.approve_chat_join_request(chat_id=context.user_data['join_request_chat_id'],user_id=context.user_data['join_request_user_id']        )awaitupdate.message.reply_text("Verification successful! You'll be forwarded to group now.")logging.info(f"User passed the verification and added to group:\n\t{update.effective_user.id}")returnConversationHandler.ENDelse:# Decline join requestawaitcontext.bot.decline_chat_join_request(chat_id=context.user_data['join_request_chat_id'],user_id=context.user_data['join_request_user_id']        )awaitupdate.message.reply_text("Verification failed. You cannot join the group.")logging.info(f"User FAILED the verification and NOT added to group:\n\t{update.effective_user.id}")returnConversationHandler.ENDif__name__=='__main__':default_bot=Bot(TOKEN)logging.info("Succesfully retrieved token")app=ApplicationBuilder().bot(default_bot).build()logging.info("Succesfully created application")# Create a handler for private mesage to userconv_handler=ConversationHandler(entry_points=[ChatJoinRequestHandler(join_request)],states={States.WAITING_FOR_VERIFICATION: [# Only plain text, no edited messages, no commands in privat conversationMessageHandler(filters.TEXT&~filters.COMMAND&~filters.UpdateType.EDITED_MESSAGE,verify_user_response)            ]        },fallbacks=[]    )# Commandsapp.add_handler(CommandHandler("start",start))# Conversationsapp.add_handler(conv_handler)# Finally run!app.run_polling(allowed_updates=Update.ALL_TYPES)

Please, advice.

Used versions:

  • Python 3.13.1
  • python-telegram-bot 21.10
  • Running from under venv and VSCodium
You must be logged in to vote

Replies: 1 comment 2 replies

Comment options

The conversation handler is bound to the group chat, since per_chat is True. I would personally probably make a conversation handler with a message handler with a user filter to which I add a user id when I expect a captcha response (and remove when the conversation flow is done).

If you want to be able to debug these issues yourself, set the logging level to debug to see where the update is handled (or in this case, isn't)

You must be logged in to vote
2 replies
@YePererva
Comment options

Any example for such approach in WIKI or documentation?

@Poolitzer
Comment options

Not that I can think of no.

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
2 participants
@YePererva@Poolitzer

[8]ページ先頭

©2009-2025 Movatter.jp