1

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...!

VikaS GuttE
  • 1,636
  • 2
  • 14
  • 38

3 Answers3

1

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
Beppe C
  • 11,256
  • 2
  • 19
  • 41
  • They didn't mean banning for a specific period of time. They meant scheduling a ban. So if a user joins the group, they get banned after a month. – Ali Padida Oct 01 '21 at 17:31
  • I have added sample code to implement background task banning users after a given period. Note: this is custom application logic so it is not part of the Telegram Chatbot API or event the REST Telegram. – Beppe C Oct 02 '21 at 09:29
  • @VikaS GuttE I think my answer should provide you with the solution you are looking for (if you use the Python Telegram API library). I can elaborate/clarify further if needed. – Beppe C Oct 03 '21 at 14:58
  • @BeppeC - I tried above one but not sure somthing is wrong, also i am not sure where and how i can store the user details. do you have any working code or sample example? I am trying this on https://replit.com/ for your infomation. Thank you for your help. – VikaS GuttE Oct 04 '21 at 13:39
  • You can look at https://github.com/gcatanese/SampleTelegramQuiz. It is a Sample Telegram Chatbot with the code to perform various replies. Once you get the `user_id` and the `chat_id` you need to store them somewhere (DB, file) so the background task can use them when it runs – Beppe C Oct 04 '21 at 13:58
  • You could try first to implement the backend task hardcoding the `chat_id` and the `user_id`, once it works you can solve the next problem (where to store these IDs and how to fetch them) – Beppe C Oct 04 '21 at 13:59
1

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.

Ali Padida
  • 1,763
  • 1
  • 16
  • 34
  • @Ali can you help me with any sample code. Thank you for your help...! – VikaS GuttE Oct 03 '21 at 05:24
  • @VikaSGuttE I updated the answer with more details. Feel free to ask a more detailed question to get an exact sample code. As you saw 2 people were confused and gave wrong and misleading answers to your question, which is why I think I'm not the only one with this thought that the question is not specific. – Ali Padida Oct 04 '21 at 19:20
0

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