async def message_handler(self, event):
        """Callback method for received events.NewMessage"""

        # Note that message_handler is called when a Telegram update occurs
        # and an event is created. Telegram may not always send information
        # about the ``.sender`` or the ``.chat``, so if you *really* want it
        # you should use ``get_chat()`` and ``get_sender()`` while working
        # with events. Since they are methods, you know they may make an API
        # call, which can be expensive.
        chat = await event.get_chat()
        if event.is_group:
            if event.out:
                sprint('>> sent "{}" to chat {}'.format(
                    event.text, get_display_name(chat)
                ))
            else:
                sprint('<< {} @ {} sent "{}"'.format(
                    get_display_name(await event.get_sender()),
                    get_display_name(chat),
                    event.text
                ))
        else:
            if event.out:
                sprint('>> "{}" to user {}'.format(
                    event.text, get_display_name(chat)
                ))
            else:
                sprint('<< {} sent "{}"'.format(
                    get_display_name(chat), event.text
                ))
    def message_handler(self, event):
        """Callback method for received events.NewMessage"""

        # Note that accessing ``.sender`` and ``.chat`` may be slow since
        # these are not cached and must be queried always! However it lets
        # us access the chat title and user name.
        if event.is_group:
            if event.out:
                sprint('>> sent "{}" to chat {}'.format(
                    event.text, get_display_name(event.chat)
                ))
            else:
                sprint('<< {} @ {} sent "{}"'.format(
                    get_display_name(event.sender),
                    get_display_name(event.chat),
                    event.text
                ))
        else:
            if event.out:
                sprint('>> "{}" to user {}'.format(
                    event.text, get_display_name(event.chat)
                ))
            else:
                sprint('<< {} sent "{}"'.format(
                    get_display_name(event.chat), event.text
                ))
    async def _add_to_group(
        self,
        message: Union[Message, "aigoram.types.CallbackQuery"],  # noqa: F821
        group: str,
        confirmed: bool = False,
        user: int = None,
    ) -> None:
        if user is None:
            user = await self._resolve_user(message)
            if not user:
                return

        if isinstance(user, int):
            user = await self._client.get_entity(user)

        if self._is_geek and not confirmed:
            await self.inline.form(
                self.strings("warning").format(
                    user.id, utils.escape_html(get_display_name(user)), group),
                message=message,
                ttl=10 * 60,
                reply_markup=[[
                    {
                        "text": self.strings("cancel"),
                        "callback": self.inline_close,
                    },
                    {
                        "text": self.strings("confirm"),
                        "callback": self._add_to_group,
                        "args": (group, True, user.id),
                    },
                ]],
            )
            return

        self._db.set(
            security.__name__,
            group,
            list(set(self._db.get(security.__name__, group, []) + [user.id])),
        )

        m = self.strings(f"{group}_added").format(
            user.id,
            utils.escape_html(get_display_name(user)),
        )

        if not self._is_geek:
            m += f"\n\n{self.strings('restart')}"

        if isinstance(message, Message):
            await utils.answer(
                message,
                m,
            )
        else:
            await message.edit(m)
Example #4
0
async def admin_report(e):
    if e.is_private:
        return
    if e.chat_id == config.log_chat:
        #        No recursion please
        return
    reporter = await e.get_sender()
    reporter_name = html.escape(utils.get_display_name(reporter))
    chat = await e.get_chat()
    if not getattr(chat, 'username', None):
        unmark_cid = await e.client.get_peer_id(chat.id, False)
        link = f'https://t.me/c/{unmark_cid}/{e.id}'
    else:
        link = f'https://t.me/{chat.username}/{e.id}'
    if e.is_reply:
        r = await e.get_reply_message()
        try:
            reportee = await r.get_sender()
            reportee_name = html.escape(utils.get_display_name(reportee))
        except AttributeError:
            await e.client.send_message(
                config.log_chat,
                strings.admin_report_no_reportee.format(
                    reporter=reporter,
                    chat=chat,
                    e=e,
                    remark=html.escape(str(e.text)),
                    link=link,
                    reporter_name=reporter_name),
                link_preview=False)
            return

        await e.client.send_message(config.log_chat,
                                    strings.admin_report.format(
                                        reporter=reporter,
                                        reportee=reportee,
                                        chat=chat,
                                        e=e,
                                        r=r,
                                        remark=html.escape(str(e.text)),
                                        link=link,
                                        reported_message=html.escape(
                                            str(r.text)),
                                        reporter_name=reporter_name,
                                        reportee_name=reportee_name),
                                    link_preview=False)
    else:
        await e.client.send_message(config.log_chat,
                                    strings.admin_report_no_reportee.format(
                                        reporter=reporter,
                                        chat=chat,
                                        e=e,
                                        remark=html.escape(str(e.text)),
                                        link=link,
                                        reporter_name=reporter_name),
                                    link_preview=False)
    async def add_entity_dialog_messages_to_db(self,
                                               entity,
                                               limit,
                                               e_id=None,
                                               e_type=None):
        if (not e_id) or (not e_type):
            if type(entity) == User:
                e_type = 'User'
                e_id = entity.id
                if entity.bot:
                    e_type = 'Bot'
                self.add_entity_db_name(e_id, e_type,
                                        self.get_user_name_text(entity),
                                        entity.phone, False)
            elif type(entity) == Chat:
                e_type = 'Chat'
                e_id = entity.id
                self.chat_names[str(e_id)] = get_display_name(entity)
                self.add_entity_db_name(e_id, e_type, get_display_name(entity),
                                        None, False)
            elif type(entity) == Channel:
                e_type = 'Channel'
                if entity.megagroup:
                    e_type = 'Megagroup'
                e_id = entity.id
                self.channel_megagroups[str(e_id)] = entity.megagroup
                self.channel_names[str(e_id)] = get_display_name(entity)
                self.add_entity_db_name(e_id, e_type, get_display_name(entity),
                                        None, entity.megagroup)
            else:
                return

        messages = await self.tg_client.get_messages(entity, limit=limit)
        for message_i in messages:
            t_date = StatusController.tg_datetime_to_local_datetime(
                message_i.date)
            from_id = None
            to_id = None
            data_message = message_i.to_dict()
            if 'to_id' in data_message:
                if data_message['to_id']['_'] == 'PeerUser':
                    to_id = data_message['to_id']['user_id']
                elif data_message['to_id']['_'] == 'PeerChannel':
                    to_id = data_message['to_id']['channel_id']
                    from_id = to_id
                elif data_message['to_id']['_'] == 'PeerChat':
                    to_id = data_message['to_id']['chat_id']

            if ('from_id' in data_message) and data_message['from_id']:
                from_id = data_message['from_id']

            message_text = self.tg_client.get_dict_message_text(data_message)
            self.tg_client.add_message_to_db(e_id, e_type, from_id, to_id,
                                             message_i.id, message_text,
                                             t_date, 0)
