I want to create a bot to get rid of inactive users. The users information is logged into a database (MariaDB) upon joining the group. Every time they send a message, a timestamp (DATETIME) is updated in the database. The goal is to write a function which is able to recurrently remove people who have been inactive for a week or more.
I have written a function that would be able to do that (with the aid of some utility functions that I implemented to retrieve data from my DB):
async def RemoveUsers(update: Update) -> None:
= “TIMESTAMPDIFF(WEEK,LAST_TIMESTAMP,NOW())>1”
success, data = db.select(tablename, “*”, condition)
if success and len(data):
db.delete(tablename, condition)
for (uid, _) in data:
update.effective_chat.ban_member(uid, until_date = datetime.now() + timedelta(seconds=30))
scheduler = BackgroundScheduler()
remove_inactive = scheduler.add_job(RemoveUsers, “interval”, days = 1, args = (?, ))
if __name__ == "__main__":
scheduler.start()
application = ApplicationBuilder().token(API_KEY).build()
# Other handlers here...
application.run_polling(allowed_updates = Update.ALL_TYPES, drop_pending_updates = True)
But how am I supposed to pass the updates to the function? I don't want to set up a trigger event (like a command or new message or whatever). I would like this to run every day on its own. However, I cannot think of a way to do this. Is there a better way I could write this?
Any help would be appreciated!
Edit: I have thought about using JobQueue
from the python-telegram-bot
module. However, it still does not solve my problem, as the function itself would still need to an event to trigger it.
If it matters, I am using Python v3.9.5 and python-telegram-bot
v20.6.
As your RemoveUsers
function is supposed to be called in regular intervals rather than when an update is received, there is no use of having an Update
object as argument. What you really need in that function is the ID of the chat that you want to ban the users from. This can either be hard-coded or passed to RemoveUsers as argument.
Note that basically the same argument holds for PTBs JobQueue
(which is basically a wrapper around APScheduler). See also this wiki entry. Moreover, note that you don't need an update from Telegram to schedule a job via the JobQueue
- just run application.job_queue.run_daily(…)
after defining the application
.
Disclaimer: I'm currently the maintainer of python-telegram-bot
.