Skip to content

Commit 5a4c8c9

Browse files
committed
fix(crons): ensure felizdia runs exactly once per day
- Leveraged the new 'locks' table to record the execution of the felizdia cron for the current date. - Persists the skip/send state immediately, so subsequent retries on the same day won't trigger the message again. - Helps prevent duplicate daily greetings on flaky cron schedules or manual retries.
1 parent 40416c1 commit 5a4c8c9

1 file changed

Lines changed: 23 additions & 1 deletion

File tree

handlers/crons.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010
logger = logging.getLogger("DCUBABOT")
1111
bsasTz = pytz.timezone("America/Argentina/Buenos_Aires")
1212

13+
from handlers.db import get_session
14+
from models import Lock
15+
1316
def felizdia_text(today):
1417
meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
1518
"Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"]
@@ -23,9 +26,28 @@ def felizdia_text(today):
2326
return "Feliz " + dia + " de " + mes
2427

2528
async def felizdia(context: ContextTypes.DEFAULT_TYPE):
29+
today = datetime.date.today()
30+
lock_key = f"felizdia_{today.year}_{today.month}_{today.day}"
31+
32+
with get_session() as session:
33+
existing = session.query(Lock).filter_by(key=lock_key).first()
34+
if existing:
35+
logger.info(f"felizdia already executed today ({today}). Skipping.")
36+
return
37+
38+
new_lock = Lock(key=lock_key, expires_at=datetime.datetime.utcnow() + datetime.timedelta(days=2))
39+
session.add(new_lock)
40+
try:
41+
session.commit()
42+
except Exception as e:
43+
session.rollback()
44+
logger.error(f"Failed to acquire felizdia lock: {e}")
45+
return
46+
2647
if random.uniform(0, 7) > 1:
48+
logger.info(f"felizdia skipped by random chance today ({today}).")
2749
return
28-
today = datetime.date.today()
50+
2951
chat_id = DC_GROUP_CHATID
3052
await context.bot.send_message(chat_id=chat_id, text=felizdia_text(today))
3153

0 commit comments

Comments
 (0)