Example #6
0
    async def message_handler(self, event):
        """Callback method for received events.NewMessage"""

        if event.text:
            # check if the required aes key is present.
            aes_shared_key = None
            for dlg in Dialog.select():
                if dlg.dialog_id == event.sender_id:
                    # found a entry of aes key shared with receiver.
                    aes_shared_key = dlg.aes_shared_key
                    break

            if aes_shared_key is None:
                # get the public key.
                peer_pub_key = get_public_key(event.sender_id)
                shared_key = my_ecdh_private_key.exchange(ec.ECDH(), peer_pub_key)
                aes_shared_key = HKDF(
                    algorithm=hashes.SHA256(),
                    length=32,
                    salt=None,
                    info=None,
                    backend=default_backend(),
                ).derive(shared_key)

                peer = Dialog(dialog_id=event.sender_id, aes_shared_key=aes_shared_key)
                peer.save(force_insert=True)

            # Decrypt the msg and print.
            b64_enc_text_bytes = event.text.encode("utf-8")
            encr_msg_bytes = base64.b64decode(b64_enc_text_bytes)
            init_vector = encr_msg_bytes[:16]
            aes = Cipher(
                algorithms.AES(aes_shared_key),
                modes.CBC(init_vector),
                backend=default_backend(),
            )
            decryptor = aes.decryptor()

            temp_bytes = decryptor.update(encr_msg_bytes[16:]) + decryptor.finalize()

            unpadder = padding.PKCS7(128).unpadder()
            temp_bytes = unpadder.update(temp_bytes) + unpadder.finalize()
            event.text = temp_bytes.decode("utf-8")

            chat = await event.get_chat()
            if event.is_group:
                sprint(
                    '<< {} @ {} sent "{}"'.format(
                        get_display_name(await event.get_sender()),
                        get_display_name(chat),
                        event.text,
                    )
                )
            else:
                sprint('<< {} sent "{}"'.format(get_display_name(chat), event.text))
Example #7
0
async def all_messages_catcher(e):
    if udB.get("TAG_LOG"):
        try:
            NEEDTOLOG = int(udB.get("TAG_LOG"))
        except Exception:
            return LOGS.warning("you given Wrong Grp/Channel ID in TAG_LOG.")
        x = await ultroid_bot.get_entity(e.sender_id)
        if x.bot or x.verified:
            return
        y = await ultroid_bot.get_entity(e.chat_id)
        where_n = get_display_name(y)
        who_n = get_display_name(x)
        where_l = f"https://t.me/c/{y.id}/{e.id}"
        send = await ultroid_bot.get_messages(e.chat_id, ids=e.id)
        try:
            if x.username:
                who_l = f"https://t.me/{x.username}"
                await asst.send_message(
                    NEEDTOLOG,
                    send,
                    buttons=[[Button.url(who_n, who_l)],
                             [Button.url(where_n, where_l)]],
                )
            else:
                await asst.send_message(
                    NEEDTOLOG,
                    send,
                    buttons=[[Button.inline(who_n, data=f"who{x.id}")],
                             [Button.url(where_n, where_l)]],
                )
        except mee:
            if x.username:
                who_l = f"https://t.me/{x.username}"
                await asst.send_message(
                    NEEDTOLOG,
                    "`Unsupported Media`",
                    buttons=[[Button.url(who_n, who_l)],
                             [Button.url(where_n, where_l)]],
                )
            else:
                await asst.send_message(
                    NEEDTOLOG,
                    "`Unsupported Media`",
                    buttons=[[Button.inline(who_n, data=f"who{x.id}")],
                             [Button.url(where_n, where_l)]],
                )
        except Exception as er:
            LOGS.info(str(er))
            await ultroid_bot.send_message(
                NEEDTOLOG,
                f"Please Add Your Assistant Bot - @{asst.me.username} as admin here."
            )
    else:
        return
Example #8
0
    async def on_message(self, event):
        """
        Event handler that will add new messages to the message log.
        """
        # We want to show only messages sent to this chat
        if event.chat_id != self.chat_id:
            return

        # Save the message ID so we know which to reply to
        self.message_ids.append(event.id)

        # Decide a prefix (">> " for our messages, "<user>" otherwise)
        if event.out:
            text = '>> '
        else:
            sender = await event.get_sender()
            text = '<{}> '.format(sanitize_str(
                utils.get_display_name(sender)))

        # If the message has media show "(MediaType) "
        if event.media:
            text += '({}) '.format(event.media.__class__.__name__)

        text += sanitize_str(event.text)
        text += '\n'

        # Append the text to the end with a newline, and scroll to the end
        self.log.insert(tkinter.END, text)
        self.log.yview(tkinter.END)
def get_tlparticipants(client, tlentity, args):

    tlentity_name = utils.get_display_name(tlentity)
    destdir = get_work_dir(args)

    print(
        "------------------------------------------------------------------------------------------------"
    )
    print(">> Collecte des informations de Chanel/User/Chat : " +
          tlentity_name)
    print(
        "------------------------------------------------------------------------------------------------\n"
    )

    # Get users Participants
    tlall_participants = client.get_participants(tlentity, limit=int(limit))

    if args.type == "chat":
        tlall_participants.append(client.get_me())

    tlall_user_details = []
    print(">> Get All participants: " + str(len(tlall_participants)))

    for tlparticipant in tlall_participants:
        tlall_user_details.append({
            "id": tlparticipant.id,
            "first_name": tlparticipant.first_name,
            "last_name": tlparticipant.last_name,
            "user": tlparticipant.username,
            "phone": tlparticipant.phone,
            "is_bot": tlparticipant.bot,
            "status": "active"
        })

    dump_tlusers(destdir, tlall_user_details)
