File size: 8,027 Bytes
de2f8a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f85dc9
de2f8a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f85dc9
de2f8a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
"""
Channel Manager Plugin β€” add, remove, and list AUTH_CHANNELs via the bot.

Commands (owner-only, private chat):
    /channels               β€” List all active AUTH_CHANNELs with names
    /addchannel <id>        β€” Add a channel (validates bot access first)
    /removechannel <id>     β€” Remove a channel

Changes take effect immediately (no restart needed) and are persisted to MongoDB.

"""

from pyrogram import filters, Client, enums
from pyrogram.types import Message
from pyrogram.errors import ChannelPrivate, ChatAdminRequired, PeerIdInvalid

from Backend import db
from Backend.helper.custom_filter import CustomFilters
from Backend.logger import LOGGER
from Backend.config import Telegram


# ── DB persistence helpers ───────────────────────────────────────────────

CHANNEL_DOC_ID = "auth_channels"


async def _load_channels_from_db():
    try:
        doc = await db.dbs["tracking"]["config"].find_one({"_id": CHANNEL_DOC_ID})
        if doc and "channels" in doc:
            db_channels = doc["channels"]
            for ch in db_channels:
                if ch not in Telegram.AUTH_CHANNEL:
                    Telegram.AUTH_CHANNEL.append(ch)
            LOGGER.info(
                f"[ChannelMgr] Loaded {len(db_channels)} channels from DB, "
                f"total active: {len(Telegram.AUTH_CHANNEL)}"
            )
    except Exception as e:
        LOGGER.error(f"[ChannelMgr] Failed to load channels from DB: {e}")


async def _save_channels_to_db():
    try:
        await db.dbs["tracking"]["config"].update_one(
            {"_id": CHANNEL_DOC_ID},
            {"$set": {"channels": list(Telegram.AUTH_CHANNEL)}},
            upsert=True,
        )
    except Exception as e:
        LOGGER.error(f"[ChannelMgr] Failed to save channels to DB: {e}")


# ── Bot Commands ─────────────────────────────────────────────────────────

@Client.on_message(filters.command('channels') & filters.private & CustomFilters.owner, group=10)
async def list_channels(client: Client, message: Message):
    if not Telegram.AUTH_CHANNEL:
        await message.reply_text(
            "πŸ“­ No AUTH_CHANNELs configured.\n\n"
            "Use /addchannel <code>&lt;channel_id&gt;</code> to add one.",
            quote=True,
            parse_mode=enums.ParseMode.HTML,
        )
        return

    lines = []
    for i, ch_id in enumerate(Telegram.AUTH_CHANNEL, 1):
        name = ch_id
        try:
            chat = await client.get_chat(int(ch_id))
            name = getattr(chat, "title", ch_id)
            members = getattr(chat, "members_count", "?")
            lines.append(f"{i}. <b>{name}</b>\n   ID: <code>{ch_id}</code> | Members: {members}")
        except Exception:
            lines.append(f"{i}. <b>[inaccessible]</b>\n   ID: <code>{ch_id}</code>")

    text = (
        "<blockquote>πŸ“‘ <b>Active AUTH_CHANNELs</b></blockquote>\n\n"
        + "\n\n".join(lines)
        + "\n\n<i>Use /addchannel or /removechannel to manage.</i>"
    )
    await message.reply_text(text, quote=True, parse_mode=enums.ParseMode.HTML)


