Exemplo n.º 1
0
async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    chat_info = None
    if chat:
        try:
            chat = int(chat)
        except ValueError:
            pass
    if not chat:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id is not None:
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await event.client(GetFullChatRequest(chat))
    except:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await event.edit("`Invalid channel/group`")
            return None
        except ChannelPrivateError:
            await event.edit(
                "`This is a private channel/group or I am banned from there`")
            return None
        except ChannelPublicGroupNaError:
            await event.edit("`Channel or supergroup doesn't exist`")
            return None
        except (TypeError, ValueError) as err:
            await event.edit(str(err))
            return None
    return chat_info
Exemplo n.º 2
0
async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    chat_info = None
    if chat:
        try:
            chat = int(chat)
        except ValueError:
            pass
    if not chat:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id is not None:
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await event.client(GetFullChatRequest(chat))
    except BaseException:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await event.reply("`channel/group tidak valid`")
            return None
        except ChannelPrivateError:
            await event.reply(
                "`Ini adalah channel/group pribadi atau saya dibanned dari sana`"
            )
            return None
        except ChannelPublicGroupNaError:
            await event.reply("`Channel atau supergroup tidak ada`")
            return None
        except (TypeError, ValueError):
            await event.reply("`channel/group tidak valid`")
            return None
    return chat_info
Exemplo n.º 3
0
async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    chat_info = None
    if chat:
        try:
            chat = int(chat)
        except ValueError:
            pass
    if not chat:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id is not None:
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await event.client(GetFullChatRequest(chat))
    except:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await event.reply("`Geçersiz kanal/grup`")
            return None
        except ChannelPrivateError:
            await event.reply("`Burası gizli grup veya Ben burdan ban yedim.`")
            return None
        except ChannelPublicGroupNaError:
            await event.reply("`Böyle bir supergrup veya kanal yok`")
            return None
        except (TypeError, ValueError) as err:
            await event.reply(str(err))
            return None
    return chat_info
Exemplo n.º 4
0
    async def _get_users(
        self, user: '******', entity: Union[TypeInputPeer, InputUser,
                                                  TypeChat, TypeUser,
                                                  InputChannel]
    ) -> List[TypeUser]:
        if self.peer_type == "chat":
            chat = await user.client(GetFullChatRequest(chat_id=self.tgid))
            return list(
                self._filter_participants(
                    chat.users, chat.full_chat.participants.participants))
        elif self.peer_type == "channel":
            if not self.megagroup and not self.sync_channel_members:
                return []

            limit = self.max_initial_member_sync
            if limit == 0:
                return []

            try:
                return await self._get_channel_users(user, entity, limit)
            except ChatAdminRequiredError:
                return []
        elif self.peer_type == "user":
            return [entity]
        else:
            raise RuntimeError(f"Unexpected peer type {self.peer_type}")
Exemplo n.º 5
0
async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    chat_info = None
    if chat:
        try:
            chat = int(chat)
        except ValueError:
            pass
    if not chat:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id is not None:
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await event.client(GetFullChatRequest(chat))
    except BaseException:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await event.edit("`Grup/Channel Tidak Valid`")
            return None
        except ChannelPrivateError:
            await event.edit(
                "`Ini Adalah Grup/Channel Privasi Atau Lord Dibanned Dari Sana`"
            )
            return None
        except ChannelPublicGroupNaError:
            await event.edit("`Channel Atau Supergrup Tidak Ditemukan`")
            return None
        except (TypeError, ValueError) as err:
            await event.edit(str(err))
            return None
    return chat_info
Exemplo n.º 6
0
async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    chat_info = None
    if chat:
        try:
            chat = int(chat)
        except ValueError:
            pass
    if not chat:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id is not None:
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await event.client(GetFullChatRequest(chat))
    except:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await event.reply("`Səhv kanal/qrup`")
            return None
        except ChannelPrivateError:
            await event.reply("`Bura gizli qrup və ya Mən buradan ban aldım.`")
            return None
        except ChannelPublicGroupNaError:
            await event.reply("`Belə bir süper qrup və ya kanal yoxdur`")
            return None
        except (TypeError, ValueError) as err:
            await event.reply(str(err))
            return None
    return chat_info
Exemplo n.º 7
0
 async def get_call(
     self,
     chat_id: int,
 ) -> Optional[InputGroupCall]:
     chat = await self._app.get_input_entity(chat_id)
     if isinstance(chat, InputPeerChannel):
         input_call = (await self._app(
             GetFullChannelRequest(
                 InputChannel(
                     chat.channel_id,
                     chat.access_hash,
                 ), ), )).full_chat.call
     else:
         input_call = (await self._app(
             GetFullChatRequest(chat_id), )).full_chat.call
     if input_call is not None:
         try:
             call: GroupCall = (await self._app(
                 GetGroupCallRequest(
                     call=input_call,
                     limit=-1,
                 ), )).call
             if call.schedule_date is not None:
                 return None
         except Exception as e:
             print(e)
     return input_call