Example #10
0
    async def on_message(self, event):
        """
        Event handler that will add new messages to the message log.
        """
        # We want to show only messages sent to this chat
        if event.chat_id != self.chat_id:
            return

        # Save the message ID so we know which to reply to
        self.message_ids.append(event.id)

        # Decide a prefix (">> " for our messages, "<user>" otherwise)
        if event.out:
            text = '>> '
        else:
            sender = await event.get_sender()
            text = '<{}> '.format(utils.get_display_name(sender))

        # If the message has media show "(MediaType) "
        if event.media:
            text += '({}) '.format(event.media.__class__.__name__)

        text += event.text
        text += '\n'

        # Append the text to the end with a newline, and scroll to the end
        self.log.insert(tkinter.END, text)
        self.log.yview(tkinter.END)
Example #11
0
def getSongLinks(client, last_id):
    '''
    get links from a chat
    '''
    raw_urls = []
    first_id = ''
    # for msg in client.iter_messages('2song1day', limit=1000):
    for msg in client.iter_messages('2song1day'): # no limits!
        # print (utils.get_display_name(msg.sender), msg.message)
        if first_id == '':
            first_id = msg.id

        if msg.id == last_id:
            return raw_urls, first_id

        if int(msg.date.strftime("%y")) == 19 and  int(msg.date.strftime("%m")) >= 7 :

            if (msg.message is not None and (msg.message.count('http') > 0) ):
                print ('>>>>>>>> FOUND LINK')
                # print (utils.get_display_name(msg.sender), msg.message.split('\n')[0])
                # print (msg.message)
                print (utils.get_display_name(msg.sender), extractLink(msg.message))
                print ('-------------------')
                raw_urls.append((extractLink(msg.message),msg.date.strftime("%y-%m-%d"))) # keep only the link

    print (' ### FOUND ', len(raw_urls), ' ENTRIES ### ')
    return raw_urls, first_id
Example #12
0
async def index_message(es_client, message):
    chat = await message.get_chat()
    chat_display_name = get_display_name(chat)

    if not is_chat_enabled(chat):
        logging.debug(
            "Skipping message {} from chat '{}' as chat type {} is not enabled"
            .format(message.id, chat_display_name, get_chat_type(chat)))
        return

    sender_user = await message.get_sender()

    doc_data = {
        "timestamp": message.date,
        "sender": {
            "username": sender_user.username,
            "firstName": sender_user.first_name,
            "lastName": sender_user.last_name,
        },
        "chat": chat_display_name,
        "message": message.text
    }

    index_date_format = get_config("elasticsearch.index.date_format",
                                   required=False)
    index_prefix = get_config("elasticsearch.index.prefix", "telegram")
    if index_date_format is None:
        index_name = index_prefix
    else:
        index_name = "-".join(
            [index_prefix,
             message.date.strftime(index_date_format)])

    es_client.index(index_name, body=doc_data, id=message.id)
Example #13
0
    async def show_history(self, entity):
        # First retrieve the messages and some information
        messages = await self.get_messages(entity, limit=10)

        # Iterate over all (in reverse order so the latest appear
        # the last in the console) and print them with format:
        # "[hh:mm] Sender: Message"
        for msg in reversed(messages):
            # Note how we access .sender here. Since we made an
            # API call using the self client, it will always have
            # information about the sender. This is different to
            # events, where Telegram may not always send the user.
            name = get_display_name(msg.sender)

            # Format the message content
            if getattr(msg, 'media', None):
                self.found_media[msg.id] = msg
                content = '<{}> {}'.format(
                    type(msg.media).__name__, msg.message)

            elif hasattr(msg, 'message'):
                content = msg.message
            elif hasattr(msg, 'action'):
                content = str(msg.action)
            else:
                # Unknown message, simply print its class name
                content = type(msg).__name__

            # And print it to the user
            sprint('[{}:{}] (ID={}) {}: {}'.format(msg.date.hour,
                                                   msg.date.minute, msg.id,
                                                   name, content))
Example #14
0
async def main():
    # if no args passed, send message to myself
    recipient = 'me'
    msg = 'I just sent you this from a python script :)'
    default_msg = False

    if len(sys.argv) == 3:
        msg = sys.argv[2]
        recipient = sys.argv[1]
        default_msg = True
    elif len(sys.argv) == 2:
        recipient = sys.argv[1]

    result = await client.get_entity(recipient)
    display_name = utils.get_display_name(result)

    if len(display_name) > 0:
        print('found recipient: ' + recipient + ', display name: ' +
              display_name)
        first_name = display_name.split(' ')[0]

        if not default_msg:
            msg = 'Hey ' + first_name + '! ' + msg
    else:
        print('recipient: ' + recipient + ' not found')

    print('sending message: "' + msg + '"')

    # send message to recipient
    await client.send_message(recipient, msg)
Example #15
0
async def _(e):
    xx = await e.eor("`Muting...`")
    input = e.pattern_match.group(1).strip()
    chat = await e.get_chat()
    if e.reply_to_msg_id:
        userid = (await e.get_reply_message()).sender_id
        name = get_display_name(await e.client.get_entity(userid))
    elif input:
        try:
            userid = await e.client.parse_id(input)
            name = inline_mention(await e.client.get_entity(userid))
        except Exception as x:
            return await xx.edit(str(x))
    else:
        return await xx.eor(get_string("tban_1"), time=3)
    if userid == ultroid_bot.uid:
        return await xx.eor("`I can't mute myself.`", time=3)
    try:
        await e.client.edit_permissions(
            chat.id,
            userid,
            until_date=None,
            send_messages=False,
        )
        await eod(
            xx,
            f"`Successfully Muted` {name} `in {chat.title}`",
        )
    except BaseException as m:
        await xx.eor(f"`{m}`", time=5)
Example #16
0
async def get_all_pinned(event):
    x = await event.eor(get_string("com_1"))
    chat_id = (str(event.chat_id)).replace("-100", "")
    chat_name = get_display_name(event.chat)
    a = ""
    c = 1
    async for i in event.client.iter_messages(
            event.chat_id, filter=InputMessagesFilterPinned):
        if i.message:
            t = " ".join(i.message.split()[:4])
            txt = "{}....".format(t)
        else:
            txt = "Go to message."
        a += f"{c}. <a href=https://t.me/c/{chat_id}/{i.id}>{txt}</a>\n"
        c += 1

    if c == 1:
        m = f"<b>The pinned message in {chat_name}:</b>\n\n"
    else:
        m = f"<b>List of pinned message(s) in {chat_name}:</b>\n\n"

    if a == "":
        return await eor(x, get_string("listpin_1"), time=5)

    await x.edit(m + a, parse_mode="html")
