Skip to content

Instantly share code, notes, and snippets.

@danbst
Last active March 24, 2021 13:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danbst/4f9f731e2d83fc864b77c43be103c4fa to your computer and use it in GitHub Desktop.
Save danbst/4f9f731e2d83fc864b77c43be103c4fa to your computer and use it in GitHub Desktop.
# all users, key is chat.id
user_settings = {}
# user chat settings
class UserChat:
timers = {} # all timers. Key is timer ID, defined arbitrary
state = None
id = None # chat.id
def tick(self, current_time):
for timer_name, timer in self.timers.items():
timer.tick(self, current_time)
class Timer:
started_at = None
callback = None # function to callback, it's argument is UserChat object
period = None
pause = False
def tick(self, settings, current_time):
if not self.period or self.pause:
return
if current_time - self.started_at >= self.period:
print("Time to send message")
self.callback(settings)
self.started_at = current_time
# The cron thread
def queue_manager():
while True:
time.sleep(1)
now = datetime.now()
for _, settings in user_settings.items():
settings.tick(now)
wakeup_thread = threading.Thread(target=queue_manager)
wakeup_thread.start()
@bot.message_handler(commands=['on'])
def start_spam(message):
bot.send_message(message.chat.id, _TR("Starting periodic checks", key="GEN1"))
print(message.chat.id)
settings = user_settings.get(message.chat.id, None)
if not settings:
settings = UserChat()
settings.id = message.chat.id
user_settings[message.chat.id] = settings
timer = Timer()
settings.timers["spam"] = timer
timer.period = timedelta(minutes=...) # this can be later changed in my_function
timer.started_at = datetime.now()
timer.callback = my_function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment