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