skip to Main Content

I am programming telegram-bot on Python, using aiogram and I need to delete user from database, when he delete the chat of the bot. I know that bot must receive some update, after user delete the chat of the bot. But my bot doesn’t receive nothing messages about it. I tried sending a message to the user who deleted the bot hoping to get an error and then process it and remove the user from the database but the messages are still sent without error. Also I read about method sendChatAction, that can solve it, but I didn’t find good examples with it. Any idea? P.S. I don’t need advice how to delete user from database, I want to know how to get errors with info that user deleted the chat of the bot, that I can process(exception handling)

2

Answers


  1. Chosen as BEST ANSWER

    Maybe it will help someone. I use Flask-SQLAlchemy for working with database and aiogram for bot-development. Make sure that you import this "from aiogram.utils.exceptions import BotBlocked" for handling exception about blocking bot by user.

    from bot_files.models import db, Users
    from aiogram.utils.exceptions import BotBlocked
    
    async def technical_works(bot):
        users = Users.query.all()
        for user in users:
            try:
                await bot.send_chat_action(user.telegram_id, action="typing")
            except BotBlocked as exception_info:
                db.session.delete(user)
                print("User is deleted")
    
        db.session.commit()
    

  2. You can use the Update.my_chat_member updates. Those will tell you when a user blocks your bot. Note that your bot does not get notified if the user simply clears the chat history or deletes the chat with your bot without blocking the bot.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search