Beispiel #1
0
    def __init__(self, api_id, api_hash, new_data_event: threading.Event, update_queue: queue.Queue):
        self.loop = asyncio.get_event_loop()  # asyncio loop
        self.database = Database()

        # support updating
        self.last_update = {}
        self.updated = set()
        self.new_data_event = new_data_event
        self.update_queue = update_queue

        self.client = TelegramClient('session', api_id, api_hash)
        self.client.start()

        # using decorators
        self.client.on(events.NewMessage())(self._new_message_handler)
        self.client.on(events.MessageEdited())(self._edit_message_handler)
        self.client.on(events.MessageRead())(self._read_message_handler)

        # updating data before start
        self.loop.create_task(self._update_dialogs())

        # starting real time updates
        self.loop.create_task(self._run_until_disconnected())
        self.loop.create_task(self.__autoupdate_dialogs())

        # starting updates_handler
        self.loop.create_task(self._updates_handler())
Beispiel #2
0
async def await_read(chat, message):
    chat = telethon.utils.get_peer_id(chat)

    async def read_filter(read_event):
        return read_event.chat_id == chat and read_event.is_read(message)

    fut = borg.await_event(events.MessageRead(inbox=False), read_filter)
    if await is_read(borg, chat, message):
        fut.cancel()
        return
    await fut
Beispiel #3
0
async def wait_for_updates(saver):
    """
    :type saver: DialogSaver
    """
    client = saver.client

    @client.on(events.NewMessage())
    @client.on(events.MessageEdited())
    async def message_updated_handler(event):
        await event.get_chat()
        await event.get_sender()
        if await filter_event(event):
            saver.save_dialog(event.chat.id,
                              get_display_name(event.chat))  # the dialog
            await saver.process_message(message=event.message,
                                        dialog_id=event.chat_id)

    @client.on(events.MessageRead())
    async def message_read_handler(event):
        if await filter_event(event):
            read_time = datetime.utcnow()
            message_ids = event._message_ids or [event._message_id]
            for message_id in message_ids:
                saver.set_message_attributes(message_id,
                                             {"read_time": read_time},
                                             commit=False)
            saver.commit()

    @client.on(events.MessageDeleted())
    async def message_delete_handler(event):
        if await filter_event(event):
            for message_id in event.deleted_ids:
                saver.set_message_attributes(message_id, {"deleted": True},
                                             commit=False)
            saver.commit()

    while True:
        try:
            logger.info("Catching up")
            await client.catch_up()

            logger.info("Waiting for updates...")
            await client.run_until_disconnected()
        except ConnectionError:
            await sleep(10)
Beispiel #4
0
            (r'(?i)too', case_matcher('twoo')),
            ('!', lambda m: ' ' + random.choice(faces))]
patterns = [(re.compile(pattern), sub) for pattern, sub in patterns]
original_texts = {}


@client.on(events.NewMessage(outgoing=True, pattern=re.compile(r'^[^!]')))
def owo(event):
    new_text = event.text
    for pattern, sub in patterns:
        new_text = pattern.sub(sub, new_text)
    if new_text != event.text:
        original_texts[event.message.id] = event.text
        event.edit(new_text, link_preview=bool(event.message.media))
        raise events.StopPropagation


@client.on(events.MessageRead(inbox=False))
def ninja(event):
    edited = []
    for message_id in original_texts:
        if event.is_read(message_id):
            logger.info('editing {} "{}"'.format(message_id,
                                                 original_texts[message_id]))
            client.edit_message(event.input_chat, message_id,
                                original_texts[message_id])
            edited.append(message_id)

    for message_id in edited:
        del original_texts[message_id]
Beispiel #5
0
        if event.is_channel:
            print(user.stringify())
            await client.send_message(1372737953,
                                      user.title + " : " + "`" + str(user.id) +
                                      "`",
                                      link_preview=False)
            return
        if event.is_group:
            await client.send_message(1372737953,
                                      user.title + " : " + "`" + str(user.id) +
                                      "`",
                                      link_preview=False)
            return


@events.register(events.MessageRead(func=lambda e: e.is_private))
async def messageRead(event):
    user = await event.get_chat()
    message = await client.get_messages(user, ids=event.max_id)
    await client.send_message(1372737953,
                              "[" + user.username.capitalize() + "]" + "(" +
                              "https://t.me/" + user.username + ")" +
                              " Has Read My Message " + "👇",
                              link_preview=False)
    await message.forward_to(1372737953)


@events.register(events.NewMessage())
async def newMessage(event):
    print(await event.get_chat())
Beispiel #6
0
        app_log.debug(msg)
    except Exception as e:
        event = event.stringify()
        trace = traceback.format_exc()
        app_log.warning(event, exc_info=True)
        app_log.warning(str(chat_info))
        sink_sms.send_notif(
            "Telegram message parsing failed!\n%s" %
            '\n'.join([event, trace, str(chat_info)]))
    try:
        client.session.save()
    except Exception as e:
        app_log.warning("Could not save session:\n" + e)


@client.on(events.MessageRead())
async def callback_read(event):
    app_log.debug(event)
    chat_info = {'ID': event.max_id, 'Status': 'read'}
    if 'original_update' in event:
        try:
            if event.outbox:
                chat_info.update(await
                                 get_outgoing_info(client, app_log,
                                                   event.original_update.peer))
            else:
                chat_info.update(await
                                 get_incoming_info(client, app_log,
                                                   event.original_update.peer))
            app_log.info(chat_info)
            sink_sms.send_dict(IDENTIFIER, None, chat_info)