Example #17
0
async def handler(event):
    amount = 0
    joincount = 0
    fleecount = 0
    autocount = 0
    manualcount = 0
    buttoncount = 0
    for databases in listdir('./databases'):
        amount += 1
        tempfile = open('./databases/{}'.format(databases))
        tempbase = json.load(tempfile)
        for userids in tempbase["users"]:
            if userids[0] == event.from_id:
                joincount += userids[1]
                fleecount += userids[2]
                autocount += userids[3]
                manualcount += userids[4]
                buttoncount += userids[6]
        tempfile.close()
    await event.reply("Hey [{}](tg://user?id={}), here are your stats for the army:\n"
                      "You joined us {} times\n"
                      "You fleed us {} times\n"
                      "You used autolynch {} times\n"
                      "You used manual lynch {} times\n"
                      "You pressed {} buttons".format(get_display_name(await event.get_sender()),
                                                      event.from_id, joincount / amount,
                                                      fleecount / amount, autocount / amount,
                                                      manualcount / amount, buttoncount))
Example #18
0
async def get_id(e):
    custom = e.pattern_match.group(1)
    if custom:
        try:
            custom = int(custom)
        except ValueError:
            pass
        try:
            en = await e.client.get_entity(custom)
        except ValueError:
            await e.edit("err \\\nUnknown entity")
            return
        id = await e.client.get_peer_id(en)
        text = html.escape(get_display_name(en))
        if isinstance(en, User):
            text = f'<a href="tg://user?id={id}">{text}</a>'
        elif getattr(en, "username", None):
            text = f'<a href="tg://resolve?domain={en.username}">{text}</a>'
        text += f"'s ID: <code>{id}</code>"
        await e.edit(text, parse_mode="HTML")
        return
    text = f"👥 ChatID[<code>{e.chat_id}</code>]\n"
    text += f"💬 MessageID[<code>{e.id}</code>]\n"
    text += f'🙋‍♂️ YourID[<code>{e.from_id}</code>, <a href="tg://user?id={e.from_id}">link</a>]\n'
    if e.is_reply:
        text += "\n"
        r = await e.get_reply_message()
        text += f"RepliedMessageID[<code>{r.id}</code>]\n"
        text += f'RepliedSenderID[<code>{r.from_id}</code>, <a href="tg://user?id={r.from_id}">link</a>]\n'
        if getattr(r.fwd_from, "from_id", None):
            text += f'RepliedForwardSenderID[<code>{r.fwd_from.from_id}</code>, <a href="tg://user?id={r.fwd_from.from_id}">link</a>]\n'
    await e.edit(text, parse_mode="HTML")
Example #19
0
async def unban(event):
    if ((event.is_channel or event.is_group)
            and not (event.chat.creator or event.chat.admin_rights.ban_users)):
        await event.edit("`You do not have rights to un-ban users in here!`")
        return

    user, reason, exception = await get_entity_from_msg(event)
    if user:
        if exception:
            await event.edit(f"`Un-ban machine broke!\n{user}`")
            return

    try:
        await client.edit_permissions(entity=await event.get_input_chat(),
                                      user=user,
                                      view_messages=True,
                                      send_messages=True,
                                      send_media=True,
                                      send_stickers=True,
                                      send_gifs=True,
                                      send_games=True,
                                      send_inline=True,
                                      send_polls=True)
        text = "`Successfully un-banned ``{}`` (``{}``)!`"
        if reason:
            text += f"\n`Reason:` `{reason}`"
        await event.edit(text.format(get_display_name(user), user.id))
    except Exception as e:
        await event.edit(f"`{e}`")
        LOGGER.exception(e)
Example #20
0
    async def kick_users():
        global chosen
        while True:
            clicked.clear()
            users = await bot.get_participants(GROUP)

            # Delete people who talked before but have left the group
            left = last_talked.keys() - {x.id for x in users}
            for x in left:
                del last_talked[x]

            lo = min(last_talked.values(), default=0)
            hi = time.time()
            delta = hi - lo
            if delta <= 0.0:
                chosen = random.choice(users)
            else:
                weights = (1 - ((last_talked.get(x.id, lo) - lo) / delta)
                           for x in users)
                chosen = random.choices(users, weights)[0]

            chosen.name = html.escape(utils.get_display_name(chosen))
            start = time.time()
            try:
                await kick_user()
            except Exception:
                logging.exception('exception on kick user')

            took = time.time() - start
            wait_after_clicked = 8 * 60 * 60 - took
            if wait_after_clicked > 0:
                await asyncio.sleep(DELAY - took)
Example #21
0
    def __init__(self, master=None, **kwargs):

        # Set the custom attributes and pop'em out
        self.entity = kwargs.pop("entity")

        # Initialize the frame
        kwargs["borderwidth"] = 2
        kwargs["relief"] = "ridge"
        super().__init__(master, **kwargs)

        # Set up our custom widget
        self.profile_picture = Label(self)
        self.profile_picture.grid(row=0, column=0, sticky=NSEW)

        self.right_column = Frame(self, padding=(16, 0))
        self.right_column.grid(row=0, column=1)

        self.name_label = Label(
            self.right_column, text=sanitize_string(get_display_name(self.entity)), font="-weight bold -size 14"
        )
        self.name_label.grid(row=0, sticky=NW)

        if hasattr(self.entity, "username"):
            self.username_label = Label(self.right_column, text="@{}".format(self.entity.username), font="-size 12")
            self.username_label.grid(row=1, sticky=NW)

        if hasattr(self.entity, "phone"):
            self.phone_label = Label(self.right_column, text="+{}".format(self.entity.phone))
            self.phone_label.grid(row=2, sticky=NW)

        elif hasattr(self.entity, "participants_count"):
            self.participants_label = Label(
                self.right_column, text="{} participants".format(self.entity.participants_count)
            )
            self.participants_label.grid(row=2, sticky=NW)
Example #22
0
    async def download_past_media(self, dumper, target_id):
        """
        下载已经转储到数据库但尚未下载的媒体。
        格式化文件名之后已存在的文件的媒体将被忽略,不会再次重新下载。
        """
        # TODO Should this respect and download only allowed media? Or all?
        target_in = await self.client.get_input_entity(target_id)
        target = await self.client.get_entity(target_in)
        target_id = utils.get_peer_id(target)

        rows = db_message.find({
            'context_id': target_id,
            "check": {
                '$ne': None
            }
        })
        for row in rows:
            await self._media_queue.put(
                (row['media_id'], target_id, row['from_id'],
                 datetime.datetime.utcfromtimestamp(row['date'])))
        chat_name = utils.get_display_name(target)
        media_consumers = [
            asyncio.ensure_future(self._media_consumer(self._media_queue,
                                                       chat_name, i),
                                  loop=self.loop) for i in range(10)
        ]
        await asyncio.wait(media_consumers)
Example #23
0
    async def __get_entity(self) -> None:
        """
        Returns chosen peer
        """
        entities = [
            d.entity for d in await self.get_dialogs(limit=self.__limit)
        ]

        entities = [
            entity for entity in entities
            if isinstance(entity, User if self.__dialogs else Channel)
        ]
        if not self.__dialogs and not self.__channels:
            entities = [entity for entity in entities if entity.megagroup]

        if not entities:
            raise TgEraserException("You aren't joined to any chat.")

        print_header("Dialogs")
        for i, entity in enumerate(entities, start=1):
            sprint(f"{i}. {get_display_name(entity)}\t | {entity.id}")

        num = cast_to_int(await async_input("\nChoose peer: "), "peer")
        self.__entities = [entities[int(num) - 1]]
        self.__display_name = get_display_name(self.__entities[0])
        print(self.__display_name)
        print("Chosen: " + self.__display_name)
Example #24
0
async def all_messages_catcher(event):
    # the bot might not have the required access_hash to mention the appropriate PM
    await event.forward_to(Config.TG_BOT_USER_NAME_BF_HER)

    # construct message
    # the message format is stolen from @MasterTagAlertBot
    ammoca_message = ""

    who_ = await event.client.get_entity(event.from_id)
    if (who_.bot or who_.verified or who_.support):
        return

    who_m = f"[{get_display_name(who_)}](tg://user?id={who_.id})"

    where_ = await event.client.get_entity(event.chat_id)

    where_m = get_display_name(where_)
    button_text = "Check 🚶"

    if isinstance(where_, Chat):
        message_link = f"https://t.me/c/{where_.id}/{event.id}"
    else:
        # not an official link,
        # only works in DrKLO/Telegram,
        # for some reason
        message_link = f"tg://openmessage?chat_id={where_.id}&message_id={event.id}"
        # Telegram is weird :\

    ammoca_message += f"User {who_m} Have Tagged You Here -> [{where_m}]({message_link}) \nCheck Message 👇 "
    log_chat = Config.PRIVATE_GROUP_ID
    await tgbot.send_message(
        log_chat,
        message=ammoca_message,
        link_preview=False,
        buttons=[[custom.Button.url(button_text, message_link)]])
async def live_lottery_group(event):
    sender = await event.get_sender()
    from_name = utils.get_display_name(sender)
    from_id = utils.get_peer_id(sender)
    logging.info(f'来自{event.chat_id}: {from_id} | {from_name}说的>>{event.message.text}')
    if event.chat_id == group_id:
        await client.forward_messages(forward_bot_id, event.message)
Example #26
0
    async def kick_users():
        global chosen
        while True:
            clicked.clear()
            users = await bot.get_participants(GROUP)

            # Delete people who talked before but have left the group
            left = last_talked.keys() - {x.id for x in users}
            for x in left:
                del last_talked[x]

            chosen, delay = pick_target_file(users)
            if chosen is None:
                warn = True
                chosen, delay = pick_random(users)
            else:
                warn = False

            chosen.name = html.escape(utils.get_display_name(chosen))
            start = time.time()
            try:
                await kick_user(delay, warn=warn)
            except Exception:
                logging.exception('exception on kick user')
            finally:
                # This may or may not fix a bug where we spam "kicked inactive"
                chosen = None

            took = time.time() - start
            wait_after_clicked = 8 * 60 * 60 - took
            if wait_after_clicked > 0:
                # It's OK if it's negative, will sleep(0)
                await asyncio.sleep(delay - took)
Example #27
0
async def all_messages_catcher(event):
    if udB.get("TAG_LOG") is not None:
        NEEDTOLOG = int(udB.get("TAG_LOG"))
        await event.forward_to(NEEDTOLOG)
        ammoca_message = ""
        who_ = await event.client.get_entity(event.sender_id)
        if who_.bot or who_.verified or who_.support:
            return
        who_m = f"[{get_display_name(who_)}](tg://user?id={who_.id})"
        where_ = await event.client.get_entity(event.chat_id)
        where_m = get_display_name(where_)
        button_text = "📨 Go to Message  "
        if isinstance(where_, Channel):
            message_link = f"https://t.me/c/{where_.id}/{event.id}"
            chat_link = f"https://t.me/c/{where_.id}"
        else:
            message_link = f"tg://openmessage?chat_id={where_.id}&message_id={event.id}"
            chat_link = f"tg://openmessage?chat_id={where_.id}"
        ammoca_message += f"{who_m} tagged you in [{where_m}]({chat_link})"
        try:
            await asst.send_message(
                entity=NEEDTOLOG,
                message=ammoca_message,
                link_preview=False,
                buttons=[[custom.Button.url(button_text, message_link)]],
                silent=True,
            )
        except BaseException:
            pass
    else:
        return
Example #28
0
async def list_all(event):
    ultroid_bot = event.client
    x = await event.eor(get_string("com_1"))
    channels = get_destinations()
    num = get_no_destinations()
    if not num:
        return await eor(x, "No chats were added.", time=5)
    msg = get_string("cha_7")
    for channel in channels:
        name = ""
        try:
            name = get_display_name(await ultroid_bot.get_entity(int(channel)))
        except BaseException:
            name = ""
        msg += f"\n=> **{name}** [`{channel}`]"
    msg += f"\nTotal {get_no_destinations()} channels."
    if len(msg) > 4096:
        MSG = msg.replace("*", "").replace("`", "")
        with io.BytesIO(str.encode(MSG)) as out_file:
            out_file.name = "channels.txt"
            await ultroid_bot.send_file(
                event.chat_id,
                out_file,
                force_document=True,
                allow_cache=False,
                caption="Destination channels in database",
                reply_to=event,
            )
            await x.delete()
    else:
        await x.edit(msg)
