2023-11-06 10:55:39 +02:00
|
|
|
import asyncio
|
2023-11-05 03:01:33 +02:00
|
|
|
import random
|
2024-11-05 11:39:37 +02:00
|
|
|
import sys
|
2023-11-05 03:01:33 +02:00
|
|
|
|
|
|
|
import aiocron
|
|
|
|
import telethon
|
|
|
|
import pgbotlib.response
|
2024-10-23 14:26:09 +03:00
|
|
|
import pgbotlib.misc
|
2024-11-05 03:30:09 +02:00
|
|
|
import pytz
|
|
|
|
import yaml
|
2023-11-05 03:01:33 +02:00
|
|
|
|
|
|
|
|
|
|
|
class Cron:
|
|
|
|
def __init__(self,
|
|
|
|
config: dict,
|
|
|
|
client: telethon.TelegramClient,
|
|
|
|
responder: pgbotlib.response.Responder) -> None:
|
2024-11-10 00:37:41 +02:00
|
|
|
schedule_conf = config.get('schedule', 'sched.yml')
|
|
|
|
local_tz = config.get('timezone', 'UTC')
|
2024-11-05 11:39:37 +02:00
|
|
|
try:
|
|
|
|
self.tz = pytz.timezone(local_tz)
|
|
|
|
except pytz.exceptions.UnknownTimeZoneError as e:
|
|
|
|
sys.stderr.write(e)
|
|
|
|
self.tz = pytz.utc
|
2024-10-23 14:26:09 +03:00
|
|
|
with open(schedule_conf, 'r', encoding='utf-8') as data:
|
2023-11-05 03:01:33 +02:00
|
|
|
self.sched = yaml.safe_load(data.read())
|
|
|
|
self.responder = responder
|
|
|
|
self.client = client
|
|
|
|
|
|
|
|
def __mkjob(self, job: dict) -> callable:
|
|
|
|
tokens = frozenset(job['tokens'].split(','))
|
2024-11-09 22:01:38 +02:00
|
|
|
|
2023-11-05 03:01:33 +02:00
|
|
|
async def send_message() -> None:
|
|
|
|
if 'rand' in job:
|
2023-11-06 10:55:39 +02:00
|
|
|
wait_seconds = random.randint(0, job['rand']) * 60
|
|
|
|
await asyncio.sleep(wait_seconds)
|
2023-11-05 03:01:33 +02:00
|
|
|
message = self.responder.get_response(tokens)
|
|
|
|
message = self.responder.api_match(message, '')
|
2024-11-22 19:52:41 +02:00
|
|
|
message = await self.responder.rndm_tmpl(message, job['chat'])
|
2023-11-05 03:01:33 +02:00
|
|
|
await self.client.send_message(job['chat'], message)
|
|
|
|
return send_message
|
|
|
|
|
|
|
|
def plan(self) -> None:
|
|
|
|
for job in self.sched:
|
2024-11-05 03:30:09 +02:00
|
|
|
aiocron.crontab(job['cron'], tz=self.tz, func=self.__mkjob(job))
|