Exemplo n.º 8
0
async def get_chatinfo(event):
    chat = extract_args(event)
    chat_info = None
    if chat.isdigit():
        chat = int(chat)
    else:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id :
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await event.client(GetFullChatRequest(chat))
    except:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await event.edit("`Geçersiz kanal/grup`")
            return None
        except ChannelPrivateError:
            await event.edit("`Bu özel bir kanal/grup veya oradan yasaklandım`")
            return None
        except ChannelPublicGroupNaError:
            await event.edit("`Kanal veya süpergrup mevcut değil`")
            return None
        except (TypeError, ValueError) as err:
            await event.edit(str(err))
            return None
    return chat_info
Exemplo n.º 9
0
async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    chat_info = None
    if chat:
        try:
            chat = int(chat)
        except ValueError:
            pass
    if not chat:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id is not None:
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await event.client(GetFullChatRequest(chat))
    except:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await event.reply("`Saluran / grup tidak valid`")
            return None
        except ChannelPrivateError:
            await event.reply("`Ini adalah grup rahasia atau saya dilarang dari sini.`")
            return None
        except ChannelPublicGroupNaError:
            await event.reply("`Tidak ada supergrup atau saluran seperti itu`")
            return None
        except (TypeError, ValueError) as err:
            await event.reply(str(err))
            return None
    return chat_info
async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    chat_info = None
    if chat:
        try:
            chat = int(chat)
        except ValueError:
            pass
    if not chat:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id is not None:
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await event.client(GetFullChatRequest(chat))
    except:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await event.edit("**❌Errore:** `Gruppo/canale non valido.`")
            return None
        except ChannelPrivateError:
            await event.edit(
                "**❌Errore:** `In questo in gruppo/canale sono bannato (oppure è privato).`"
            )
            return None
        except ChannelPublicGroupNaError:
            await event.edit("**❌Errore:** `Questo gruppo/canale non esiste.`")
            return None
        except (TypeError, ValueError) as err:
            await event.edit(str(err))
            return None
    return chat_info
Exemplo n.º 11
0
async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    chat_info = None
    if chat:
        try:
            chat = int(chat)
        except ValueError:
            pass
    if not chat:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id is not None:
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await event.client(GetFullChatRequest(chat))
    except BaseException:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await event.edit("`Canal/grupo inválido`")
            return None
        except ChannelPrivateError:
            await event.edit(
                "`Este é um canal/grupo privado ou fui banido de lá`")
            return None
        except ChannelPublicGroupNaError:
            await event.edit("`Canal ou supergrupo não existe`")
            return None
        except (TypeError, ValueError) as err:
            await event.edit(str(err))
            return None
    return chat_info
Exemplo n.º 12
0
    async def _get_users(
        self, user: '******', entity: Union[TypeInputPeer, InputUser,
                                                  TypeChat, TypeUser,
                                                  InputChannel]
    ) -> Tuple[List[TypeUser], List[TypeParticipant]]:
        # TODO replace with client.get_participants
        if self.peer_type == "chat":
            chat = await user.client(GetFullChatRequest(chat_id=self.tgid))
            return chat.users, chat.full_chat.participants.participants
        elif self.peer_type == "channel":
            if not self.megagroup and not self.sync_channel_members:
                return [], []

            limit = self.max_initial_member_sync
            if limit == 0:
                return [], []

            try:
                if 0 < limit <= 200:
                    response = await user.client(
                        GetParticipantsRequest(entity,
                                               ChannelParticipantsRecent(),
                                               offset=0,
                                               limit=limit,
                                               hash=0))
                    return response.users, response.participants
                elif limit > 200 or limit == -1:
                    users: List[TypeUser] = []
                    participants: List[TypeParticipant] = []
                    offset = 0
                    remaining_quota = limit if limit > 0 else 1000000
                    query = (ChannelParticipantsSearch("")
                             if limit == -1 else ChannelParticipantsRecent())
                    while True:
                        if remaining_quota <= 0:
                            break
                        response = await user.client(
                            GetParticipantsRequest(entity,
                                                   query,
                                                   offset=offset,
                                                   limit=min(
                                                       remaining_quota, 100),
                                                   hash=0))
                        if not response.users:
                            break
                        participants += response.participants
                        users += response.users
                        offset += len(response.participants)
                        remaining_quota -= len(response.participants)
                    return users, participants
            except ChatAdminRequiredError:
                return [], []
        elif self.peer_type == "user":
            return [entity], []
        return [], []