Example #29
0
async def ban(event):
    if ((event.is_channel or event.is_group)
            and not (event.chat.creator or event.chat.admin_rights.ban_users)):
        await event.edit("`You do not have rights to ban users in here!`")
        return

    user, reason, exception = await get_entity_from_msg(event)
    if user:
        if exception:
            await event.edit(f"`Ban machine broke!\n{user}`")
            return

    try:
        await client.edit_permissions(entity=await event.get_input_chat(),
                                      user=user,
                                      view_messages=False)
        text = "`Successfully banned ``{}`` (``{}``)!`"
        if reason:
            text += f"\n`Reason:` `{reason}`"
        await event.edit(text.format(get_display_name(user), user.id))
    except Exception as e:
        await event.edit("`An exception occured trying to ban. "
                         " Make sure you have the correct rights! "
                         "Check the logs for more information.`")
        LOGGER.exception(e)
Example #30
0
async def get_chat_link(arg: Union[types.User, types.Chat, types.Channel,
                                   NewMessage.Event],
                        reply=None) -> str:
    if isinstance(arg, (types.User, types.Chat, types.Channel)):
        entity = arg
    else:
        entity = await arg.get_chat()

    if isinstance(entity, types.User):
        if entity.is_self:
            name = "yourself"
        else:
            name = get_display_name(entity) or "Deleted Account?"
        extra = f"[{name}](tg://user?id={entity.id})"
    else:
        if hasattr(entity, 'username') and entity.username is not None:
            username = '******' + entity.username
        else:
            username = entity.id
        if reply is not None:
            if isinstance(username, str) and username.startswith('@'):
                username = username[1:]
            else:
                username = f"c/{username}"
            extra = f"[{entity.title}](https://t.me/{username}/{reply})"
        else:
            if isinstance(username, int):
                username = f"`{username}`"
                extra = f"{entity.title} ( {username} )"
            else:
                extra = f"[{entity.title}](tg://resolve?domain={username})"
    return extra
Example #31
0
async def promote(event):
    if ((event.is_channel or event.is_group) and
            not (event.chat.creator or event.chat.admin_rights.add_admins)):
        await event.edit("`You do not have rights to add admins in here!`")
        return

    user, extra, exception = await get_entity_from_msg(event)
    if user:
        if exception:
            await event.edit(f"`Promote machine broke!\n{user}`")
            return

    try:
        await client.edit_admin(
            entity=await event.get_input_chat(),
            post_messages=True if event.is_channel else False,
            edit_messages=True if event.is_channel else False,
            user=user,
            is_admin=True,
            title=extra)
        text = "`Successfully promoted ``{}`` (``{}``)!`"
        if extra:
            text += f"\n`Title:` `{extra}`"
        await event.edit(text.format(get_display_name(user), user.id))
    except Exception as e:
        await event.edit("`An exception occured trying to promote. "
                         " Make sure you have the correct rights! "
                         "Check the logs for more information.`")
        LOGGER.exception(e)
Example #32
0
def get_message(client):
    me = client.get_me()
    group_name_list=[]
    responses = client.iter_dialogs()
    if responses is not None:
        for response in responses:
            # if isinstance(response.entity, Channel):  # 过滤群组
            print(response)
            group_name_list.append(response.name)

    #循环爬取全部群组消息
    for name in group_name_list:
        id = name
        channel_item = client.get_entity(id)  # 获取channel这个entity的信息
        messages = client.iter_messages(id)

        #写入文件,或者数据库

        f = open(id + '.csv', 'w', encoding='utf-8-sig')
        csv_writer = csv.writer(f)
        csv_writer.writerow(["date", "sender", "message"])
        for message in messages:
            csv_writer.writerow([str(message.date), str(utils.get_display_name(message.sender)),
                                 str(message.message).replace('\r', '').replace('\n', '').replace('\t', '')])#过滤消息中的换行
        f.close()
        print(id, 'over')
Example #33
0
    async def download_past_media(self, dumper, target_id):
        """
        Downloads the past media that has already been dumped into the
        database but has not been downloaded for the given target ID yet.

        Media which formatted filename results in an already-existing file
        will be *ignored* and not re-downloaded again.
        """
        # TODO Should this respect and download only allowed media? Or all?
        target_in = await self.client.get_input_entity(target_id)
        target = await self.client.get_entity(target_in)
        target_id = utils.get_peer_id(target)
        bar = tqdm.tqdm(unit='B',
                        desc='media',
                        unit_divisor=1000,
                        unit_scale=True,
                        bar_format=BAR_FORMAT,
                        total=0,
                        postfix={'chat': utils.get_display_name(target)})

        msg_cursor = dumper.conn.cursor()
        msg_cursor.execute(
            'SELECT ID, Date, FromID, MediaID FROM Message '
            'WHERE ContextID = ? AND MediaID IS NOT NULL', (target_id, ))

        msg_row = msg_cursor.fetchone()
        while msg_row:
            await self._download_media(media_id=msg_row[3],
                                       context_id=target_id,
                                       sender_id=msg_row[2],
                                       date=msg_row[1],
                                       bar=bar)
            msg_row = msg_cursor.fetchone()
Example #34
0
    def enqueue_entities(self, entities):
        """
        Enqueues the given iterable of entities to be dumped later by a
        different coroutine. These in turn might enqueue profile photos.
        """
        for entity in entities:
            eid = utils.get_peer_id(entity)
            self._displays[eid] = utils.get_display_name(entity)
            if isinstance(entity, types.User):
                if entity.deleted or entity.min:
                    continue  # Empty name would cause IntegrityError
            elif isinstance(entity, types.Channel):
                if entity.left:
                    continue  # Getting full info triggers ChannelPrivateError
            elif not isinstance(entity,
                                (types.Chat, types.InputPeerUser,
                                 types.InputPeerChat, types.InputPeerChannel)):
                # Drop UserEmpty, ChatEmpty, ChatForbidden and ChannelForbidden
                continue

            if eid in self._checked_entity_ids:
                continue
            else:
                self._checked_entity_ids.add(eid)
                if isinstance(entity, (types.User, types.InputPeerUser)):
                    self._user_queue.put_nowait(entity)
                else:
                    self._chat_queue.put_nowait(entity)
    def update_conversation_list(self):
        """Updates the conversation list with the currently
           loaded entities and filtered by the current search"""
        search = self.search_box.get().lower()
        self.conversation_list.delete(0, END)

        for entity in self.entities:
            display = sanitize_string(get_display_name(entity))
            if search in display.lower():
                self.conversation_list.insert(END, display)