@Client.on_message(filters.command('addchannel') & filters.private & CustomFilters.owner, group=10)
async def add_channel(client: Client, message: Message):
    args = message.text.split(maxsplit=1)
    if len(args) < 2:
        await message.reply_text(
            "Usage: /addchannel <code>&lt;channel_id&gt;</code>\n\n"
            "Example: <code>/addchannel -1001234567890</code>\n\n"
            "πŸ’‘ <i>To find a channel ID, forward a message from it to "
            "@userinfobot or check the channel's invite link.</i>",
            quote=True,
            parse_mode=enums.ParseMode.HTML,
        )
        return

    ch_id = args[1].strip()

    try:
        int(ch_id)
    except ValueError:
        await message.reply_text(
            f"❌ <code>{ch_id}</code> is not a valid channel ID.\n"
            "Channel IDs are numeric, usually starting with <code>-100</code>.",
            quote=True,
            parse_mode=enums.ParseMode.HTML,
        )
        return

    if ch_id in Telegram.AUTH_CHANNEL:
        await message.reply_text(
            f"ℹ️ Channel <code>{ch_id}</code> is already in AUTH_CHANNELs.",
            quote=True,
            parse_mode=enums.ParseMode.HTML,
        )
        return

    status_msg = await message.reply_text(
        "πŸ” Validating channel access…",
        quote=True,
        parse_mode=enums.ParseMode.HTML,
    )

    try:
        chat = await client.get_chat(int(ch_id))
        ch_name = getattr(chat, "title", ch_id)
    except (ChannelPrivate, ChatAdminRequired):
        await status_msg.edit_text(
            f"❌ <b>Access denied</b> to channel <code>{ch_id}</code>.\n\n"
            "Make sure the bot is added as an <b>admin</b> in the channel first.",
            parse_mode=enums.ParseMode.HTML,
        )
        return
    except PeerIdInvalid:
        await status_msg.edit_text(
            f"❌ Channel <code>{ch_id}</code> not found.\n"
            "Double-check the ID.",
            parse_mode=enums.ParseMode.HTML,
        )
        return
    except Exception as e:
        await status_msg.edit_text(
            f"❌ Error accessing channel: <code>{e}</code>",
            parse_mode=enums.ParseMode.HTML,
        )
        return

    Telegram.AUTH_CHANNEL.append(ch_id)
    await _save_channels_to_db()

    LOGGER.info(f"[ChannelMgr] Added channel {ch_id} ({ch_name})")

    await status_msg.edit_text(
        f"βœ… <b>Channel added!</b>\n\n"
        f"πŸ“‘ <b>{ch_name}</b>\n"
        f"ID: <code>{ch_id}</code>\n\n"
        f"The bot will now index new videos from this channel.\n"
        f"Use /scan <code>{ch_id}</code> to index existing content.",
        parse_mode=enums.ParseMode.HTML,
    )


@Client.on_message(filters.command('removechannel') & filters.private & CustomFilters.owner, group=10)
async def remove_channel(client: Client, message: Message):
    args = message.text.split(maxsplit=1)
    if len(args) < 2:
        if Telegram.AUTH_CHANNEL:
            lines = []
            for ch_id in Telegram.AUTH_CHANNEL:
                try:
                    chat = await client.get_chat(int(ch_id))
                    name = getattr(chat, "title", ch_id)
                except Exception:
                    name = "[inaccessible]"
                lines.append(f"β€’ <code>{ch_id}</code> β€” {name}")

            await message.reply_text(
                "Usage: /removechannel <code>&lt;channel_id&gt;</code>\n\n"
                "<b>Current channels:</b>\n" + "\n".join(lines),
                quote=True,
                parse_mode=enums.ParseMode.HTML,
            )
        else:
            await message.reply_text(
                "πŸ“­ No channels to remove.",
                quote=True,
            )
        return

    ch_id = args[1].strip()

    if ch_id not in Telegram.AUTH_CHANNEL:
        await message.reply_text(
            f"❌ Channel <code>{ch_id}</code> is not in AUTH_CHANNELs.",
            quote=True,
            parse_mode=enums.ParseMode.HTML,
        )
        return

    ch_name = ch_id
    try:
        chat = await client.get_chat(int(ch_id))
        ch_name = getattr(chat, "title", ch_id)
    except Exception:
        pass

    Telegram.AUTH_CHANNEL.remove(ch_id)
    await _save_channels_to_db()

    LOGGER.info(f"[ChannelMgr] Removed channel {ch_id} ({ch_name})")

    await message.reply_text(
        f"βœ… <b>Channel removed!</b>\n\n"
        f"πŸ“‘ <b>{ch_name}</b> (<code>{ch_id}</code>)\n\n"
        f"⚠️ Existing DB entries from this channel are <b>not</b> deleted.\n"
        f"Videos already indexed will still be streamable.\n"
        f"New videos in this channel will no longer be indexed.",
        quote=True,
        parse_mode=enums.ParseMode.HTML,
    )