Exemplo n.º 13
0
async def _(e):
    reply = await e.get_reply_message()
    match = e.pattern_match.group(1).strip()
    if reply and not isinstance(reply.sender, User):
        chat = await reply.get_sender()
    else:
        chat = await e.get_chat()
    if hasattr(chat, "username") and chat.username:
        return await e.eor(f"Username: @{chat.username}")
    request, usage, title = None, None, None
    if match:
        split = match.split(maxsplit=1)
        request = bool(split[0] in ["r", "request"])
        title = "Created by Ultroid"
        if len(split) > 1:
            match = split[1]
            spli = match.split(maxsplit=1)
            if spli[0].isdigit():
                usage = int(spli[0])
            if len(spli) > 1:
                title = spli[1]
        elif not request:
            if match.isdigit():
                usage = int(match)
            else:
                title = match
        if request and usage:
            usage = 0
    if request or title:
        try:
            r = await e.client(
                ExportChatInviteRequest(
                    e.chat_id,
                    request_needed=request,
                    usage_limit=usage,
                    title=title,
                ), )
        except no_admin:
            return await e.eor(get_string("chats_2"), time=10)
        link = r.link
    else:
        if isinstance(chat, types.Chat):
            FC = await e.client(GetFullChatRequest(chat.id))
        elif isinstance(chat, types.Channel):
            FC = await e.client(GetFullChannelRequest(chat.id))
        else:
            return
        Inv = FC.full_chat.exported_invite
        if Inv and not Inv.revoked:
            link = Inv.link
    if link:
        return await e.eor(f"Link:- {link}")
    await e.eor(
        "`Failed to getlink!\nSeems like link is inaccessible to you...`")
Exemplo n.º 14
0
async def djshsh(event):
    chat = await event.get_chat()
    if isinstance(chat, types.Chat):
        FChat = await event.client(GetFullChatRequest(chat.id))
    elif isinstance(chat, types.Channel):
        FChat = await event.client(GetFullChannelRequest(chat.id))
    else:
        return
    msg_id = FChat.full_chat.pinned_msg_id
    if not msg_id:
        return await event.eor(get_string("pinned_1"))
    msg = await event.client.get_messages(chat.id, ids=msg_id)
    if msg:
        await event.eor(get_string("pinned_2").format(msg.message_link))
Exemplo n.º 15
0
 async def get_call(
     self,
     chat_id: int,
 ) -> Optional[InputGroupCall]:
     chat = await self._app.get_input_entity(chat_id)
     if isinstance(chat, InputPeerChannel):
         return (await self._app(
             GetFullChannelRequest(
                 InputChannel(
                     chat.channel_id,
                     chat.access_hash,
                 ), ), )).full_chat.call
     else:
         return (await
                 self._app(GetFullChatRequest(chat_id), )).full_chat.call
Exemplo n.º 16
0
async def djshsh(event):
    chat = await event.get_chat()
    if isinstance(chat, types.Chat):
        FChat = await event.client(GetFullChatRequest(chat.id))
    elif isinstance(chat, types.Channel):
        FChat = await event.client(GetFullChannelRequest(chat.id))
    else:
        return
    msg_id = FChat.full_chat.pinned_msg_id
    if not msg_id:
        return await eor(event, "No Pinned Message Found!")
    msg = await event.client.get_messages(chat.id, ids=msg_id)
    await eor(
        event,
        f"Pinned Message in Current chat is [here]({msg.message_link}).")
Exemplo n.º 17
0
async def whois(event):
    match = event.matches[0].group(1)
    reply_id = None

    if event.entities or match:
        user = await get_user_from_msg(event)
        if not user:
            await event.edit("`Couldn't get user/chat from the message.`")
            return
    else:
        user = "******"

    if event.reply_to_msg_id:
        reply_id = event.reply_to_msg_id
        if not match:
            reply = await event.get_reply_message()
            if reply.fwd_from:
                if reply.fwd_from.from_id:
                    user = reply.fwd_from.from_id
                else:
                    user = reply.sender_id

    try:
        input_entity = await client.get_input_entity(user)
    except Exception as e:
        await event.reply('`' + type(e).__name__ + ': ' + str(e) + '`')
        return

    try:
        if isinstance(input_entity, InputPeerChat):
            full_chat = await client(GetFullChatRequest(chat_id=input_entity))
            string = await Parser.parse_full_chat(full_chat, event)
        elif isinstance(input_entity, InputPeerChannel):
            full_channel = await client(
                GetFullChannelRequest(channel=input_entity))
            string = await Parser.parse_full_chat(full_channel, event)
        else:
            full_user = await client(GetFullUserRequest(id=input_entity))
            string = await Parser.parse_full_user(full_user, event)
    except Exception as e:
        await event.reply('`' + type(e).__name__ + ': ' + str(e) + '`')
        return

    if reply_id:
        await event.delete()
    await event.respond(string, reply_to=reply_id)
Exemplo n.º 18
0
async def get_chat_from_event(event: NewMessage.Event, **kwargs):
    chat = kwargs.get('chat', None)

    if chat:
        try:
            input_entity = await event.client.get_input_entity(chat)
            if isinstance(input_entity, InputPeerChannel):
                return await event.client(GetFullChannelRequest(input_entity.channel_id))
            elif isinstance(input_entity, InputPeerChat):
                return await event.client(GetFullChatRequest(input_entity.chat_id))
            else:
                return None
        except(TypeError, ValueError):
            return None
    else:
        chat = await event.get_chat()
        return await event.client(GetFullChannelRequest(chat.id))
