Team Ai
Apppublic

azils3/bash

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
_userlogs.py300 linesDownload Raw Back to plugins
1# Ultroid - UserBot2# Copyright (C) 2021-2025 TeamUltroid3#4# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >5# PLease read the GNU Affero General Public License in6# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.7 8import os9import re10 11from telethon.errors.rpcerrorlist import (12    ChannelPrivateError,13    ChatWriteForbiddenError,14    MediaCaptionTooLongError,15    MediaEmptyError,16    MessageTooLongError,17    PeerIdInvalidError,18    UserNotParticipantError,19)20from telethon.tl.types import MessageEntityMention, MessageEntityMentionName, User21from telethon.utils import get_display_name22 23from pyUltroid.dB.botchat_db import tag_add, who_tag24 25from . import (26    LOG_CHANNEL,27    LOGS,28    Button,29    asst,30    callback,31    events,32    get_string,33    inline_mention,34    udB,35    ultroid_bot,36)37 38CACHE_SPAM = {}39TAG_EDITS = {}40 41 42@ultroid_bot.on(43    events.NewMessage(44        incoming=True,45        func=lambda e: (e.mentioned),46    ),47)48async def all_messages_catcher(e):49    x = await e.get_sender()50    if isinstance(x, User) and (x.bot or x.verified):51        return52    if not udB.get_key("TAG_LOG"):53        return54    NEEDTOLOG = udB.get_key("TAG_LOG")55    if e.chat_id == NEEDTOLOG:56        return57    buttons = await parse_buttons(e)58    try:59        sent = await asst.send_message(NEEDTOLOG, e.message, buttons=buttons)60        if TAG_EDITS.get(e.chat_id):61            TAG_EDITS[e.chat_id].update({e.id: {"id": sent.id, "msg": e}})62        else:63            TAG_EDITS.update({e.chat_id: {e.id: {"id": sent.id, "msg": e}}})64        tag_add(sent.id, e.chat_id, e.id)65    except MediaEmptyError as er:66        LOGS.debug(f"handling {er}.")67        try:68            msg = await asst.get_messages(e.chat_id, ids=e.id)69            sent = await asst.send_message(NEEDTOLOG, msg, buttons=buttons)70            if TAG_EDITS.get(e.chat_id):71                TAG_EDITS[e.chat_id].update({e.id: {"id": sent.id, "msg": e}})72            else:73                TAG_EDITS.update({e.chat_id: {e.id: {"id": sent.id, "msg": e}}})74            tag_add(sent.id, e.chat_id, e.id)75        except Exception as me:76            if not isinstance(me, (PeerIdInvalidError, ValueError)):77                LOGS.exception(me)78            if e.photo or e.sticker or e.gif:79                try:80                    media = await e.download_media()81                    sent = await asst.send_message(82                        NEEDTOLOG, e.message.text, file=media, buttons=buttons83                    )84                    if TAG_EDITS.get(e.chat_id):85                        TAG_EDITS[e.chat_id].update({e.id: {"id": sent.id, "msg": e}})86                    else:87                        TAG_EDITS.update({e.chat_id: {e.id: {"id": sent.id, "msg": e}}})88                    return os.remove(media)89                except Exception as er:90                    LOGS.exception(er)91            await asst.send_message(NEEDTOLOG, get_string("com_4"), buttons=buttons)92    except (PeerIdInvalidError, ValueError) as er:93        LOGS.exception(er)94        try:95            CACHE_SPAM[NEEDTOLOG]96        except KeyError:97            await asst.send_message(98                udB.get_key("LOG_CHANNEL"), get_string("userlogs_1")99            )100            CACHE_SPAM.update({NEEDTOLOG: True})101    except ChatWriteForbiddenError:102        try:103            await asst.get_permissions(NEEDTOLOG, "me")104            MSG = get_string("userlogs_4")105        except UserNotParticipantError:106            MSG = get_string("userlogs_2")107        try:108            CACHE_SPAM[NEEDTOLOG]109        except KeyError:110            await asst.send_message(LOG_CHANNEL, MSG)111            CACHE_SPAM.update({NEEDTOLOG: True})112    except Exception as er:113        LOGS.exception(er)114 115 116if udB.get_key("TAG_LOG"):117 118    @ultroid_bot.on(events.MessageEdited(func=lambda x: not x.out))119    async def upd_edits(event):120        x = event.sender121        if isinstance(x, User) and (x.bot or x.verified):122            return123        if event.chat_id not in TAG_EDITS:124            if event.sender_id == udB.get_key("TAG_LOG"):125                return126            if event.is_private:127                return128            if entities := event.get_entities_text():129                is_self = False130                username = event.client.me.username131                if username:132                    username = username.lower()133                for ent, text in entities:134                    if isinstance(ent, MessageEntityMention):135                        is_self = text[1:].lower() == username136                    elif isinstance(ent, MessageEntityMentionName):137                        is_self = ent.user_id == event.client.me.id138                if is_self:139                    text = f"**#Edited & #Mentioned**\n\n{event.text}"140                    try:141                        sent = await asst.send_message(142                            udB.get_key("TAG_LOG"),143                            text,144                            buttons=await parse_buttons(event),145                        )146                    except Exception as er:147                        return LOGS.exception(er)148                    if TAG_EDITS.get(event.chat_id):149                        TAG_EDITS[event.chat_id].update({event.id: {"id": sent.id}})150                    else:151                        TAG_EDITS.update({event.chat_id: {event.id: {"id": sent.id}}})152            return153        d_ = TAG_EDITS[event.chat_id]154        if not d_.get(event.id):155            return156        d_ = d_[event.id]157        if d_["msg"].text == event.text:158            return159        msg = None160        if d_.get("count"):161            d_["count"] += 1162        else:163            msg = True164            d_.update({"count": 1})165        if d_["count"] > 10:166            return  # some limit to take edits167        try:168            MSG = await asst.get_messages(udB.get_key("TAG_LOG"), ids=d_["id"])169        except Exception as er:170            return LOGS.exception(er)171        TEXT = MSG.text172        if msg:173            TEXT += "\n\n🖋 **Later Edited to !**"174        strf = event.edit_date.strftime("%H:%M:%S")175        if "\n" not in event.text:176            TEXT += f"\n• `{strf}` : {event.text}"177        else:178            TEXT += f"\n• `{strf}` :\n-> {event.text}"179        if d_["count"] == 10:180            TEXT += "\n\n• __Only the first 10 Edits are shown.__"181        try:182            msg = await MSG.edit(TEXT, buttons=await parse_buttons(event))183            d_["msg"] = msg184        except (MessageTooLongError, MediaCaptionTooLongError):185            del TAG_EDITS[event.chat_id][event.id]186        except Exception as er:187            LOGS.exception(er)188 189    @ultroid_bot.on(190        events.NewMessage(191            outgoing=True,192            chats=[udB.get_key("TAG_LOG")],193            func=lambda e: e.reply_to,194        )195    )196    async def idk(e):197        id = e.reply_to_msg_id198        chat, msg = who_tag(id)199        if chat and msg:200            try:201                await ultroid_bot.send_message(chat, e.message, reply_to=msg)202            except BaseException as er:203                LOGS.exception(er)204 205 206# log for assistant/user joins/add207 208 209async def when_added_or_joined(event):210    user = await event.get_user()211    chat = await event.get_chat()212    if not (user and user.is_self):213        return214    if getattr(chat, "username", None):215        chat = f"[{chat.title}](https://t.me/{chat.username}/{event.action_message.id})"216    else:217        chat = f"[{chat.title}](https://t.me/c/{chat.id}/{event.action_message.id})"218    key = "bot" if event.client._bot else "user"219    buttons = Button.inline(220        get_string("userlogs_3"), data=f"leave_ch_{event.chat_id}|{key}"221    )222    if event.user_added:223        tmp = event.added_by224        text = f"#ADD_LOG\n\n{inline_mention(tmp)} just added {inline_mention(user)} to {chat}."225    elif event.from_request:226        text = f"#APPROVAL_LOG\n\n{inline_mention(user)} just got Chat Join Approval to {chat}."227    else:228        text = f"#JOIN_LOG\n\n{inline_mention(user)} just joined {chat}."229    await asst.send_message(udB.get_key("LOG_CHANNEL"), text, buttons=buttons)230 231 232asst.add_event_handler(233    when_added_or_joined, events.ChatAction(func=lambda x: x.user_added)234)235ultroid_bot.add_event_handler(236    when_added_or_joined,237    events.ChatAction(func=lambda x: x.user_added or x.user_joined),238)239_client = {"bot": asst, "user": ultroid_bot}240 241 242@callback(243    re.compile(244        "leave_ch_(.*)",245    ),246    from_users=[ultroid_bot.uid],247)248async def leave_ch_at(event):249    cht = event.data_match.group(1).decode("UTF-8")250    ch_id, client = cht.split("|")251    try:252        client = _client[client]253    except KeyError:254        return255    try:256        name = (await client.get_entity(int(ch_id))).title257        await client.delete_dialog(int(ch_id))258    except UserNotParticipantError:259        pass260    except ChannelPrivateError:261        return await event.edit(262            "`[CANT_ACCESS_CHAT]` `Maybe already left or got banned.`"263        )264    except Exception as er:265        LOGS.exception(er)266        return await event.answer(str(er))267    await event.edit(get_string("userlogs_5").format(name))268 269 270@callback("do_nothing")271async def _(event):272    await event.answer()273 274 275async def parse_buttons(event):276    y, x = event.chat, event.sender277    where_n, who_n = get_display_name(y), get_display_name(x)278    where_l = event.message_link279    buttons = [[Button.url(where_n, where_l)]]280    if isinstance(x, User) and x.username:281        try:282            buttons.append(283                [Button.mention(who_n, await asst.get_input_entity(x.username))]284            )285        except Exception as er:286            LOGS.exception(er)287            buttons.append([Button.url(who_n, f"t.me/{x.username}")])288    elif getattr(x, "username"):289        buttons.append([Button.url(who_n, f"t.me/{x.username}")])290    else:291        buttons.append([Button.url(who_n, where_l)])292    replied = await event.get_reply_message()293    if replied and replied.out:294        button = Button.url("Replied to", replied.message_link)295        if len(who_n) > 7:296            buttons.append([button])297        else:298            buttons[-1].append(button)299    return buttons300