Exemplo n.º 1
0
async def delete(event):
    if event.reply_to_msg_id:
        chat = await event.get_chat()
        try:
            if isinstance(chat, Channel):  # channel or supergroup
                update = await event.client(
                    DeleteMessagesRequest(chat.id, [event.reply_to_msg_id]))
            else:
                # chat id isn't required to delete messages in normal groups or in PMs
                update = await event.client(
                    DeleteMessagesRequestGPM([event.reply_to_msg_id],
                                             revoke=True))
            if not update.pts_count:  # pts_count is set to 1 if target message has been deleted
                await event.edit(msgRep.CANNOT_DEL_MSG)
                return
            await event.delete()
        except MessageDeleteForbiddenError:
            await event.edit(msgRep.UNABLE_DEL_MSG)
        except Exception as e:
            log.warning(e)
            await event.edit(msgRep.DEL_MSG_FAILED)
    else:
        await event.edit(msgRep.REPLY_DEL_MSG)

    return
Exemplo n.º 2
0
async def purge(event):
    """ Please don't abuse this feature to delete someone's else whole group history, for real, just don't """
    if event.reply_to_msg_id:
        chat = await event.get_chat()
        channel_obj = True if isinstance(
            chat, Channel) else False  # Channel or supergroup
        chat_obj = True if isinstance(chat, Chat) else False  # Normal group

        if channel_obj or chat_obj:
            if not chat.creator and not chat.admin_rights:
                await event.edit(msgRep.NO_ADMIN_PURGE)
                return
            if chat.admin_rights and not chat.admin_rights.delete_messages:
                await event.edit(msgRep.NO_DEL_PRIV)
                return

        message_ids = []
        wait_time_sec = 2  # Prevent FloodWaitError
        async for message in event.client.iter_messages(
                entity=chat.id,
                min_id=event.reply_to_msg_id,
                wait_time=wait_time_sec):
            message_ids.append(message.id)

        message_ids.append(
            event.reply_to_msg_id)  # last but not least add replied message
        msg_count = len(message_ids)

        try:
            if channel_obj:
                await event.client(DeleteMessagesRequest(chat.id, message_ids))
            else:
                await event.client(
                    DeleteMessagesRequestGPM(message_ids, revoke=True))
        except Exception as e:
            log.warning(e)
            await event.edit(msgRep.PURGE_MSG_FAILED)
            return

        try:
            result = await event.client.send_message(
                chat.id, msgRep.PURGE_COMPLETE.format(msg_count))
            await sleep(2.5)
            await result.delete()
            if LOGGING:
                await event_log(
                    event,
                    "PURGE",
                    chat_title=chat.title if hasattr(chat, "title") else None,
                    chat_link=chat.username
                    if hasattr(chat, "username") else None,
                    chat_id=chat.id if hasattr(chat, "id") else None,
                    custom_text=msgRep.LOG_PURGE.format(msg_count))
        except Exception as e:
            log.error(e)
    else:
        await event.edit(msgRep.REPLY_PURGE_MSG)

    return
Exemplo n.º 3
0
 def delete_messages_from_peer(self, peer):
     messages_to_delete = list(self.messages_to_delete)
     print_header('УДАЛЕНИЕ {} СВОИХ СООБЩЕНИЙ В ЧАТЕ {}'.format(
         len(messages_to_delete), peer.title))
     for chunk_data in chunks(messages_to_delete, 100):
         # Поскольку удалить больше чем 100 сообщеий мы не можем - разделяем на маленькие кусочки
         r = self(DeleteMessagesRequest(peer, chunk_data))
         if r.pts_count:
             print('Удалено сообщений: {}'.format(r.pts_count))
         sleep(1)
     return True
Exemplo n.º 4
0
 def flush_delete(self, with_update=True):
     while True:
         try:
             print('try processing delete queue...')
             self.client.invoke(
                 DeleteMessagesRequest(get_input_peer(self.channel),
                                       self.del_list))
             break
         except ValueError:
             self.client.disconnect()
             self.client.connect()
         except FloodWaitError as e:
             print('flood error occurred, waiting...')
             sleep(e.seconds + 2)
     self.del_list.clear()
     if with_update: self.update('작동중')