Exemplo n.º 19
0
async def _(e):
    chat = await e.get_chat()
    if chat.username:
        return await eor(e, f"Username: @{chat.username}")
    if isinstance(chat, types.Chat):
        FC = await e.client(GetFullChatRequest(chat.id))
    elif isinstance(chat, types.Channel):
        FC = await e.client(GetFullChannelRequest(chat.id))
    Inv = FC.full_chat.exported_invite
    if Inv and not Inv.revoked:
        link = Inv.link
    else:
        try:
            r = await e.client(ExportChatInviteRequest(e.chat_id), )
        except no_admin:
            return await eor(e, get_string("chats_2"), time=10)
        link = r.link
    await eor(e, f"Link:- {link}")
async def test_update_info_group_user(helper, client, bot_group, channel,
                                      slave, bot_id, chat_type, alias, avatar):
    chat = slave.get_chat_by_criteria(chat_type=chat_type,
                                      alias=alias,
                                      avatar=avatar)

    # Set bot as admin if needed
    if await is_bot_admin(client, bot_id, bot_group):
        await client.edit_admin(bot_group,
                                bot_id,
                                change_info=True,
                                is_admin=True,
                                delete_messages=False)

    with link_chats(channel, (chat, ), bot_group):
        await client.send_message(bot_group, "/update_info")
        title = (await helper.wait_for_event(in_chats(bot_group)
                                             & new_title)).new_title
        if alias:
            assert chat.alias in title
        else:
            assert chat.name in title

        if avatar:
            await helper.wait_for_event(in_chats(bot_group) & new_photo)

        if chat_type == "GroupChat":
            # Get group description
            bot_group_t, peer_type = resolve_id(bot_group)
            if peer_type == PeerChannel:
                group: ChatFull = await client(
                    GetFullChannelRequest(bot_group_t))
            else:
                group: ChatFull = await client(GetFullChatRequest(bot_group_t))
            desc = group.full_chat.about

            chats_found = sum(
                int((i.name in desc) and  # Original name is found, and
                    (i.alias is None or i.alias in desc
                     )  # alias is found too if available
                    ) for i in chat.members)

            assert len(chat.members) >= 5
            assert chats_found >= 5, f"At least 5 members shall be found in the description: {desc}"
Exemplo n.º 21
0
    async def _can_use_commands(self, chat, tgid):
        if tgid in self.tg_whitelist:
            return True

        user = u.User.get_by_tgid(tgid)
        if user and user.is_admin:
            self.tg_whitelist.append(user.tgid)
            return True

        if self.whitelist_group_admins:
            if isinstance(chat, PeerChannel):
                p = await self.client(GetParticipantRequest(chat, tgid))
                return isinstance(p, (ChannelParticipantCreator, ChannelParticipantAdmin))
            elif isinstance(chat, PeerChat):
                chat = await self.client(GetFullChatRequest(chat.chat_id))
                participants = chat.full_chat.participants.participants
                for p in participants:
                    if p.user_id == tgid:
                        return isinstance(p, (ChatParticipantCreator, ChatParticipantAdmin))
Exemplo n.º 22
0
async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    if event.reply_to_msg_id and not chat:
        replied_msg = await event.get_reply_message()
        if replied_msg.from_id and isinstance(replied_msg.from_id,
                                              PeerChannel):
            chat = replied_msg.from_id.channel_id
        elif (replied_msg.fwd_from and replied_msg.fwd_from.from_id
              and isinstance(replied_msg.fwd_from.from_id, PeerChannel)):
            chat = replied_msg.fwd_from.from_id.channel_id
        else:
            await event.edit(msgRep.REPLY_NOT_CHANNEL)
            return None
    else:
        try:
            chat = int(chat)
        except ValueError:
            pass

    if not chat:
        chat = event.chat_id

    try:
        if not isinstance(chat, int):
            # if input is not an ID, skip GetFullChatRequest as it
            # accepts only integers
            raise Exception("'chat' is not an integer")
        chat_info = await event.client(GetFullChatRequest(chat))
        return chat_info
    except Exception:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
            return chat_info
        except ChannelInvalidError:
            await event.edit(msgRep.INVALID_CH_GRP)
        except ChannelPrivateError:
            await event.edit(msgRep.PRV_BAN)
        except ChannelPublicGroupNaError:
            await event.edit(msgRep.NOT_EXISTS)
        except Exception as e:
            log.warning(e)
            await event.edit(msgRep.CANNOT_GET_CHATINFO.format(chat))
    return None
