File size: 7,444 Bytes
1404692
36dde81
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
c12bb0b
1404692
36dde81
 
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
c12bb0b
1404692
36dde81
1404692
36dde81
1404692
c12bb0b
1404692
c12bb0b
1404692
c12bb0b
36dde81
c12bb0b
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
 
 
 
 
 
1404692
 
 
c12bb0b
 
 
1404692
36dde81
1404692
 
c12bb0b
 
 
36dde81
c12bb0b
 
36dde81
 
 
 
 
 
 
 
 
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404692
c12bb0b
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
c12bb0b
 
 
 
 
 
 
 
1404692
c12bb0b
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
from asyncio import sleep
from typing import List

from pyrogram.errors import (
    FloodWait,
    ChatAdminRequired,
    ChannelPrivate,
    MessageDeleteForbidden,
    MessageAuthorRequired,
    PeerIdInvalid,
    UserNotParticipant,
    AuthKeyUnregistered,
    SessionRevoked,
    RPCError,
)
from pyrogram.enums import ParseMode

from Backend.logger import LOGGER
import Backend.pyrofork.bot as botmod
from Backend.pyrofork.bot import StreamBot

DELETE_BATCH_SIZE = 10
_FALLBACK_WORTHY = (
    ChatAdminRequired,
    ChannelPrivate,
    MessageDeleteForbidden,
    MessageAuthorRequired,
    UserNotParticipant,
    RPCError,
)
_SESSION_DEAD = (AuthKeyUnregistered, SessionRevoked)
_userbot_session_dead = False


def _userbot_usable() -> bool:
    return botmod.Userbot is not None and not _userbot_session_dead


async def _resolve_peer(client, chat_id) -> bool:
    try:
        await client.get_chat(chat_id)
        return True
    except Exception as e:
        return False


async def edit_message(chat_id: int, msg_id: int, new_caption: str):
    try:
        await StreamBot.edit_message_caption(chat_id=chat_id, message_id=msg_id, caption=new_caption, parse_mode=ParseMode.HTML)
        await sleep(2)
        return
    except FloodWait as e:
        LOGGER.warning(f"FloodWait for {e.value}s while editing message {msg_id} in {chat_id}")
        await sleep(e.value)
        try:
            await StreamBot.edit_message_caption(chat_id=chat_id, message_id=msg_id, caption=new_caption, parse_mode=ParseMode.HTML)
            return
        except Exception as e2:
            LOGGER.error(f"Retry after FloodWait failed while editing {msg_id} in {chat_id}: {e2}")
    except PeerIdInvalid as e:
        if await _resolve_peer(StreamBot, chat_id):
            try:
                await StreamBot.edit_message_caption(chat_id=chat_id, message_id=msg_id, caption=new_caption, parse_mode=ParseMode.HTML)
                return
            except Exception as e2:
                LOGGER.error(f"Retry after peer resolve failed while editing {msg_id} in {chat_id}: {e2}")
        if not _userbot_usable():
            LOGGER.error(f"Error while editing message {msg_id} in {chat_id}: {e}")
            return
        LOGGER.info(f"[USERBOT] Fallback triggered: edit_message {msg_id} in {chat_id} (StreamBot: {e})")
        await _userbot_edit(chat_id, msg_id, new_caption)
    except _FALLBACK_WORTHY as e:
        if not _userbot_usable():
            LOGGER.error(f"Error while editing message {msg_id} in {chat_id}: {e}")
            return
        LOGGER.info(f"[USERBOT] Fallback triggered: edit_message {msg_id} in {chat_id} (StreamBot: {e})")
        await _userbot_edit(chat_id, msg_id, new_caption)
    except Exception as e:
        LOGGER.error(f"Error while editing message {msg_id} in {chat_id}: {e}")


