Skip to content

Commit 7090d22

Browse files
committed
fix(groups): handle telegram rate limits and add revive groups script
- Differentiate between Forbidden/BadRequest (bot kicked/chat deleted) and Rate Limits (RetryAfter) in update_group_url. - Ignore Listables without chat_id when updating group URLs. - Add utility script to revive unvalidated groups.
1 parent 5e6f437 commit 7090d22

2 files changed

Lines changed: 37 additions & 6 deletions

File tree

handlers/groups.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -133,31 +133,42 @@ async def agregarotros(update: Update, context: ContextTypes.DEFAULT_TYPE):
133133
async def agregareci(update: Update, context: ContextTypes.DEFAULT_TYPE):
134134
await agregar(update, context, ECI, "eci")
135135

136+
from telegram.error import Forbidden, BadRequest, RetryAfter
137+
136138
async def update_group_url(context: ContextTypes.DEFAULT_TYPE, chat_id: str) -> tuple[str, str, bool]:
137139
try:
138140
url = await context.bot.export_chat_invite_link(chat_id=chat_id)
139141
return chat_id, url, True
140-
except Exception:
141-
logger.error(f"Could not create invite link for {chat_id}", exc_info=True)
142+
except (Forbidden, BadRequest) as e:
143+
logger.error(f"Bot is no longer allowed to create invite link for {chat_id}: {e}")
142144
return None, None, False
145+
except RetryAfter as e:
146+
logger.warning(f"Rate limited while creating invite link for {chat_id}. Retry after {e.retry_after} seconds.")
147+
return None, None, None
148+
except Exception as e:
149+
logger.error(f"Could not create invite link for {chat_id}: {e}", exc_info=True)
150+
return None, None, None
143151

144152
async def _update_groups(context: ContextTypes.DEFAULT_TYPE):
145153
logger.info("Starting update_groups job")
146154
with get_session() as session:
147-
chats = [(c.id, c.chat_id, c.name) for c in session.query(Listable).filter_by(validated=True).all()]
155+
chats = [(c.id, c.chat_id, c.name) for c in session.query(Listable).filter_by(validated=True).filter(Listable.chat_id != None, Listable.chat_id != '').all()]
148156
logger.info(f"Found {len(chats)} groups to update")
149157

150158
for chat_db_id, chat_chat_id, chat_name in chats:
151159
await asyncio.sleep(1)
152160
chat_id, url, validated = await update_group_url(context, chat_chat_id)
153-
if not validated:
161+
if validated is False:
154162
logger.warning(f"Failed to update URL for group '{chat_name}'. De-validating.")
155163
with get_session() as session:
156164
c = session.query(Listable).filter_by(id=chat_db_id).first()
157165
if c:
158166
c.validated = False
159-
await context.bot.send_message(chat_id=DC_GROUP_CHATID, text=f"El grupo {chat_name} murió 💀")
160-
else:
167+
try:
168+
await context.bot.send_message(chat_id=DC_GROUP_CHATID, text=f"El grupo {chat_name} murió 💀")
169+
except Exception as e:
170+
logger.error(f"Failed to send death message for {chat_name}: {e}")
171+
elif validated is True:
161172
logger.info(f"Updating URL for group '{chat_name}'")
162173
with get_session() as session:
163174
c = session.query(Listable).filter_by(id=chat_db_id).first()

utils/revive_groups.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import os
2+
from models import init_db, Listable, Session
3+
from handlers.db import get_session
4+
5+
def revive_all_groups():
6+
init_db()
7+
8+
with get_session() as session:
9+
# Find groups that have a chat_id but are not validated
10+
dead_groups = session.query(Listable).filter(Listable.chat_id != None, Listable.validated == False).all()
11+
12+
print(f"Found {len(dead_groups)} groups to revive.")
13+
for group in dead_groups:
14+
print(f"Reviving: {group.name} (Chat ID: {group.chat_id})")
15+
group.validated = True
16+
17+
print("All groups have been revived. If any group is truly dead, the next cron job will handle it properly.")
18+
19+
if __name__ == "__main__":
20+
revive_all_groups()

0 commit comments

Comments
 (0)