skip to Main Content

I have telegram channel/group where i add members manually and i remove/kick users manually after one/two/three month. Is there any way to do this task automatically, I mean can we remove/kick user from channel/group automatically or by scheduling?

Any sample python code will help for understanding. Thank you…!

3

Answers


  1. you can schedule any action using python-telegram-bot,
    and can also schedule kick_chat_member
    Read Full Documentation Here
    https://python-telegram-bot.readthedocs.io

    Login or Signup to reply.
  2. You can ban a user from a group for a predefined amount of time using kick_chat_member. The function will return True if the user is successfully removed.

            # kick a user from a group
            m = context.bot.kick_chat_member(
            chat_id="-1001572091573", 
            user_id='123456789',
            timeout=int(time.time() + 86400)) # expiry after 24h
    

    You need to obtain the chat_id of the Group chat and the user_id of the user to ban: you can do that by intercepting events like new_chat_members which provides all the information when a new user is added to the group

    # handler to process new member event
    updater.dispatcher.add_handler(
         MessageHandler(Filters.status_update.new_chat_members, new_member))
    
    def new_member(update, context):
      logging.info(f"new_member : {update}")
    
      chat_id = update.message.chat.id
      user_id = update.message.from_user.id
    

    The bot needs to be able to perform this type of operation, so make sure it is an admin or has the ban user privilege.

    Scheduling

    Scheduling operations like that are (obviously) not covered by the Telegram BOT API, but it is logic that the application/chatbot should implement.

    You need to take care of the following:

    • obtain the chat_id (see above) and save it for later user
    • save member IDs (see above) when they join the group, together with the date (to be able to establish how long they have been part of the group)

    A good way to implement tasks in Python is to use Advanced Python Scheduler

    from apscheduler.schedulers.background import BackgroundScheduler
    
    scheduler = BackgroundScheduler()
    
    scheduler.add_job(ban_members, 'interval', days=30) 
    scheduler.start()
    
    def ban_members():
    
       # get users from DB
       # establish who needs to be removed
       # call kick_chat_member
    
    Login or Signup to reply.
  3. Due to Official Telegram Bot API docs, it’s not possible to schedule a banChatMember.

    What you can do is to register users in a database including a field called kick_date and have cron jobs run a script to check if their kick_date is before current time and use banChatMember to ban them.


    I didn’t post any codes since your question;

    1. looked like as if you are looking for a method in Telegram’s API.
    2. You haven’t mentioned which Python Telegram bot API you want to use.
    3. Giving code sample for your question (ignoring both 1 & 2 reasons), would be a project for itself since it consists of different sections of code. I suggest you divide your question to these parts and search/ask about them:
    • How to store current members in a database?
    • How to store new members in a database?
    • How to run a script on Python periodically?
    • How to kick members by id?

    I’m gonna give you the steps you can take to achieve your goal.

    1. Upon adding a member to your group you will get an Update from Telegram including the field new_chat_members:
    
    {
          "update_id": 436022554,
          "message": {
            "message_id": 259,
            "from": {
              "id": <user_id>,
              "is_bot": false,
              "first_name": <user_first_name>,
              "username": <user_username>,
              "language_code": "en"
            },
            "chat": {
              "id": <chat_id>,
              "title": <chat_title>,
              "type": "group",
              "all_members_are_administrators": true
            },
            "date": 1633373553,
            "new_chat_members": [
              {
                "id": <chat_member_id>,
                "is_bot": false,
                "first_name": <chat_member_first_name>,
                "username": <chat_member_username>
              }
            ]
          }
        }
    
    1. You’re gonna iterate through new_chat_members and add them to your database along with a kick_at time.

    2. Write a script to get your members from the database and check if it’s time to kick them. (kick_at < now) and use banChatMember for that matter.

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