async def _userbot_edit(chat_id: int, msg_id: int, new_caption: str):
    global _userbot_session_dead
    try:
        await botmod.Userbot.edit_message_caption(chat_id=chat_id, message_id=msg_id, caption=new_caption, parse_mode=ParseMode.HTML)
        await sleep(2)
    except FloodWait as e:
        LOGGER.warning(f"[USERBOT] FloodWait detected: sleeping {e.value}s (edit {msg_id} in {chat_id})")
        await sleep(e.value)
        try:
            await botmod.Userbot.edit_message_caption(chat_id=chat_id, message_id=msg_id, caption=new_caption, parse_mode=ParseMode.HTML)
        except Exception as e2:
            LOGGER.error(f"[USERBOT] Retry after FloodWait failed while editing {msg_id} in {chat_id}: {e2}")
    except PeerIdInvalid as e:
        if await _resolve_peer(botmod.Userbot, chat_id):
            try:
                await botmod.Userbot.edit_message_caption(chat_id=chat_id, message_id=msg_id, caption=new_caption, parse_mode=ParseMode.HTML)
                return
            except Exception as e2:
                LOGGER.error(f"[USERBOT] Retry after peer resolve failed while editing {msg_id} in {chat_id}: {e2}")
                return
        LOGGER.error(f"[USERBOT] Peer unresolved while editing {msg_id} in {chat_id}: {e}")
    except _SESSION_DEAD as e:
        _userbot_session_dead = True
        LOGGER.error(f"[USERBOT] Session invalid ({type(e).__name__}): {e}. Disabling Userbot fallback for this run.")
    except Exception as e:
        LOGGER.error(f"[USERBOT] Error while editing message {msg_id} in {chat_id}: {e}")


async def delete_message(chat_id: int, msg_id: int):
    await delete_messages_batch(chat_id, [msg_id])


async def delete_messages_batch(chat_id: int, msg_ids: List[int]):
    if not msg_ids:
        return

    for i in range(0, len(msg_ids), DELETE_BATCH_SIZE):
        chunk = msg_ids[i:i + DELETE_BATCH_SIZE]

        remaining = await _delete_chunk(StreamBot, "StreamBot", chat_id, chunk)

        if remaining and _userbot_usable():
            LOGGER.info(f"[USERBOT] Fallback triggered: deleting {len(remaining)} message(s) in {chat_id}")
            remaining = await _delete_chunk(botmod.Userbot, "Userbot", chat_id, remaining)

        if remaining:
            LOGGER.error(
                f"Could not delete {len(remaining)} message(s) in {chat_id} "
                f"(no usable Userbot fallback)" if not _userbot_usable() else
                f"Could not delete {len(remaining)} message(s) in {chat_id} even with Userbot fallback"
            )

        await sleep(1)


async def _delete_chunk(client, client_label: str, chat_id: int, msg_ids: List[int]) -> List[int]:
    global _userbot_session_dead
    try:
        await client.delete_messages(chat_id=chat_id, message_ids=msg_ids)
        LOGGER.info(f"[{client_label.upper()}] Deleted {len(msg_ids)} message(s) in {chat_id}")
        return []
    except FloodWait as e:
        LOGGER.warning(f"[{client_label.upper()}] FloodWait detected: sleeping {e.value}s ({len(msg_ids)} msg(s) in {chat_id})")
        await sleep(e.value)
        try:
            await client.delete_messages(chat_id=chat_id, message_ids=msg_ids)
            LOGGER.info(f"[{client_label.upper()}] Deleted {len(msg_ids)} message(s) in {chat_id} after FloodWait retry")
            return []
        except Exception as e2:
            LOGGER.error(f"[{client_label.upper()}] Retry after FloodWait failed in {chat_id}: {e2}")
            return msg_ids
    except PeerIdInvalid as e:
        if await _resolve_peer(client, chat_id):
            try:
                await client.delete_messages(chat_id=chat_id, message_ids=msg_ids)
                LOGGER.info(f"[{client_label.upper()}] Deleted {len(msg_ids)} message(s) in {chat_id} after peer resolve")
                return []
            except Exception as e2:
                LOGGER.error(f"[{client_label.upper()}] Retry after peer resolve failed in {chat_id}: {e2}")
                return msg_ids
        LOGGER.warning(f"[{client_label.upper()}] Peer unresolved in {chat_id}: {e}")
        return msg_ids
    except _SESSION_DEAD as e:
        if client_label == "Userbot":
            _userbot_session_dead = True
        LOGGER.error(f"[{client_label.upper()}] Session invalid ({type(e).__name__}): {e}")
        return msg_ids
    except _FALLBACK_WORTHY as e:
        LOGGER.warning(f"[{client_label.upper()}] Cannot delete in {chat_id} ({type(e).__name__}): {e}")
        return msg_ids
    except Exception as e:
        LOGGER.error(f"[{client_label.upper()}] Unexpected error deleting in {chat_id}: {e}")
        return msg_ids