Example #36
0
 def set_signed_in(self, me):
     """
     Configures the application as "signed in" (displays user's
     name and disables the entry to input phone/bot token/code).
     """
     self.me = me
     self.sign_in_label.configure(text='Signed in')
     self.sign_in_entry.configure(state=tkinter.NORMAL)
     self.sign_in_entry.delete(0, tkinter.END)
     self.sign_in_entry.insert(tkinter.INSERT, utils.get_display_name(me))
     self.sign_in_entry.configure(state=tkinter.DISABLED)
     self.sign_in_button.configure(text='Log out')
     self.chat.focus()
Example #37
0
    async def handler(event):
        """
        #haste: Replaces the message you reply to with a hastebin link.
        """
        await event.delete()
        if not event.reply_to_msg_id:
            return

        msg = await event.get_reply_message()
        if len(msg.raw_text or '') < 200:
            return

        sent = await event.respond(
            'Uploading paste…', reply_to=msg.reply_to_msg_id)

        name = html.escape(
            utils.get_display_name(await msg.get_sender()) or 'A user')

        text = msg.raw_text
        code = ''
        for _, string in msg.get_entities_text((
                types.MessageEntityCode, types.MessageEntityPre)):
            code += f'{string}\n'
            text = text.replace(string, '')

        code = code.rstrip()
        if code:
            text = re.sub(r'\s+', ' ', text)
        else:
            code = msg.raw_text
            text = ''

        async with aiohttp.ClientSession() as session:
            async with session.post('https://hastebin.com/documents',
                                    data=code.encode('utf-8')) as resp:
                if resp.status >= 300:
                    await sent.edit("Hastebin seems to be down… ( ^^')")
                    return

                haste = (await resp.json())['key']

        await asyncio.wait([
            msg.delete(),
            sent.edit(f'<a href="tg://user?id={msg.sender_id}">{name}</a> '
                      f'said: {text} hastebin.com/{haste}.py'
                      .replace('  ', ' '), parse_mode='html')
        ])
    def on_next(self, event=None):
        """Gets fired after the Next button is clicked"""
        # Ensure the user has selected an entity
        selection = self.conversation_list.curselection()
        if selection:
            index = selection[0]
            value = self.conversation_list.get(index)

            # Search for the matching entity (user or chat)
            # TODO Note that this will NOT work if they have the exact same name!
            for entity in self.entities:
                display = sanitize_string(get_display_name(entity))
                if value == display:
                    self.master.destroy()
                    # Import the window here to avoid cyclic dependencies
                    from gui.windows import BackupWindow
                    start_app(BackupWindow, entity=entity)
