File size: 11,016 Bytes
5321464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""
plugins/admin.py β€” Comandos de administraciΓ³n de grupos.

Comandos:
  .kick [@user]              β€” Expulsar usuario
  .ban [@user]               β€” Banear usuario
  .unban [@user]             β€” Desbanear usuario
  .mute [@user] [tiempo]     β€” Silenciar (ej: 10m, 2h, 1d)
  .unmute [@user]            β€” Silenciar permanentemente
  .promote [@user]           β€” Dar permisos de admin
  .demote [@user]            β€” Quitar permisos de admin
  .title [@user] <tΓ­tulo>    β€” Establecer tΓ­tulo de admin
  .members               β€” Cantidad de miembros del grupo
"""
import asyncio
import re
from datetime import datetime, timedelta

from pyrogram import filters
from pyrogram.errors import ChatAdminRequired, UserAdminInvalid, RPCError
from pyrogram.types import Message, ChatPermissions, ChatPrivileges

from bot import app
from config import Config

P = Config.CMD_PREFIX


# ── Helper: resolver usuario destino ─────────────────────────────────────────
async def _resolve_target(client, msg: Message, args: list):
    """
    Returns (user, error_str).
    Priority: reply > first arg as username/id.
    """
    if msg.reply_to_message and msg.reply_to_message.from_user:
        return msg.reply_to_message.from_user, None
    if len(args) > 1:
        try:
            return await client.get_users(args[1].lstrip("@")), None
        except Exception as e:
            return None, str(e)
    return None, "Especifica un usuario o responde a su mensaje."


def _parse_duration(text: str) -> int:
    """Convert '10m', '2h', '1d' β†’ seconds. Returns 0 if not parseable."""
    m = re.match(r"(\d+)([smhd]?)", text.strip())
    if not m:
        return 0
    v, u = int(m.group(1)), m.group(2)
    return v * {"s": 1, "m": 60, "h": 3600, "d": 86400}.get(u, 60)


async def _respond(client, msg: Message, text: str, delay: int = 5):
    note = await client.send_message(msg.chat.id, text)
    await asyncio.sleep(delay)
    await note.delete()


# ── .kick ─────────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("kick", prefixes=P))
async def cmd_kick(client, msg: Message):
    await msg.delete()
    args = msg.text.split()
    user, err = await _resolve_target(client, msg, args)
    if err:
        await _respond(client, msg, f"❌ {err}"); return
    try:
        await client.ban_chat_member(msg.chat.id, user.id)
        await client.unban_chat_member(msg.chat.id, user.id)  # unban so they can rejoin
        name = user.first_name or user.username or user.id
        await _respond(client, msg, f"πŸ‘’ **{name}** ha sido expulsado.")
    except (ChatAdminRequired, UserAdminInvalid) as e:
        await _respond(client, msg, f"❌ Sin permisos: `{e}`")
    except RPCError as e:
        await _respond(client, msg, f"❌ `{e}`")


# ── .ban ──────────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("ban", prefixes=P))
async def cmd_ban(client, msg: Message):
    await msg.delete()
    args = msg.text.split()
    user, err = await _resolve_target(client, msg, args)
    if err:
        await _respond(client, msg, f"❌ {err}"); return
    try:
        await client.ban_chat_member(msg.chat.id, user.id)
        name = user.first_name or user.username or user.id
        await _respond(client, msg, f"πŸ”¨ **{name}** ha sido baneado.")
    except (ChatAdminRequired, UserAdminInvalid) as e:
        await _respond(client, msg, f"❌ Sin permisos: `{e}`")


# ── .unban ────────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("unban", prefixes=P))
async def cmd_unban(client, msg: Message):
    await msg.delete()
    args = msg.text.split()
    user, err = await _resolve_target(client, msg, args)
    if err:
        await _respond(client, msg, f"❌ {err}"); return
    try:
        await client.unban_chat_member(msg.chat.id, user.id)
        name = user.first_name or user.username or user.id
        await _respond(client, msg, f"βœ… **{name}** ha sido desbaneado.")
    except RPCError as e:
        await _respond(client, msg, f"❌ `{e}`")


# ── .mute ─────────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("mute", prefixes=P))
async def cmd_mute(client, msg: Message):
    await msg.delete()
    args = msg.text.split()
    user, err = await _resolve_target(client, msg, args)
    if err:
        await _respond(client, msg, f"❌ {err}"); return

    # Duration: last arg if it looks like "10m", "2h", "1d"
    dur_str = args[-1] if len(args) > 1 and re.match(r"\d+[smhd]?", args[-1]) else "0"
    dur_secs = _parse_duration(dur_str)
    until = datetime.utcnow() + timedelta(seconds=dur_secs) if dur_secs else None

    try:
        perms = ChatPermissions(
            can_send_messages=False,
            can_send_media_messages=False,
            can_send_other_messages=False,
            can_add_web_page_previews=False,
        )
        await client.restrict_chat_member(msg.chat.id, user.id, perms,
                                          until_date=until)
        name = user.first_name or user.username or user.id
        dur_label = f" por `{dur_str}`" if dur_secs else " permanentemente"
        await _respond(client, msg, f"πŸ”‡ **{name}** silenciado{dur_label}.")
    except (ChatAdminRequired, UserAdminInvalid) as e:
        await _respond(client, msg, f"❌ Sin permisos: `{e}`")


# ── .unmute ───────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("unmute", prefixes=P))
async def cmd_unmute(client, msg: Message):
    await msg.delete()
    args = msg.text.split()
    user, err = await _resolve_target(client, msg, args)
    if err:
        await _respond(client, msg, f"❌ {err}"); return
    try:
        perms = ChatPermissions(
            can_send_messages=True,
            can_send_media_messages=True,
            can_send_other_messages=True,
            can_add_web_page_previews=True,
        )
        await client.restrict_chat_member(msg.chat.id, user.id, perms)
        name = user.first_name or user.username or user.id
        await _respond(client, msg, f"πŸ”Š **{name}** ya puede hablar.")
    except RPCError as e:
        await _respond(client, msg, f"❌ `{e}`")


# ── .promote ──────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("promote", prefixes=P))
async def cmd_promote(client, msg: Message):
    await msg.delete()
    args = msg.text.split()
    user, err = await _resolve_target(client, msg, args)
    if err:
        await _respond(client, msg, f"❌ {err}"); return
    try:
        await client.promote_chat_member(
            msg.chat.id, user.id,
            privileges=ChatPrivileges(
                can_manage_chat=True,
                can_delete_messages=True,
                can_restrict_members=True,
                can_invite_users=True,
                can_pin_messages=True,
                can_promote_members=False,
            )
        )
        name = user.first_name or user.username or user.id
        await _respond(client, msg, f"⭐ **{name}** promovido a admin.")
    except (ChatAdminRequired, UserAdminInvalid) as e:
        await _respond(client, msg, f"❌ Sin permisos: `{e}`")


# ── .demote ───────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("demote", prefixes=P))
async def cmd_demote(client, msg: Message):
    await msg.delete()
    args = msg.text.split()
    user, err = await _resolve_target(client, msg, args)
    if err:
        await _respond(client, msg, f"❌ {err}"); return
    try:
        await client.promote_chat_member(
            msg.chat.id, user.id,
            privileges=ChatPrivileges(can_manage_chat=False)
        )
        name = user.first_name or user.username or user.id
        await _respond(client, msg, f"⬇️ **{name}** degradado.")
    except (ChatAdminRequired, UserAdminInvalid) as e:
        await _respond(client, msg, f"❌ Sin permisos: `{e}`")


# ── .title ────────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("title", prefixes=P))
async def cmd_title(client, msg: Message):
    await msg.delete()
    args = msg.text.split(None, 2)
    user, err = await _resolve_target(client, msg, args)
    if err:
        await _respond(client, msg, f"❌ {err}"); return

    title = args[-1] if len(args) >= 3 else ""
    try:
        await client.set_administrator_title(msg.chat.id, user.id, title)
        name = user.first_name or user.username or user.id
        await _respond(client, msg, f"✏️ TΓ­tulo de **{name}** β†’ `{title or '(vacΓ­o)'}`")
    except RPCError as e:
        await _respond(client, msg, f"❌ `{e}`")


# ── .members ──────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("members", prefixes=P))
async def cmd_members(client, msg: Message):
    await msg.delete()
    try:
        chat = await client.get_chat(msg.chat.id)
        count = chat.members_count or "?"
        title = chat.title or "este chat"
        note = await client.send_message(
            msg.chat.id,
            f"πŸ‘₯ **{title}** tiene `{count:,}` miembros." if isinstance(count, int)
            else f"πŸ‘₯ Miembros: `{count}`"
        )
        await asyncio.sleep(6)
        await note.delete()
    except RPCError as e:
        note = await client.send_message(msg.chat.id, f"❌ `{e}`")
        await asyncio.sleep(5)
        await note.delete()