Exemplo n.º 23
0
async def on_new_mssg(event):
    who = event.sender_id
    # doesn't reply to that user anymore
    if event.text.startswith("/") or who == OWNER_ID:
        return
    if FSUB:
        MSG = ""
        BTTS = []
        for chat in FSUB:
            try:
                await event.client.get_permissions(chat, event.sender_id)
            except UserNotParticipantError:
                if not MSG:
                    MSG += get_string("pmbot_1")
                try:
                    TAHC_ = await event.client.get_entity(chat)
                    if hasattr(TAHC_, "username") and TAHC_.username:
                        uri = "t.me/" + TAHC_.username
                    elif CACHE.get(chat):
                        uri = CACHE[chat]
                    else:
                        if isinstance(TAHC_, Channel):
                            FUGB = await event.client(
                                GetFullChannelRequest(chat))
                        elif isinstance(TAHC_, Chat):
                            FUGB = await event.client(GetFullChatRequest(chat))
                        else:
                            return
                        if FUGB.full_chat.exported_invite:
                            CACHE[chat] = FUGB.full_chat.exported_invite.link
                            uri = CACHE[chat]
                    BTTS.append(Button.url(get_display_name(TAHC_), uri))
                except Exception as er:
                    LOGS.exception(
                        f"Error On PmBot Force Sub!\n - {chat} \n{er}")
        if MSG and BTTS:
            return await event.reply(MSG, buttons=BTTS)
    xx = await event.forward_to(OWNER_ID)
    if event.fwd_from:
        await xx.reply(
            f"From {inline_mention(event.sender)} [`{event.sender_id}`]")
    add_stuff(xx.id, who)
Exemplo n.º 24
0
async def sync_full(evt: CommandEvent) -> EventID:
    portal = po.Portal.get_by_mxid(evt.room_id)
    if not portal:
        return await evt.reply("This is not a portal room.")

    if len(evt.args) > 0 and evt.args[0] == "--usebot" and evt.sender.is_admin:
        src = evt.tgbot
    else:
        src = evt.tgbot if await evt.sender.needs_relaybot(portal) else evt.sender

    try:
        if portal.peer_type == "channel":
            res = await src.client(GetFullChannelRequest(portal.peer))
        elif portal.peer_type == "chat":
            res = await src.client(GetFullChatRequest(portal.tgid))
        else:
            return await evt.reply("This is not a channel or chat portal.")
    except (ValueError, RPCError):
        return await evt.reply("Failed to get portal info from Telegram.")

    await portal.update_matrix_room(src, res.full_chat)
    return await evt.reply("Portal synced successfully.")
Exemplo n.º 25
0
async def _(e):
    reply = await e.get_reply_message()
    if reply and not isinstance(reply.sender, User):
        chat = await reply.get_sender()
    else:
        chat = await e.get_chat()
    if hasattr(chat, "username") and chat.username:
        return await e.eor(f"Username: @{chat.username}")
    if isinstance(chat, types.Chat):
        FC = await e.client(GetFullChatRequest(chat.id))
    elif isinstance(chat, types.Channel):
        FC = await e.client(GetFullChannelRequest(chat.id))
    Inv = FC.full_chat.exported_invite
    if Inv and not Inv.revoked:
        link = Inv.link
    else:
        try:
            r = await e.client(ExportChatInviteRequest(e.chat_id), )
        except no_admin:
            return await e.eor(get_string("chats_2"), time=10)
        link = r.link
    await e.eor(f"Link:- {link}")
Exemplo n.º 26
0
async def get_users(
    client: MautrixTelegramClient,
    tgid: int,
    entity: TypeInputPeer | InputUser | TypeChat | TypeUser | InputChannel,
    limit: int,
    peer_type: str,
) -> list[TypeUser]:
    if peer_type == "chat":
        chat = await client(GetFullChatRequest(chat_id=tgid))
        users = list(
            _filter_participants(chat.users,
                                 chat.full_chat.participants.participants))
        return users[:limit] if limit > 0 else users
    elif peer_type == "channel":
        try:
            return await _get_channel_users(client, entity, limit)
        except ChatAdminRequiredError:
            return []
    elif peer_type == "user":
        return [entity]
    else:
        raise RuntimeError(f"Unexpected peer type {peer_type}")