Example #39
0
    def __init__(self, master=None, **args):
        super().__init__(master)

        # Save our entity and its display
        self.entity = args['entity']
        self.display = sanitize_string(get_display_name(self.entity))

        # Get a cached client and initialize a backuper instance with it
        self.client = get_cached_client()
        self.backuper = Backuper(self.client, self.entity)
        self.backuper.on_metadata_change = self.on_metadata_change

        # Set up the frame itself
        self.master.title('Backup with {}'.format(self.display))
        self.pack(padx=16, pady=16)
        self.create_widgets()

        # Download the profile picture in a different thread
        Thread(target=self.dl_propic).start()
    async def run(self):
        """Main loop of the TelegramClient, will wait for user action"""

        # Once everything is ready, we can add an event handler.
        #
        # Events are an abstraction over Telegram's "Updates" and
        # are much easier to use.
        self.add_event_handler(self.message_handler, events.NewMessage)

        # Enter a while loop to chat as long as the user wants
        while True:
            # Retrieve the top dialogs. You can set the limit to None to
            # retrieve all of them if you wish, but beware that may take
            # a long time if you have hundreds of them.
            dialog_count = 15

            # Entities represent the user, chat or channel
            # corresponding to the dialog on the same index.
            dialogs = await self.get_dialogs(limit=dialog_count)

            i = None
            while i is None:
                print_title('Dialogs window')

                # Display them so the user can choose
                for i, dialog in enumerate(dialogs, start=1):
                    sprint('{}. {}'.format(i, get_display_name(dialog.entity)))

                # Let the user decide who they want to talk to
                print()
                print('> Who do you want to send messages to?')
                print('> Available commands:')
                print('  !q: Quits the dialogs window and exits.')
                print('  !l: Logs out, terminating this session.')
                print()
                i = await async_input('Enter dialog ID or a command: ')
                if i == '!q':
                    return
                if i == '!l':
                    # Logging out will cause the user to need to reenter the
                    # code next time they want to use the library, and will
                    # also delete the *.session file off the filesystem.
                    #
                    # This is not the same as simply calling .disconnect(),
                    # which simply shuts down everything gracefully.
                    await self.log_out()
                    return

                try:
                    i = int(i if i else 0) - 1
                    # Ensure it is inside the bounds, otherwise retry
                    if not 0 <= i < dialog_count:
                        i = None
                except ValueError:
                    i = None

            # Retrieve the selected user (or chat, or channel)
            entity = dialogs[i].entity

            # Show some information
            print_title('Chat with "{}"'.format(get_display_name(entity)))
            print('Available commands:')
            print('  !q:  Quits the current chat.')
            print('  !Q:  Quits the current chat and exits.')
            print('  !h:  prints the latest messages (message History).')
            print('  !up  <path>: Uploads and sends the Photo from path.')
            print('  !uf  <path>: Uploads and sends the File from path.')
            print('  !d   <msg-id>: Deletes a message by its id')
            print('  !dm  <msg-id>: Downloads the given message Media (if any).')
            print('  !dp: Downloads the current dialog Profile picture.')
            print('  !i:  Prints information about this chat..')
            print()

            # And start a while loop to chat
            while True:
                msg = await async_input('Enter a message: ')
                # Quit
                if msg == '!q':
                    break
                elif msg == '!Q':
                    return

                # History
                elif msg == '!h':
                    # First retrieve the messages and some information
                    messages = await self.get_messages(entity, limit=10)

                    # Iterate over all (in reverse order so the latest appear
                    # the last in the console) and print them with format:
                    # "[hh:mm] Sender: Message"
                    for msg in reversed(messages):
                        # Note how we access .sender here. Since we made an
                        # API call using the self client, it will always have
                        # information about the sender. This is different to
                        # events, where Telegram may not always send the user.
                        name = get_display_name(msg.sender)

                        # Format the message content
                        if getattr(msg, 'media', None):
                            self.found_media[msg.id] = msg
                            content = '<{}> {}'.format(
                                type(msg.media).__name__, msg.message)

                        elif hasattr(msg, 'message'):
                            content = msg.message
                        elif hasattr(msg, 'action'):
                            content = str(msg.action)
                        else:
                            # Unknown message, simply print its class name
                            content = type(msg).__name__

                        # And print it to the user
                        sprint('[{}:{}] (ID={}) {}: {}'.format(
                            msg.date.hour, msg.date.minute, msg.id, name, content))

                # Send photo
                elif msg.startswith('!up '):
                    # Slice the message to get the path
                    path = msg[len('!up '):]
                    await self.send_photo(path=path, entity=entity)

                # Send file (document)
                elif msg.startswith('!uf '):
                    # Slice the message to get the path
                    path = msg[len('!uf '):]
                    await self.send_document(path=path, entity=entity)

                # Delete messages
                elif msg.startswith('!d '):
                    # Slice the message to get message ID
                    msg = msg[len('!d '):]
                    deleted_msg = await self.delete_messages(entity, msg)
                    print('Deleted {}'.format(deleted_msg))

                # Download media
                elif msg.startswith('!dm '):
                    # Slice the message to get message ID
                    await self.download_media_by_id(msg[len('!dm '):])

                # Download profile photo
                elif msg == '!dp':
                    print('Downloading profile picture to usermedia/...')
                    os.makedirs('usermedia', exist_ok=True)
                    output = await self.download_profile_photo(entity,
                                                               'usermedia')
                    if output:
                        print('Profile picture downloaded to', output)
                    else:
                        print('No profile picture found for this user!')

                elif msg == '!i':
                    attributes = list(entity.to_dict().items())
                    pad = max(len(x) for x, _ in attributes)
                    for name, val in attributes:
                        print("{:<{width}} : {}".format(name, val, width=pad))

                # Send chat message (if any)
                elif msg:
                    await self.send_message(entity, msg, link_preview=False)
    def run(self):
        # Listen for updates
        self.add_update_handler(self.update_handler)

        # Enter a while loop to chat as long as the user wants
        while True:
            # Retrieve the top dialogs
            dialog_count = 10

            # Entities represent the user, chat or channel
            # corresponding to the dialog on the same index
            dialogs, entities = self.get_dialogs(dialog_count)

            i = None
            while i is None:
                print_title('Dialogs window')

                # Display them so the user can choose
                for i, entity in enumerate(entities, start=1):
                    sprint('{}. {}'.format(i, get_display_name(entity)))

                # Let the user decide who they want to talk to
                print()
                print('> Who do you want to send messages to?')
                print('> Available commands:')
                print('  !q: Quits the dialogs window and exits.')
                print('  !l: Logs out, terminating this session.')
                print()
                i = input('Enter dialog ID or a command: ')
                if i == '!q':
                    return
                if i == '!l':
                    self.log_out()
                    return

                try:
                    i = int(i if i else 0) - 1
                    # Ensure it is inside the bounds, otherwise retry
                    if not 0 <= i < dialog_count:
                        i = None
                except ValueError:
                    i = None

            # Retrieve the selected user (or chat, or channel)
            entity = entities[i]

            # Show some information
            print_title('Chat with "{}"'.format(get_display_name(entity)))
            print('Available commands:')
            print('  !q: Quits the current chat.')
            print('  !Q: Quits the current chat and exits.')
            print('  !h: prints the latest messages (message History).')
            print('  !up <path>: Uploads and sends the Photo from path.')
            print('  !uf <path>: Uploads and sends the File from path.')
            print('  !dm <msg-id>: Downloads the given message Media (if any).')
            print('  !dp: Downloads the current dialog Profile picture.')
            print()

            # And start a while loop to chat
            while True:
                msg = input('Enter a message: ')
                # Quit
                if msg == '!q':
                    break
                elif msg == '!Q':
                    return

                # History
                elif msg == '!h':
                    # First retrieve the messages and some information
                    total_count, messages, senders = self.get_message_history(
                        entity, limit=10)

                    # Iterate over all (in reverse order so the latest appear
                    # the last in the console) and print them with format:
                    # "[hh:mm] Sender: Message"
                    for msg, sender in zip(
                            reversed(messages), reversed(senders)):
                        # Get the name of the sender if any
                        if sender:
                            name = getattr(sender, 'first_name', None)
                            if not name:
                                name = getattr(sender, 'title')
                                if not name:
                                    name = '???'
                        else:
                            name = '???'

                        # Format the message content
                        if getattr(msg, 'media', None):
                            self.found_media.add(msg)
                            # The media may or may not have a caption
                            caption = getattr(msg.media, 'caption', '')
                            content = '<{}> {}'.format(
                                type(msg.media).__name__, caption)

                        elif hasattr(msg, 'message'):
                            content = msg.message
                        elif hasattr(msg, 'action'):
                            content = str(msg.action)
                        else:
                            # Unknown message, simply print its class name
                            content = type(msg).__name__

                        # And print it to the user
                        sprint('[{}:{}] (ID={}) {}: {}'.format(
                               msg.date.hour, msg.date.minute, msg.id, name,
                               content))

                # Send photo
                elif msg.startswith('!up '):
                    # Slice the message to get the path
                    self.send_photo(path=msg[len('!up '):], entity=entity)

                # Send file (document)
                elif msg.startswith('!uf '):
                    # Slice the message to get the path
                    self.send_document(path=msg[len('!uf '):], entity=entity)

                # Download media
                elif msg.startswith('!dm '):
                    # Slice the message to get message ID
                    self.download_media(msg[len('!dm '):])

                # Download profile photo
                elif msg == '!dp':
                    output = str('usermedia/propic_{}'.format(entity.id))
                    print('Downloading profile picture...')
                    success = self.download_profile_photo(entity.photo, output)
                    if success:
                        print('Profile picture downloaded to {}'.format(
                            output))
                    else:
                        print('No profile picture found for this user.')

                # Send chat message (if any)
                elif msg:
                    self.send_message(
                        entity, msg, link_preview=False)
Example #42
0
async def handler(event):
    sender = await event.get_sender()
    name = utils.get_display_name(sender)
    print(name, 'said', event.text, '!')