Exemplo n.º 5
0
 def _unsafe_handle_message(self, msg):
   def render_name(user):
     if getattr(user, 'username', None):
       return '@' + user.username
     name = user.first_name
     if getattr(user, 'last_name', None):
       name += ' ' + user.last_name
     return name
     
   print('Tamada:', msg)
   if self._is_admin_message(msg):
     if self._handle_admin_message(msg):
       return
   msg_id = getattr(msg, 'id', None)
   if getattr(msg, 'via_bot_id', None) == SAYTEXTBOT_ID and getattr(self._settings, 'saytextbot', False):
     self._client.invoke(DeleteMessagesRequest(self._peer, [msg_id]))
     return
   text = getattr(msg, 'message', None)
   from_id = getattr(msg, 'from_id', None)
   sender = self._get_full_user(from_id)
   if not sender:
     return
   reply_to_msg_id = getattr(msg, 'reply_to_msg_id', None)
   now = datetime.datetime.now()
   if not text or not from_id or not msg_id:
     return
   if text in ['/possat', '/nassat']:
     if reply_to_msg_id:
       msg = self._get_message(reply_to_msg_id)
       target_id = getattr(msg, 'from_id', None)
       if not target_id:
         return
       target = self._get_full_user(target_id)
       if not target:
         return
       if target_id == from_id:
         self._client.send_message(self._peer, render_name(sender) + ' обоссался!')
       else:
         self._client.send_message(self._peer, render_name(sender) + ' вероломно поссал прямо на ' + render_name(target) + '!')
     else:
       self._client.send_message(self._peer, render_name(sender) + ' поссал прямо при всех! Стыдоба!')
   elif text in ['/ping']:
       self._client.send_message(self._peer, 'Что, ' + render_name(sender) + ', заняться больше нечем?')
Exemplo n.º 6
0
 async def __delete_messages_from_peer(self, entity: hints.Entity) -> None:
     """
     Method deletes messages
     """
     messages_to_delete = list(self.__messages_to_delete)
     print_header(
         f"Delete {len(messages_to_delete)} of my messages in chat {self.__display_name}"
     )
     for chunk_data in chunks(
             messages_to_delete, 100
     ):  # Because we can delete only 100 messages per request (Telegram API restrictions)
         if self.__dialogs:
             result = await self(
                 DeleteMessagesRequestFromUser(chunk_data, revoke=True))
         else:
             result = await self(DeleteMessagesRequest(entity, chunk_data))
         if result.pts_count:
             print(f"Number of deleted messages: {result.pts_count}")
         sleep(1)
     print_header("Erasing is finished.")
Exemplo n.º 7
0
async def stop(chat: Channel, client: Client, db: Database, event: Command, tags: Tags):
    if not event.message.is_reply:
        return
    db_chat = await db.chats.get(event.chat_id)
    start_id = db_chat.raid_start
    reply_msg = await event.message.get_reply_message()
    end_id = reply_msg.id
    await db.chats.stop_raid(event.chat_id)
    raidno = tags.get('raidno', None)

    user_ids = set()
    message_ids = set()
    async for msg in client.iter_messages(chat, min_id=start_id-1, reverse=True):
        if msg.id >= end_id + 1:
            break
        if isinstance(msg.action, MessageActionChatAddUser):
            action: MessageActionChatAddUser = msg.action
            if msg.sender_id in action.users:
                uid = msg.sender_id
                user_ids.add(uid)
                message_ids.add(msg.id)

    await client(DeleteMessagesRequest(chat, list(message_ids)))

    for uid in user_ids:
        try:
            result = await client(GetParticipantRequest(chat, uid))
            if not isinstance(result.participant, ChannelParticipantBanned):
                try:
                    await client.ban(chat, uid)
                except FloodWaitError as e:
                    flood_wait_message: Message = await client.send_message(chat, f'FloodWait for {e.seconds}')
                    await asyncio.sleep(e.seconds)
                    await flood_wait_message.delete()
                    await client.ban(chat, uid)
                    if raidno:
                        await client.gban(uid, f'Raid[{raidno}]')
            await asyncio.sleep(0.5)

        except (UserNotParticipantError, BadRequestError):
            pass
Exemplo n.º 8
0
async def safe_delete_message(bot, delay, *args, **kwarg):
    await asyncio.sleep(delay)
    try:
        await bot(DeleteMessagesRequest(*args, **kwarg))
    except errors.BadRequestError:  # msg to delete not found
        pass