Exemplo n.º 27
0
async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    chat_info = None
    if chat:
        try:
            chat = int(chat)
        except ValueError:
            pass
    if not chat:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id is not None:
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await king_bot(GetFullChatRequest(chat))
    except BaseException:
        try:
            chat_info = await king_bot(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await eor(event, "`Grup atau channel invalid.`")
            return None
        except ChannelPrivateError:
            await eor(
                event,
                "`Ini adalah grup/channel privat atau mungkin saya di ban disana.`"
            )
            return None
        except ChannelPublicGroupNaError:
            await eor(event, "`Channel atau supergroup tidak ditemukan.`")
            return None
        except (TypeError, ValueError) as err:
            await eor(event, str(err))
            return None
    return chat_info
Exemplo n.º 28
0
    def xmpp_update_handler(self, obj):
        print('new update for ' + self.jid)
        print(type(obj), obj.__dict__)
        '''
        Боты
        Сделать запоминание ростера в бд
        Сделать лучше хендлинг ошибок
        Доделать все типы информационных сообщений
        Сделать джойны по линкам в чаты/каналы
        Сделать поиск и добавление пользователей
        Сделать листание истории
        Сделать отправку всех непрочтенных сообщений при входе
        '''

        # Здесь будет очень длинный пиздец ^__^

        nl = '\n' if self.user_options['nl_after_info'] else ''

        try:
            if type(
                    obj
            ) is Updates:  # Какой-то общий тип обновления (всегда большое со списками)
                print('Updates')

                # Делаем разбор пользователей/чатов, которые учавствуют в апдейте
                updates_users = {usr.id: usr for usr in obj.users}
                updates_groups = {}
                updates_channels = {}
                updates_supergroups = {}
                updates_type_channels = {}  # Супегруппы и каналы вместе

                for chat in obj.chats:
                    if type(chat) is Chat:  # Обычная группа
                        updates_groups[chat.id] = chat
                    elif type(chat) is Channel:
                        if chat.broadcast:  # Канал
                            updates_channels[chat.id] = chat
                        else:  # Супегруппа
                            updates_supergroups[chat.id] = chat
                        updates_type_channels[chat.id] = chat

                # -------------------------------------------------------------------------------------------

                for update in obj.updates:  # Апдейт содержит список с апдейтами
                    # Новое сообщение или отредактированное в супегруппе или канале
                    # А так же отредактированные и новые сообщения с медиа в ЛС и группах
                    if type(update) in [
                            UpdateNewChannelMessage, UpdateEditChannelMessage,
                            UpdateNewMessage, UpdateEditMessage
                    ]:
                        if update.message.out:  # Игнорируем исходящее сообщение
                            return

                        uid = update.message.from_id  # Будет None, если канал, а так же post=True
                        mid = update.message.id
                        cid = None
                        is_post = update.message.post
                        usr = updates_users[uid] if uid else None
                        nickname = display_tg_name(
                            usr.first_name, usr.last_name) if usr else None

                        from_type = 'c' if is_post else 's'
                        msg = ''
                        alt_msg = None
                        edited = ''
                        fwd_reply = ''
                        orig_msg = None

                        is_user = type(update.message.to_id) is PeerUser
                        is_group = type(update.message.to_id) is PeerChat
                        is_supergroup = type(
                            update.message.to_id) is PeerChannel

                        if is_user:
                            cid = update.message.from_id
                        elif is_group:
                            cid = update.message.to_id.chat_id
                        elif is_supergroup:
                            cid = update.message.to_id.channel_id

                        if type(
                                update.message
                        ) is MessageService:  # Сервисные уведомления в чате
                            print('messageService detected')
                            with open(
                                    '/home/sofia/tgdebug/' + str(mid) + '.txt',
                                    'w') as f:
                                f.write(var_dump(obj))
                            ##################################################################
                            alt_msg = self._process_info_msg(
                                update.message, obj.users)
                        else:  # Обычное сообщение в чате
                            msg = update.message.message

                            if update.message.media:
                                print('media detected')
                                #######################################################
                                msg = '[{}] {}'.format(
                                    update.message.media.__class__.__name__,
                                    '{} {}'.format(
                                        self._process_media_msg(
                                            update.message.media), msg))

                            if update.message.reply_to_msg_id:
                                fwd_reply = '|Reply to MID: {}'.format(
                                    update.message.reply_to_msg_id)
                                reply_mid = update.message.reply_to_msg_id
                                orig_msg = self.get_cached_message(
                                    cid, reply_mid, is_user, is_group,
                                    is_supergroup)

                            if update.message.fwd_from:  # Пересланное сообщение
                                fwd_reply = self._process_forward_msg(
                                    update.message, updates_users,
                                    updates_channels)

                        if update.message.edit_date:  # Если новое - отмечаем прочитанным
                            edited = '|Edited'

                        if alt_msg is None:
                            if is_post or type(
                                    update.message.to_id) is PeerUser:
                                header = '[MID:{}{}{}] '.format(
                                    mid, fwd_reply, edited)
                            else:
                                header = '[User: {}|UID:{}|MID:{}{}{}] {}'\
                                    .format(nickname, uid, mid, fwd_reply, edited, nl)

                            alt_msg = '{}{}'.format(header, msg)

                            self.set_cached_message(  # Кэшируем без цитаты
                                cid,
                                mid,
                                alt_msg,
                                user=is_user,
                                group=is_group,
                                supergroup=is_supergroup)

                            if orig_msg is not None:  # Перестраиваем сообщение уже с цитатой
                                alt_msg = '{}> {}\n{}'.format(
                                    header, orig_msg.replace('\n', '\n> '),
                                    msg)

                        if is_user:
                            self.gate_send_message(mfrom='u' + str(cid),
                                                   mbody=alt_msg)

                            if False:  # Зарезервируем рекурсивные цитаты под опцию
                                self.set_cached_message(cid,
                                                        mid,
                                                        alt_msg,
                                                        user=True)

                            if not update.message.edit_date:
                                self.invoke(
                                    ReadHistoryRequest(  # Отмечаем прочитанным
                                        InputPeerUser(usr.id, usr.access_hash),
                                        mid))
                        elif is_group:
                            self.gate_send_message(
                                mfrom='g' + str(update.message.to_id.chat_id),
                                mbody=alt_msg)

                            if False:  # ...
                                self.set_cached_message(cid,
                                                        mid,
                                                        alt_msg,
                                                        group=True)

                            if not update.message.edit_date:
                                self.invoke(
                                    ReadHistoryRequest(InputPeerChat(cid),
                                                       mid))
                        elif is_supergroup:
                            self.gate_send_message(mfrom=from_type + str(cid),
                                                   mbody=alt_msg)

                            if False:  # ...
                                self.set_cached_message(cid,
                                                        mid,
                                                        alt_msg,
                                                        supergroup=True)

                            if not update.message.edit_date:
                                access_hash = updates_type_channels[
                                    cid].access_hash
                                self.invoke(
                                    ReadHistoryChannel(
                                        InputPeerChannel(cid, access_hash),
                                        mid))
                    elif type(
                            update
                    ) is UpdateDeleteChannelMessages:  # Удаленные сообщения в супергруппе/канале
                        channel_id = update.channel_id
                        channel_type = 's'

                        if self.xmpp_gate.tg_dialogs[self.jid]['supergroups'][
                                channel_id].broadcast:  # А может канал?
                            channel_type = 'c'

                        self.gate_send_message(
                            mfrom=channel_type + str(channel_id),
                            mbody='[Deleted messages IDs: {}]'.format(
                                ', '.join(
                                    [str(mid) for mid in update.messages])))
                    elif type(update) is UpdateDeleteMessages:
                        # Этот ивент обновления присылается при удалении сообщения в личном сообщении или группе.
                        # Только id сообщения. Нет информации об диалоге/пользователе/группе.
                        pass

                if type(obj.updates) is list and type(
                        obj.updates[0]) is UpdateChannelTooLong:
                    print('too long')

            # ***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***

            if type(
                    obj
            ) is UpdateShort:  # Тоже какой-то общий тип обновления (всегда маленькое)
                if type(
                        obj.update
                ) is UpdateUserStatus:  # Обновление статуса пользователя в сети Tg
                    print('UpdateUserStatus')

                    if type(obj.update.status) is UserStatusOnline:
                        self.xmpp_gate.send_presence(
                            pto=self.jid,
                            pfrom='u' + str(obj.update.user_id) + '@' +
                            self.xmpp_gate.config['jid'])
                    elif type(obj.update.status) is UserStatusOffline:
                        self.xmpp_gate.send_presence(
                            pto=self.jid,
                            pfrom='u' + str(obj.update.user_id) + '@' +
                            self.xmpp_gate.config['jid'],
                            ptype='xa',
                            pstatus=obj.update.status.was_online.strftime(
                                'Last seen at %H:%M %d/%m/%Y'))
                    elif type(obj.update.status) is UserStatusRecently:
                        self.xmpp_gate.send_presence(
                            pto=self.jid,
                            pfrom='u' + str(obj.update.user_id) + '@' +
                            self.xmpp_gate.config['jid'],
                            pstatus='Last seen recently')
                    else:
                        print(type(obj.update.status))
                        print(obj.update.status.__dict__)

                elif type(
                        obj.update
                ) is UpdateDeleteChannelMessages:  # Удаленное сообщение в супергруппе
                    if obj.update.pts > self._del_pts:  # Фильтруем дубли обновлений
                        channel_id = obj.update.channel_id
                        channel_type = 's'

                        if self.xmpp_gate.tg_dialogs[
                                self.jid]['supergroups'][channel_id].broadcast:
                            channel_type = 'c'

                        msg = '[Deleted messages IDs: {}]'.format(', '.join(
                            [str(mid) for mid in obj.update.messages]))

                        self.gate_send_message(mfrom=channel_type +
                                               str(channel_id),
                                               mbody=msg)

                    self._del_pts = obj.update.pts

            # ***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***

            # Входящее сообщение в ЛС или группу (без медиа вложений)
            if type(obj) in [UpdateShortMessage, UpdateShortChatMessage
                             ] and not obj.out:
                fwd_reply = ''
                nickname = ''

                if type(obj) is UpdateShortChatMessage:
                    # Так как в апдейте есть только ID пользователя, то запрашиваем с сервера информацию о группе
                    if obj.from_id not in self._groups_users:
                        chat_info = self.invoke(GetFullChatRequest(
                            obj.chat_id))

                        for usr in chat_info.users:
                            self._groups_users[usr.id] = usr

                    nickname = display_tg_name(
                        self._groups_users[obj.from_id].first_name,
                        self._groups_users[obj.from_id].last_name)

                if obj.reply_to_msg_id:
                    fwd_reply = '|Reply to MID: {}'.format(obj.reply_to_msg_id)

                if obj.fwd_from:
                    full_update = self.invoke(
                        GetDifferenceRequest(obj.pts - 1, obj.date, -1, 1))

                    fwd_reply = self._process_forward_msg(
                        full_update.new_messages[0],
                        {usr.id: usr
                         for usr in full_update.users}, {})

                if type(obj) is UpdateShortMessage:
                    self.gate_send_message(mfrom='u' + str(obj.user_id),
                                           mbody='[MID:{}{}] {}'.format(
                                               obj.id, fwd_reply, obj.message))

                    if obj.user_id in self.xmpp_gate.tg_dialogs[
                            self.jid]['users']:
                        usr = self.xmpp_gate.tg_dialogs[self.jid]['users'][
                            obj.user_id]
                        self.invoke(
                            ReadHistoryRequest(  # Отмечаем прочитанным
                                InputPeerUser(usr.id, usr.access_hash),
                                obj.id))
                elif type(obj) is UpdateShortChatMessage:
                    self.gate_send_message(
                        mfrom='g' + str(obj.chat_id),
                        mbody='[User: {}|UID:{}|MID:{}{}] {}'.format(
                            nickname, obj.from_id, obj.id, fwd_reply,
                            obj.message))

                    self.invoke(
                        ReadHistoryRequest(InputPeerChat(obj.chat_id), obj.id))

        except Exception:
            print('Exception occurs!')
            print(traceback.format_exc())

        print(' ')
Exemplo n.º 29
0
    async def _check(self, message, func):
        self._reload_rights()
        config = self.get_flags(func)

        if not config:  # Either False or 0, either way we can failfast
            return False

        logger.debug("Checking security match for %d", config)

        f_owner = config & OWNER
        f_sudo = config & SUDO
        f_support = config & SUPPORT
        f_group_owner = config & GROUP_OWNER
        f_group_admin_add_admins = config & GROUP_ADMIN_ADD_ADMINS
        f_group_admin_change_info = config & GROUP_ADMIN_CHANGE_INFO
        f_group_admin_ban_users = config & GROUP_ADMIN_BAN_USERS
        f_group_admin_delete_messages = config & GROUP_ADMIN_DELETE_MESSAGES
        f_group_admin_pin_messages = config & GROUP_ADMIN_PIN_MESSAGES
        f_group_admin_invite_users = config & GROUP_ADMIN_INVITE_USERS
        f_group_admin = config & GROUP_ADMIN
        f_group_member = config & GROUP_MEMBER
        f_pm = config & PM

        f_group_admin_any = (
            f_group_admin_add_admins
            or f_group_admin_change_info
            or f_group_admin_ban_users
            or f_group_admin_delete_messages
            or f_group_admin_pin_messages
            or f_group_admin_invite_users
            or f_group_admin
        )

        if f_owner and message.sender_id in self._owner + [self._me]:
            return True

        if f_sudo and message.sender_id in self._sudo:
            return True

        if f_support and message.sender_id in self._support:
            return True

        if message.sender_id in self._db.get(main.__name__, "blacklist_users", []):
            return False

        if f_pm and message.is_private:
            return True

        if f_group_member and message.is_group:
            return True

        if message.is_channel:
            if not message.is_group:
                if message.edit_date:
                    return False

                chat = await message.get_chat()

                if not chat.creator and not (
                    chat.admin_rights and chat.admin_rights.post_messages
                ):
                    return False

                if self._any_admin and f_group_admin_any:
                    return True

                if f_group_admin:
                    return True
            else:
                if f_group_admin_any or f_group_owner:
                    participant = await message.client(
                        GetParticipantRequest(
                            await message.get_input_chat(),
                            await message.get_input_sender(),
                        )
                    )
                    participant = participant.participant

                    if isinstance(
                        participant, telethon.types.ChannelParticipantCreator
                    ):
                        return True

                    if isinstance(participant, telethon.types.ChannelParticipantAdmin):
                        if self._any_admin and f_group_admin_any:
                            return True
                        rights = participant.admin_rights

                        if (
                            f_group_admin
                            or f_group_admin_add_admins
                            and rights.add_admins
                            or f_group_admin_change_info
                            and rights.change_info
                            or f_group_admin_ban_users
                            and rights.ban_users
                            or f_group_admin_delete_messages
                            and rights.delete_messages
                            or f_group_admin_pin_messages
                            and rights.pin_messages
                            or f_group_admin_invite_users
                            and rights.invite_users
                        ):
                            return True

                chat = await message.get_chat()

            if message.out:
                if chat.creator and f_group_owner:
                    return True
                me_id = (await message.client.get_me(True)).user_id

                if (
                    f_owner
                    and me_id in self._owner
                    or f_sudo
                    and me_id in self._sudo
                    or f_support
                    and me_id in self._support
                ):
                    return True

        elif message.is_group:
            if f_group_admin_any or f_group_owner:
                full_chat = await message.client(GetFullChatRequest(message.chat_id))
                participants = full_chat.full_chat.participants.participants
                participant = next(
                    (
                        possible_participant
                        for possible_participant in participants
                        if possible_participant.user_id == message.sender_id
                    ),
                    None,
                )

                if not participant:
                    return

                if isinstance(participant, telethon.types.ChatParticipantCreator):
                    return True

            if (
                isinstance(participant, telethon.types.ChatParticipantAdmin)
                and f_group_admin_any
            ):
                return True

        return False