async def get_chat_administrators( token: str = TOKEN_VALIDATION, chat_id: Union[int, str] = Query(..., description='Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)'), ) -> JSONableResponse: """ Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. https://core.telegram.org/bots/api#getchatadministrators """ from ....main import _get_bot bot = await _get_bot(token) try: entity = await get_entity(bot, chat_id) except BotMethodInvalidError: assert isinstance(chat_id, int) or (isinstance(chat_id, str) and len(chat_id) > 0 and chat_id[0] == '@') entity = chat_id except ValueError: raise HTTPException(404, detail="chat not found?") # end try # https://t.me/TelethonChat/248256 result = await bot.iter_participants( entity=entity, filter=ChannelParticipantsAdmins() ) data = await to_web_api(result, bot) return r_success(data.to_array())
async def polizei(event: NewMessage.Event) -> None: """Checks every message against the autobahn blacklists and bans a user if necessary If the message comes from an admin or a bot it is ignored. The user will be banned with a reason that contains the blacklist and the index of the blacklisted item. The message is automatically submitted to the SpamWatch API if applicable. Tags: polizei: exclude: Messages won't be checked """ if event.is_private: return client: Client = event.client try: chat: Channel = await event.get_chat() except ChannelPrivateError: return tags = await Tags.from_event(event) bancmd = tags.get('gbancmd', 'manual') polizei_tag = tags.get('polizei') if polizei_tag == 'exclude': return ban_type, ban_reason = await _check_message(event) if ban_type and ban_reason: uid = event.message.from_id admins = [p.id for p in await client.get_participants(event.chat_id, filter=ChannelParticipantsAdmins())] if uid not in admins: await _banuser(event, chat, uid, bancmd, ban_type, ban_reason)
async def is_bot_admin(client: TelegramClient, bot_id: int, group): async for admin in client.iter_participants( group, filter=ChannelParticipantsAdmins()): if admin.id == bot_id: return True return False
async def update_admin_cache(chat_id): admin_list = await bot.get_participants( int(chat_id), filter=ChannelParticipantsAdmins()) admins = [] for admin in admin_list: admins.append(admin.id) dump = ujson.dumps(admins) redis.set('admins_cache_{}'.format(chat_id), dump) redis.expire('admins_cache_{}'.format(chat_id), 3600)
async def _check_message(event): client: KantekClient = event.client msg: Message = event.message # exclude users below a certain id to avoid banning "legit" users if msg.from_id < 610000000: return False, False admins = [ p.id for p in (await client.get_participants( event.chat_id, filter=ChannelParticipantsAdmins())) ] if msg.from_id in admins: return False, False # commands used in bots to blacklist items, these will be used by admins # so they shouldnt be banned for it blacklisting_commands = [ '/addblacklist', ] for cmd in blacklisting_commands: if msg.text and msg.text.startswith(cmd): return False, False db: ArangoDB = client.db string_blacklist = db.ab_string_blacklist.get_all() channel_blacklist = db.ab_channel_blacklist.get_all() domain_blacklist = db.ab_domain_blacklist.get_all() entities = [e[1] for e in msg.get_entities_text()] for e in entities: link_creator, chat_id, random_part = await helpers.resolve_invite_link( e) if chat_id in channel_blacklist.keys(): return db.ab_channel_blacklist.hex_type, channel_blacklist[chat_id] for string in string_blacklist: if string in msg.raw_text: return db.ab_string_blacklist.hex_type, string_blacklist[string] if msg.entities: for entity in msg.entities: if isinstance(entity, MessageEntityTextUrl): domain = await helpers.resolve_url(entity.url) if domain in domain_blacklist: return db.ab_domain_blacklist.hex_type, domain_blacklist[ domain] return False, False
async def fetch_info(chat, event): # chat.chats is a list so we use get_entity() to avoid IndexError chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False chat_type = "Channel" if broadcast else "Group" chat_title = chat_obj_info.title warn_emoji = emojize(":warning:") try: msg_info = await event.client( GetHistoryRequest(peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0)) except Exception as e: msg_info = None print("Exception:", e) # No chance for IndexError as it checks for msg_info.messages first first_msg_valid = True if msg_info and msg_info.messages and msg_info.messages[ 0].id == 1 else False # Same for msg_info.users creator_valid = True if first_msg_valid and msg_info.users else False creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = msg_info.users[ 0].first_name if creator_valid and msg_info.users[ 0].first_name is not None else "Deleted Account" creator_username = msg_info.users[ 0].username if creator_valid and msg_info.users[ 0].username is not None else None created = msg_info.messages[0].date if first_msg_valid else None former_title = msg_info.messages[ 0].action.title if first_msg_valid and type( msg_info.messages[0].action ) is MessageActionChannelMigrateFrom and msg_info.messages[ 0].action.title != chat_title else None try: dc_id, location = get_input_location(chat.full_chat.chat_photo) except Exception as e: dc_id = "Unknown" location = str(e) #this is some spaghetti I need to change description = chat.full_chat.about members = chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count admins = chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None banned_users = chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None restrcited_users = chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None members_online = chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0 group_stickers = chat.full_chat.stickerset.title if hasattr( chat.full_chat, "stickerset") and chat.full_chat.stickerset else None messages_viewable = msg_info.count if msg_info else None messages_sent = chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None messages_sent_alt = chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = "<b>Evet</b>" if hasattr( chat_obj_info, "megagroup") and chat_obj_info.megagroup else "No" slowmode = "<b>Evet</b>" if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else "No" slowmode_time = chat.full_chat.slowmode_seconds if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None restricted = "<b>Evet</b>" if hasattr( chat_obj_info, "restricted") and chat_obj_info.restricted else "No" verified = "<b>Evet</b>" if hasattr( chat_obj_info, "verified") and chat_obj_info.verified else "No" username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None #end of spaghetti block if admins is None: # use this alternative way if chat.full_chat.admins_count is None, works even without being an admin try: participants_admins = await event.client( GetParticipantsRequest(channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0)) admins = participants_admins.count if participants_admins else None except Exception as e: print("Exception:", e) if bots_list: for bot in bots_list: bots += 1 caption = "<b>Grup Bilgileri:</b>\n" caption += f"ID: <code>{chat_obj_info.id}</code>\n" if chat_title is not None: caption += f"{chat_type} ismi: {chat_title}\n" if former_title is not None: # Meant is the very first title caption += f"Eski ad: {former_title}\n" if username is not None: caption += f"{chat_type} türü: Açık\n" caption += f"Link: {username}\n" else: caption += f"{chat_type} Türü: Gizli\n" if creator_username is not None: caption += f"Kurucu: {creator_username}\n" elif creator_valid: caption += f"Kurucu: <a href=\"tg://user?id={creator_id}\">{creator_firstname}</a>\n" if created is not None: caption += f"Oluşturulma zamanı: <code>{created.date().strftime('%b %d, %Y')} - {created.time()}</code>\n" else: caption += f"Oluşturulma zamanı: <code>{chat_obj_info.date.date().strftime('%b %d, %Y')} - {chat_obj_info.date.time()}</code> {warn_emoji}\n" caption += f"Veri Merkezi ID: {dc_id}\n" if exp_count is not None: chat_level = int((1 + sqrt(1 + 7 * exp_count / 14)) / 2) caption += f"{chat_type} seviyesi: <code>{chat_level}</code>\n" if messages_viewable is not None: caption += f"Görünen mesajlar: <code>{messages_viewable}</code>\n" if messages_sent: caption += f"Gönderilen mesajlar: <code>{messages_sent}</code>\n" elif messages_sent_alt: caption += f"Gönderilen mesajlar: <code>{messages_sent_alt}</code> {warn_emoji}\n" if members is not None: caption += f"Üyeler: <code>{members}</code>\n" if admins is not None: caption += f"Adminler: <code>{admins}</code>\n" if bots_list: caption += f"Botlar: <code>{bots}</code>\n" if members_online: caption += f"Aktif üyeler: <code>{members_online}</code>\n" if restrcited_users is not None: caption += f"Yasaklanan üyeler: <code>{restrcited_users}</code>\n" if banned_users is not None: caption += f"Bloklanan üyeler: <code>{banned_users}</code>\n" if group_stickers is not None: caption += f"{chat_type} stickerları: <a href=\"t.me/addstickers/{chat.full_chat.stickerset.short_name}\">{group_stickers}</a>\n" caption += "\n" if not broadcast: caption += f"Yavaş mod: {slowmode}" if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled: caption += f", <code>{slowmode_time}s</code>\n\n" else: caption += "\n\n" if not broadcast: caption += f"Supergroup: {supergroup}\n\n" if hasattr(chat_obj_info, "restricted"): caption += f"Kısıtlanan: {restricted}\n" if chat_obj_info.restricted: caption += f"> Platform: {chat_obj_info.restriction_reason[0].platform}\n" caption += f"> Sebebi: {chat_obj_info.restriction_reason[0].reason}\n" caption += f"> Yazı: {chat_obj_info.restriction_reason[0].text}\n\n" else: caption += "\n" if hasattr(chat_obj_info, "scam") and chat_obj_info.scam: caption += "Scam: <b>Evet</b>\n\n" if hasattr(chat_obj_info, "verified"): caption += f"Telegram tarafından doğrulandı: {verified}\n\n" if description: caption += f"Açıklama: \n<code>{description}</code>\n" return caption
async def fetch_info(chat, event): chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False chat_type = "Kanal" if broadcast else "Grup" chat_title = chat_obj_info.title warn_emoji = emojize(":warning:") try: msg_info = await event.client( GetHistoryRequest(peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0)) except Exception as e: msg_info = None print("Exception:", e) first_msg_valid = True if msg_info and msg_info.messages and msg_info.messages[ 0].id == 1 else False creator_valid = True if first_msg_valid and msg_info.users else False creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = msg_info.users[ 0].first_name if creator_valid and msg_info.users[ 0].first_name is not None else "Deleted Account" creator_username = msg_info.users[ 0].username if creator_valid and msg_info.users[ 0].username is not None else None created = msg_info.messages[0].date if first_msg_valid else None former_title = msg_info.messages[ 0].action.title if first_msg_valid and type( msg_info.messages[0].action ) is MessageActionChannelMigrateFrom and msg_info.messages[ 0].action.title != chat_title else None try: dc_id, location = get_input_location(chat.full_chat.chat_photo) except Exception as e: dc_id = "Unknown" location = str(e) description = chat.full_chat.about members = chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count admins = chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None banned_users = chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None restrcited_users = chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None members_online = chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0 group_stickers = chat.full_chat.stickerset.title if hasattr( chat.full_chat, "stickerset") and chat.full_chat.stickerset else None messages_viewable = msg_info.count if msg_info else None messages_sent = chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None messages_sent_alt = chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = "<b>Evet</b>" if hasattr( chat_obj_info, "megagroup") and chat_obj_info.megagroup else "Hayır" slowmode = "<b>Evet</b>" if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else "Hayır" slowmode_time = chat.full_chat.slowmode_seconds if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None restricted = "<b>Evet</b>" if hasattr( chat_obj_info, "restricted") and chat_obj_info.restricted else "Hayır" verified = "<b>Evet</b>" if hasattr( chat_obj_info, "verified") and chat_obj_info.verified else "Hayır" username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None if admins is None: try: participants_admins = await event.client( GetParticipantsRequest(channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0)) admins = participants_admins.count if participants_admins else None except Exception as e: print("Exception:", e) if bots_list: for bot in bots_list: bots += 1 caption = "<b>GRUP BILGISI:</b>\n" caption += f"ID: <code>{chat_obj_info.id}</code>\n" if chat_title is not None: caption += f"{chat_type} ismi: {chat_title}\n" if former_title is not None: caption += f"Eski grup: {former_title}\n" if username is not None: caption += f"{chat_type} tipi: Herkese açık\n" caption += f"Link: {username}\n" else: caption += f"{chat_type} tipi: Gizli\n" if creator_username is not None: caption += f"Oluşturan kişi: {creator_username}\n" elif creator_valid: caption += f"Oluşturan kişi: <a href=\"tg://user?id={creator_id}\">{creator_firstname}</a>\n" if created is not None: caption += f"Oluşturulma tarihi: <code>{created.date().strftime('%b %d, %Y')} - {created.time()}</code>\n" else: caption += f"Oluşturulma tarihi: <code>{chat_obj_info.date.date().strftime('%b %d, %Y')} - {chat_obj_info.date.time()}</code> {warn_emoji}\n" caption += f"Veri merkezi ID: {dc_id}\n" if exp_count is not None: chat_level = int((1 + sqrt(1 + 7 * exp_count / 14)) / 2) caption += f"{chat_type} seviyesi: <code>{chat_level}</code>\n" if messages_viewable is not None: caption += f"Görüntülenebilir mesajlar: <code>{messages_viewable}</code>\n" if messages_sent: caption += f"Gönderilen mesajlar: <code>{messages_sent}</code>\n" elif messages_sent_alt: caption += f"Gönderilen mesajlar: <code>{messages_sent_alt}</code> {warn_emoji}\n" if members is not None: caption += f"Üye sayısı: <code>{members}</code>\n" if admins is not None: caption += f"Yönetici sayısı: <code>{admins}</code>\n" if bots_list: caption += f"Bot sayısı: <code>{bots}</code>\n" if members_online: caption += f"Çevrimiçi kişi sayısı: <code>{members_online}</code>\n" if restrcited_users is not None: caption += f"Kısıtlı kullanıcı sayısı: <code>{restrcited_users}</code>\n" if banned_users is not None: caption += f"Yasaklanmış kullanıcı sayısı: <code>{banned_users}</code>\n" if group_stickers is not None: caption += f"{chat_type} çıkartma paketi: <a href=\"t.me/addstickers/{chat.full_chat.stickerset.short_name}\">{group_stickers}</a>\n" caption += "\n" if not broadcast: caption += f"Yavaş mod: {slowmode}" if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled: caption += f", <code>{slowmode_time}s</code>\n\n" else: caption += "\n\n" if not broadcast: caption += f"Süper grup mu: {supergroup}\n\n" if hasattr(chat_obj_info, "restricted"): caption += f"Kısıtlı mı: {restricted}\n" if chat_obj_info.restricted: caption += f"> Platform: {chat_obj_info.restriction_reason[0].platform}\n" caption += f"> Nedeni: {chat_obj_info.restriction_reason[0].reason}\n" caption += f"> Metin: {chat_obj_info.restriction_reason[0].text}\n\n" else: caption += "\n" if hasattr(chat_obj_info, "scam") and chat_obj_info.scam: caption += "Scam: <b>Evet</b>\n\n" if hasattr(chat_obj_info, "verified"): caption += f"Telegram tarafından doğrulandı mı: {verified}\n\n" if description: caption += f"Grup açıklaması: \n<code>{description}</code>\n" return caption
async def fetch_info(chat, event): chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = (chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False) chat_type = "Channel" if broadcast else "Group" chat_title = chat_obj_info.title warn_emoji = emojize(":warning:") try: msg_info = await event.client( GetHistoryRequest( peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0, )) except Exception as e: msg_info = None print("Exception:", e) first_msg_valid = bool(msg_info and msg_info.messages and msg_info.messages[0].id == 1) creator_valid = bool(first_msg_valid and msg_info.users) creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = (msg_info.users[0].first_name if creator_valid and msg_info.users[0].first_name is not None else "Akun Terhapus") creator_username = (msg_info.users[0].username if creator_valid and msg_info.users[0].username is not None else None) created = msg_info.messages[0].date if first_msg_valid else None former_title = ( msg_info.messages[0].action.title if first_msg_valid and isinstance( msg_info.messages[0].action, MessageActionChannelMigrateFrom) and msg_info.messages[0].action.title != chat_title else None) try: dc_id, location = get_input_location(chat.full_chat.chat_photo) except Exception as e: dc_id = "Unknown" str(e) description = chat.full_chat.about members = (chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count) admins = (chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None) banned_users = (chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None) restrcited_users = (chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None) members_online = (chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0) group_stickers = (chat.full_chat.stickerset.title if hasattr(chat.full_chat, "stickerset") and chat.full_chat.stickerset else None) messages_viewable = msg_info.count if msg_info else None messages_sent = (chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None) messages_sent_alt = (chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None) exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = ("<b>Yes</b>" if hasattr(chat_obj_info, "megagroup") and chat_obj_info.megagroup else "Tidak") slowmode = ("<b>Yes</b>" if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else "Tidak") slowmode_time = (chat.full_chat.slowmode_seconds if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None) restricted = ("<b>Yes</b>" if hasattr(chat_obj_info, "restricted") and chat_obj_info.restricted else "Tidak") verified = ("<b>Yes</b>" if hasattr(chat_obj_info, "verified") and chat_obj_info.verified else "Tidak") username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None if admins is None: try: participants_admins = await event.client( GetParticipantsRequest( channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0, )) admins = participants_admins.count if participants_admins else None except Exception as e: print("Exception:", e) if bots_list: for _ in bots_list: bots += 1 caption = "<b>INFORMASI OBROLAN:</b>\n" caption += f"ID: <code>{chat_obj_info.id}</code>\n" if chat_title is not None: caption += f"{chat_type} Nama: {chat_title}\n" if former_title is not None: # Meant is the very first title caption += f"Nama Lama: {former_title}\n" if username is not None: caption += f"{chat_type} Type: Publik\n" caption += f"Link: {username}\n" else: caption += f"{chat_type} type: Privasi\n" if creator_username is not None: caption += f"Pembuat: {creator_username}\n" elif creator_valid: caption += ( f'Pembuat: <a href="tg://user?id={creator_id}">{creator_firstname}</a>\n' ) if created is not None: caption += f"Informasi Pembuatan: <code>{created.date().strftime('%b %d, %Y')} - {created.time()}</code>\n" else: caption += f"Informasi Pembuatan: <code>{chat_obj_info.date.date().strftime('%b %d, %Y')} - {chat_obj_info.date.time()}</code> {warn_emoji}\n" caption += f"Data Centre ID: {dc_id}\n" if exp_count is not None: chat_level = int((1 + sqrt(1 + 7 * exp_count / 14)) / 2) caption += f"{chat_type} Level: <code>{chat_level}</code>\n" if messages_viewable is not None: caption += f"Pesan Yang Dapat Dilihat: <code>{messages_viewable}</code>\n" if messages_sent: caption += f"Pesan Dikirim: <code>{messages_sent}</code>\n" elif messages_sent_alt: caption += f"Pesan Dikirim: <code>{messages_sent_alt}</code> {warn_emoji}\n" if members is not None: caption += f"Member: <code>{members}</code>\n" if admins is not None: caption += f"Admin: <code>{admins}</code>\n" if bots_list: caption += f"Bot: <code>{bots}</code>\n" if members_online: caption += f"Sedang Online: <code>{members_online}</code>\n" if restrcited_users is not None: caption += f"Pengguna Yang Dibatasi: <code>{restrcited_users}</code>\n" if banned_users is not None: caption += f"Banned Pengguna: <code>{banned_users}</code>\n" if group_stickers is not None: caption += f'{chat_type} Sticker: <a href="t.me/addstickers/{chat.full_chat.stickerset.short_name}">{group_stickers}</a>\n' caption += "\n" if not broadcast: caption += f"Mode Slow: {slowmode}" if (hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled): caption += f", <code>{slowmode_time}s</code>\n\n" else: caption += "\n\n" caption += f"Supergrup: {supergroup}\n\n" if hasattr(chat_obj_info, "Terbatas"): caption += f"Terbatas: {restricted}\n" if chat_obj_info.restricted: caption += f"> Platform: {chat_obj_info.restriction_reason[0].platform}\n" caption += f"> Alasan: {chat_obj_info.restriction_reason[0].reason}\n" caption += f"> Teks: {chat_obj_info.restriction_reason[0].text}\n\n" else: caption += "\n" if hasattr(chat_obj_info, "scam") and chat_obj_info.scam: caption += "Scam: <b>Yes</b>\n\n" if hasattr(chat_obj_info, "verified"): caption += f"Di Verifikasi Oleh Telegram: {verified}\n\n" if description: caption += f"Deskripsi: \n<code>{description}</code>\n" return caption
async def fetch_info(chat, event): # chat.chats is a list so we use get_entity() to avoid IndexError chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = (chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False) chat_type = "القنـاة" if broadcast else "المجمـوعه" chat_title = chat_obj_info.title warn_emoji = emojize(":warning:") try: msg_info = await event.client( GetHistoryRequest( peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0, )) except Exception as e: msg_info = None print("Exception:", e) # No chance for IndexError as it checks for msg_info.messages first first_msg_valid = (True if msg_info and msg_info.messages and msg_info.messages[0].id == 1 else False) # Same for msg_info.users creator_valid = True if first_msg_valid and msg_info.users else False creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = (msg_info.users[0].first_name if creator_valid and msg_info.users[0].first_name is not None else "Deleted Account") creator_username = (msg_info.users[0].username if creator_valid and msg_info.users[0].username is not None else None) created = msg_info.messages[0].date if first_msg_valid else None former_title = ( msg_info.messages[0].action.title if first_msg_valid and isinstance( msg_info.messages[0].action, MessageActionChannelMigrateFrom) and msg_info.messages[0].action.title != chat_title else None) try: dc_id, location = get_input_location(chat.full_chat.chat_photo) except Exception as e: dc_id = "Unknown" str(e) # this is some spaghetti I need to change description = chat.full_chat.about members = (chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count) admins = (chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None) banned_users = (chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None) restrcited_users = (chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None) members_online = (chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0) group_stickers = (chat.full_chat.stickerset.title if hasattr(chat.full_chat, "stickerset") and chat.full_chat.stickerset else None) messages_viewable = msg_info.count if msg_info else None messages_sent = (chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None) messages_sent_alt = (chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None) exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = ("<b>نعم</b>" if hasattr(chat_obj_info, "megagroup") and chat_obj_info.megagroup else "لا") slowmode = ("<b>مفعل</b>" if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else "معطل") slowmode_time = (chat.full_chat.slowmode_seconds if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None) restricted = ("<b>Yes</b>" if hasattr(chat_obj_info, "restricted") and chat_obj_info.restricted else "No") verified = ("<b>Yes</b>" if hasattr(chat_obj_info, "verified") and chat_obj_info.verified else "No") username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None # end of spaghetti block if admins is None: # use this alternative way if chat.full_chat.admins_count is None, # works even without being an admin try: participants_admins = await event.client( GetParticipantsRequest( channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0, )) admins = participants_admins.count if participants_admins else None except Exception as e: print("Exception:", e) if bots_list: for bot in bots_list: bots += 1 caption = "<b> 𓆰 𝑺𝑶𝑼𝑹𝑪𝑬 𝙎𝘼𝘿𝙏𝙃𝙊𝙉 - 𝑮𝑹𝑼𝑶𝑷 𝑫𝑨𝑻𝑨 𓆪\n𓍹ⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧ𓍻 </b>\n" caption += f"⪼ ايـدي المجمـوعه : <code>{chat_obj_info.id}</code>\n" if chat_title is not None: caption += f"⪼ اسـم {chat_type} : {chat_title}\n" if former_title is not None: # Meant is the very first title caption += f"⪼ الاسـم السـايق : {former_title}\n" if username is not None: caption += f"⪼ نـوع {chat_type} : عامة\n" caption += f"⪼ الرابـط : {username}\n" else: caption += f"⪼ نـوع {chat_type} : خاصة\n" if creator_username is not None: caption += f"⪼ المنشـئ : {creator_username}\n" elif creator_valid: caption += ( f'⪼ المنشـئ : <a href="tg://user?id={creator_id}">{creator_firstname}</a>\n' ) if created is not None: caption += f"⪼ الانشـاء : <code>{created.date().strftime('%b %d, %Y')} - {created.time()}</code>\n" else: caption += f"⪼ الانشـاء : <code>{chat_obj_info.date.date().strftime('%b %d, %Y')} - {chat_obj_info.date.time()}</code> {warn_emoji}\n" caption += f"⪼ مركـز البيـانات : {dc_id}\n" if exp_count is not None: chat_level = int((1 + sqrt(1 + 7 * exp_count / 14)) / 2) caption += f"⪼ مستوى {chat_type} : <code>{chat_level}</code>\n" if messages_viewable is not None: caption += f"⪼ الرسائل القابلة للعرض : <code>{messages_viewable}</code>\n" if messages_sent: caption += f"⪼ الرسائل المرسـله : <code>{messages_sent}</code>\n" elif messages_sent_alt: caption += ( f"⪼ الرسائل المرسـله : <code>{messages_sent_alt}</code> {warn_emoji}\n" ) if members is not None: caption += f"⪼ الاعضـاء : <code>{members}</code>\n" if admins is not None: caption += f"⪼ المشـرفين : <code>{admins}</code>\n" if bots_list: caption += f"⪼ البـوتات : <code>{bots}</code>\n" if members_online: caption += f"⪼ المتـصلون : <code>{members_online}</code>\n" if restrcited_users is not None: caption += f"⪼ المقيـدون : <code>{restrcited_users}</code>\n" if banned_users is not None: caption += f"⪼ المحظـورون : <code>{banned_users}</code>\n" if group_stickers is not None: caption += f'⪼ ملصـقات {chat_type}: <a href="t.me/addstickers/{chat.full_chat.stickerset.short_name}">{group_stickers}</a>\n' # caption += "\n" if not broadcast: caption += f"⪼ الارسـال البطيئ : {slowmode}" if (hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled): caption += f", <code>{slowmode_time}s</code>\n\n" else: caption += "\n" if not broadcast: caption += f"⪼ المجموعة خارقه: {supergroup}\n 𓍹ⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧ𓍻\n𓆩 𝙎𝙊𝙐𝙍𝘾𝞝 𝘿𝙀𝙑 - @rruuurr 𓆪" # if hasattr(chat_obj_info, "restricted"): # caption += f"محدد: {restricted}\n" if chat_obj_info.restricted: caption += f"> Platform: {chat_obj_info.restriction_reason[0].platform}\n" caption += f"> Reason: {chat_obj_info.restriction_reason[0].reason}\n" caption += f"> Text: {chat_obj_info.restriction_reason[0].text}\n\n" else: caption += "\n" if hasattr(chat_obj_info, "scam") and chat_obj_info.scam: caption += "Scam: <b>Yes</b>\n\n" # if hasattr(chat_obj_info, "verified"): # caption += f"تم التحقق بواسطة تلكرام: {verified}\n" # if description: caption += f"الوصف: \n<code>{description}</code>\n" caption = f"<b>𓆩 𝙎𝙊𝙐𝙍𝘾𝞝 𝘿𝙀𝙑 - @rruuurr 𓆪</b>" return caption
async def fetch_info(chat, event): chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = (chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False) chat_type = msgRep.CHANNEL if broadcast else msgRep.GROUP chat_title = chat_obj_info.title warn_emoji = u"\u26A0" try: msg_info = await event.client( GetHistoryRequest(peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0)) except: msg_info = None first_msg_valid = (True if msg_info and msg_info.messages and msg_info.messages[0].id == 1 else False) owner_id, owner_firstname, owner_username = (None, ) * 3 admins = 0 created = msg_info.messages[0].date if first_msg_valid else None former_title = ( msg_info.messages[0].action.title if first_msg_valid and type(msg_info.messages[0].action) is MessageActionChannelMigrateFrom and msg_info.messages[0].action.title != chat_title else None) dc_id = (chat.full_chat.chat_photo.dc_id if hasattr( chat.full_chat.chat_photo, "dc_id") else msgRep.UNKNOWN) # Prototype's spaghetti, although already salted by me description = chat.full_chat.about members = (chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count) banned_users = (chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None) restricted_users = (chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None) members_online = (chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0) group_stickers = (chat.full_chat.stickerset.title if hasattr(chat.full_chat, "stickerset") and chat.full_chat.stickerset else None) messages_viewable = (msg_info.count if msg_info and hasattr(msg_info, "count") else None) messages_sent = (chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None) messages_sent_alt = (chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None) if messages_sent and messages_viewable: deleted_messages = ((messages_sent - messages_viewable) if messages_sent >= messages_viewable else 0) elif messages_sent_alt and messages_viewable: deleted_messages = ((messages_sent_alt - messages_viewable) if messages_sent_alt >= messages_viewable else 0) else: deleted_messages = 0 username = ("@" + chat_obj_info.username if hasattr(chat_obj_info, "username") and chat_obj_info.username else None) chat_type_priv_or_public = (msgRep.CHAT_PUBLIC if username else msgRep.CHAT_PRIVATE) bots_list = chat.full_chat.bot_info # this is a list bots = len(bots_list) if bots_list else 0 supergroup = (True if hasattr(chat_obj_info, "megagroup") and chat_obj_info.megagroup else False) gigagroup = (True if hasattr(chat_obj_info, "gigagroup") and chat_obj_info.gigagroup else False) slowmode = (msgRep.YES_BOLD if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else msgRep.NO) slowmode_time = (chat.full_chat.slowmode_seconds if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None) restricted = (msgRep.YES_BOLD if hasattr(chat_obj_info, "restricted") and chat_obj_info.restricted else msgRep.NO) verified = (msgRep.YES_BOLD if hasattr(chat_obj_info, "verified") and chat_obj_info.verified else msgRep.NO) linked_chat_id = (chat.full_chat.linked_chat_id if hasattr( chat.full_chat, "linked_chat_id") else None) linked_chat = msgRep.YES_BOLD if linked_chat_id is not None else msgRep.NO linked_chat_title = None linked_chat_username = None if linked_chat_id is not None and chat.chats: for c in chat.chats: if c.id == linked_chat_id: linked_chat_title = c.title if c.username is not None: linked_chat_username = "******" + c.username break # End of spaghetti block try: is_channel_obj = True if isinstance(chat_obj_info, Channel) else False async for admin in (event.client.iter_participants( entity=chat.full_chat.id, filter=(ChannelParticipantsAdmins() if is_channel_obj else None))): if isinstance(admin.participant, (ChannelParticipantCreator, ChatParticipantCreator)): owner_id = admin.id owner_username = ("@" + admin.username if admin.username else None) if not is_channel_obj: break if is_channel_obj: admins += 1 except: pass caption = msgRep.CHATINFO caption += msgRep.CHAT_ID.format(format_chat_id(chat_obj_info)) caption += msgRep.CHAT_TYPE.format(chat_type, chat_type_priv_or_public) if not broadcast: if gigagroup: group_type = msgRep.GROUP_TYPE_GIGAGROUP elif supergroup: group_type = msgRep.GROUP_TYPE_SUPERGROUP else: group_type = msgRep.GROUP_TYPE_NORMAL caption += f"{msgRep.GROUP_TYPE}: {group_type}\n" if chat_title: caption += msgRep.CHAT_NAME.format(chat_title) if former_title: # Meant is the very first title caption += msgRep.FORMER_NAME.format(former_title) if username: caption += f"Link: {username}\n" if owner_username: caption += msgRep.OWNER.format(owner_username) elif owner_id and owner_firstname: caption += msgRep.OWNER_WITH_URL.format(owner_id, owner_firstname) if created: caption += msgRep.CREATED_NOT_NULL.format( created.date().strftime('%b %d, %Y'), created.time(), created.tzinfo) else: caption += msgRep.CREATED_NULL.format( chat_obj_info.date.date().strftime('%b %d, %Y'), chat_obj_info.date.time(), chat_obj_info.date.tzinfo, warn_emoji) caption += msgRep.DCID.format(dc_id) if messages_viewable is not None: caption += msgRep.VIEWABLE_MSG.format(messages_viewable) if deleted_messages: caption += msgRep.DELETED_MSG.format(deleted_messages) if messages_sent: caption += msgRep.SENT_MSG.format(messages_sent) elif messages_sent_alt: caption += msgRep.SENT_MSG_PRED.format(messages_sent_alt, warn_emoji) if members: caption += msgRep.MEMBERS.format(members) if admins: caption += msgRep.ADMINS.format(admins) if bots_list: caption += msgRep.BOT_COUNT.format(bots) if members_online: caption += msgRep.ONLINE_MEM.format(members_online) if restricted_users: caption += msgRep.RESTRICTED_COUNT.format(restricted_users) if banned_users: caption += msgRep.BANNEDCOUNT.format(banned_users) if group_stickers: caption += msgRep.GRUP_STICKERS.format( chat.full_chat.stickerset.short_name, group_stickers) caption += "\n" if broadcast or supergroup: caption += msgRep.LINKED_CHAT.format(linked_chat) if linked_chat_title: caption += msgRep.LINKED_CHAT_TITLE.format(linked_chat_title) if linked_chat_username: caption += f"> Link: {linked_chat_username}\n" caption += "\n" if not broadcast: caption += msgRep.SLW_MODE.format(slowmode) if hasattr(chat_obj_info, "slowmode_enabled") and \ chat_obj_info.slowmode_enabled: caption += msgRep.SLW_MODE_TIME.format(slowmode_time) else: caption += "\n\n" if hasattr(chat_obj_info, "restricted"): caption += msgRep.RESTR.format(restricted) if chat_obj_info.restricted: caption += msgRep.PFORM.format( chat_obj_info.restriction_reason[0].platform) caption += msgRep.REASON.format( chat_obj_info.restriction_reason[0].reason) caption += msgRep.TEXT.format( chat_obj_info.restriction_reason[0].text) else: caption += "\n" if hasattr(chat_obj_info, "scam") and chat_obj_info.scam: caption += msgRep.SCAM if hasattr(chat_obj_info, "verified"): caption += msgRep.VERFIED.format(verified) if description: caption += msgRep.DESCRIPTION.format(description) return caption
async def fetch_info(chat, event): # chat.chats is a list so we use get_entity() to avoid IndexError chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False chat_type = "Canale" if broadcast else "Gruppo" chat_title = chat_obj_info.title warn_emoji = emojize(":warning:") try: msg_info = await event.client( GetHistoryRequest(peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0)) except Exception as e: msg_info = None print("Exception:", e) # No chance for IndexError as it checks for msg_info.messages first first_msg_valid = True if msg_info and msg_info.messages and msg_info.messages[ 0].id == 1 else False # Same for msg_info.users creator_valid = True if first_msg_valid and msg_info.users else False creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = msg_info.users[ 0].first_name if creator_valid and msg_info.users[ 0].first_name is not None else "Account Eliminato" creator_username = msg_info.users[ 0].username if creator_valid and msg_info.users[ 0].username is not None else None created = msg_info.messages[0].date if first_msg_valid else None former_title = msg_info.messages[ 0].action.title if first_msg_valid and type( msg_info.messages[0].action ) is MessageActionChannelMigrateFrom and msg_info.messages[ 0].action.title != chat_title else None try: dc_id, location = get_input_location(chat.full_chat.chat_photo) except Exception as e: dc_id = "Sconosciuto" location = str(e) #this is some spaghetti I need to change description = chat.full_chat.about members = chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count admins = chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None banned_users = chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None restrcited_users = chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None members_online = chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0 group_stickers = chat.full_chat.stickerset.title if hasattr( chat.full_chat, "stickerset") and chat.full_chat.stickerset else None messages_viewable = msg_info.count if msg_info else None messages_sent = chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None messages_sent_alt = chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = "<b>Si</b>" if hasattr( chat_obj_info, "megagroup") and chat_obj_info.megagroup else "No" slowmode = "<b>Si</b>" if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else "No" slowmode_time = chat.full_chat.slowmode_seconds if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None restricted = "<b>Si</b>" if hasattr( chat_obj_info, "restricted") and chat_obj_info.restricted else "No" verified = "<b>Si</b>" if hasattr( chat_obj_info, "verified") and chat_obj_info.verified else "No" username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None #end of spaghetti block if admins is None: # use this alternative way if chat.full_chat.admins_count is None, works even without being an admin try: participants_admins = await event.client( GetParticipantsRequest(channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0)) admins = participants_admins.count if participants_admins else None except Exception as e: print("Exception:", e) if bots_list: for bot in bots_list: bots += 1 caption = "<b></b>\n" caption += f"<b>🖊️Info della Chat</b>\n• 🆔: <code>{chat_obj_info.id}</code>\n" if chat_title is not None: caption += f"<b>• 📰Titolo del {chat_type} :</b> {chat_title}\n" if former_title is not None: # Meant is the very first title caption += f"<b>• 🥇Titolo Originario:</b> {former_title}\n" if username is not None: caption += f"<b>• 🏷Tipo di {chat_type}:</b> Publico\n" caption += f"<b>• 🖇Link:<b> {username}\n" else: caption += f"<b>• 🏷Tipo di {chat_type} :</b> Privato\n" if creator_username is not None: caption += f"<b>• 👑Creatore:</b> {creator_username}\n" elif creator_valid: caption += f"<b>• 👑Creatore:</b> <a href=\"tg://user?id={creator_id}\">{creator_firstname}</a>\n" if created is not None: caption += f"<b>• 🕐Creato:</b> <code>{created.date().strftime('%b %d, %Y')} - {created.time()}</code>\n" else: caption += f"<b>• 🕐Creato:</b> <code>{chat_obj_info.date.date().strftime('%b %d, %Y')} - {chat_obj_info.date.time()}</code> {warn_emoji}\n" caption += f"<b>• 📡Data Center ID:</b> {dc_id}\n" if exp_count is not None: chat_level = int((1 + sqrt(1 + 7 * exp_count / 14)) / 2) caption += f"<b>• 🏁Livello del {chat_type}:</b> <code>{chat_level}</code>\n" if messages_viewable is not None: caption += f"<b>• ✉️Messaggi Visibili:</b> <code>{messages_viewable}</code>\n" if messages_sent: caption += f"<b>• 📨Messaggi inviati:</b> <code>{messages_sent}</code>\n" elif messages_sent_alt: caption += f"<b>• 📨Messaggi Inviati:</b> <code>{messages_sent_alt}</code> {warn_emoji}\n" if members is not None: caption += f"<b>• 👥Membri:</b> <code>{members}</code>\n" if admins is not None: caption += f"<b>• ⚜Amministratori:</b> <code>{admins}</code>\n" if bots_list: caption += f"<b>• 🤖Bot</b>: <code>{bots}</code>\n" if members_online: caption += f"<b>• 👥💡Membri Online al Momento:</b> <code>{members_online}</code>\n" if restrcited_users is not None: caption += f"<b>• 👥🚨Utenti Limitati:</b> <code>{restrcited_users}</code>\n" if banned_users is not None: caption += f"<b>• 👥🚷Utenti Bannati:</b> <code>{banned_users}</code>\n" if group_stickers is not None: caption += f"<b>• 🎨Sticker del {chat_type}:</b> <a href=\"t.me/addstickers/{chat.full_chat.stickerset.short_name}\">{group_stickers}</a>\n" caption += "\n" if not broadcast: caption += f"<b>• 🐌Modalità Lenta:</b> {slowmode}" if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled: caption += f", <code>{slowmode_time}s</code>\n\n" else: caption += "\n\n" if not broadcast: caption += f"<b>🏆SuperGruppo:<b> {supergroup}\n\n" if hasattr(chat_obj_info, "restricted"): caption += f"<b>🚨Limitato:<b> {restricted}\n" if chat_obj_info.restricted: caption += f"<b>> 💻Piattaforma:<b> {chat_obj_info.restriction_reason[0].platform}\n" caption += f"<b>> 📝Motivo:<b> {chat_obj_info.restriction_reason[0].reason}\n" caption += f"<b>> 📖Testo:<b> {chat_obj_info.restriction_reason[0].text}\n\n" else: caption += "\n" if hasattr(chat_obj_info, "scam") and chat_obj_info.scam: caption += "<b>⚠️Scam:<b> <b>Si</b>\n\n" if hasattr(chat_obj_info, "verified"): caption += f"✅<b>Verificato da Telegram:<b> {verified}\n\n" if description: caption += f"<b>💬Descrizione:<b> \n<code>{description}</code>\n" return caption
async def fetch_info(chat, event): # chat.chats is a list so we use get_entity() to avoid IndexError chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False chat_type = "Channel" if broadcast else "Group" chat_title = chat_obj_info.title warn_emoji = emojize(":warning:") try: msg_info = await event.client( GetHistoryRequest(peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0)) except Exception as e: msg_info = None print("Exception:", e) # No chance for IndexError as it checks for msg_info.messages first first_msg_valid = True if msg_info and msg_info.messages and msg_info.messages[ 0].id == 1 else False # Same for msg_info.users creator_valid = True if first_msg_valid and msg_info.users else False creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = msg_info.users[ 0].first_name if creator_valid and msg_info.users[ 0].first_name is not None else "Deleted Account" creator_username = msg_info.users[ 0].username if creator_valid and msg_info.users[ 0].username is not None else None created = msg_info.messages[0].date if first_msg_valid else None former_title = msg_info.messages[ 0].action.title if first_msg_valid and type( msg_info.messages[0].action ) is MessageActionChannelMigrateFrom and msg_info.messages[ 0].action.title != chat_title else None try: dc_id, location = get_input_location(chat.full_chat.chat_photo) except Exception as e: dc_id = "Unknown" location = str(e) #this is some spaghetti I need to change description = chat.full_chat.about members = chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count admins = chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None banned_users = chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None members_online = chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0 group_stickers = chat.full_chat.stickerset.title if hasattr( chat.full_chat, "stickerset") and chat.full_chat.stickerset else None messages_viewable = msg_info.count if msg_info else None messages_sent = chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None messages_sent_alt = chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = "<b>Yes</b>" if hasattr( chat_obj_info, "megagroup") and chat_obj_info.megagroup else "No" username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None #end of spaghetti block if admins is None: # use this alternative way if chat.full_chat.admins_count is None, works even without being an admin try: participants_admins = await event.client( GetParticipantsRequest(channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0)) admins = participants_admins.count if participants_admins else None except Exception as e: print("Exception:", e) if bots_list: for bot in bots_list: bots += 1 caption = "<b>📌 CHAT INFO:</b>\n\n" caption += f" ★ ID: <code>{chat_obj_info.id}</code>\n" if chat_title is not None: caption += f" ★ {chat_type} : {chat_title}\n" if former_title is not None: # Meant is the very first title caption += f" ★ Former name: {former_title}\n" if username is not None: caption += f" ★ {chat_type} : Pubblico\n" caption += f" ★ Link: {username}\n" else: caption += f" ★ {chat_type} : Privato\n" if creator_username is not None: caption += f" ★ Founder: {creator_username}\n" elif creator_valid: caption += f" ★ Founder: <a href=\"tg://user?id={creator_id}\">{creator_firstname}</a>\n" if created is not None: caption += f" ★ Creato il: <code>{created.date().strftime('%b %d, %Y')} - {created.time()}</code>\n" else: caption += f" ★ Creato il: <code>{chat_obj_info.date.date().strftime('%b %d, %Y')} - {chat_obj_info.date.time()}</code> {warn_emoji}\n" caption += f" ★ DC ID: {dc_id}\n" if messages_viewable is not None: caption += f" ★ View messaggi: <code>{messages_viewable}</code>\n" if messages_sent: caption += f" ★ Messaggi scritti: <code>{messages_sent}</code>\n" elif messages_sent_alt: caption += f" ★ Messages sent: <code>{messages_sent_alt}</code> {warn_emoji}\n" if members is not None: caption += f" ★ Membri: <code>{members}</code>\n" if admins is not None: caption += f" ★ Admins: <code>{admins}</code>\n" if bots_list: caption += f" ★ Bot: <code>{bots}</code>\n" if members_online: caption += f" ★ User online: <code>{members_online}</code>\n" if banned_users is not None: caption += f" ★ User bannati: <code>{banned_users}</code>\n" if group_stickers is not None: caption += f" ★ {chat_type} Stickers: <a href=\"t.me/addstickers/{chat.full_chat.stickerset.short_name}\">{group_stickers}</a>\n" if not broadcast: caption += f" ★ Supergruppo: {supergroup}\n\n" if description: caption += f"<b>📌 DESCRIZIONE:</b>\n\n<code>{description}</code>\n" return caption
def _update_admins_list(self): result = self._client.invoke(GetParticipantsRequest(self._peer, ChannelParticipantsAdmins(), 0, 100)) self._admins = getattr(result, 'participants', []) print('Current tamada admins: ', self._admins)
def scrape_task(user_id, group_id, tg_account_id=None): user = User.objects.get(pk=user_id) group = TelegramGroup.objects.get(pk=group_id) if tg_account_id: account = TelegramAccount.objects.get(pk=tg_account_id) else: try: account = random.choice( TelegramAccount.objects.filter(active=True, confirmed=True)) except IndexError: return { 'success': False, 'error': _('No available active accounts ' 'for scrapping.') } proxy_settings = (socks.HTTP, settings.PROXY_HOST, settings.PROXY_PORT, True, settings.PROXY_USERNAME + '-session-{}'.format(random.randint(9999, 9999999)), settings.PROXY_PASSWORD) account.set_is_used(True) client = TelegramClient(StringSession(account.session), account.api_id, account.api_hash, proxy=proxy_settings) client.connect() try: try: group_entity = client.get_input_entity( group.username if group.username else group.join_link) except Exception as e: logger.exception(e) account.set_is_used(False) client.disconnect() return {'success': False, 'error': _('Error finding group.')} joined = join_group(client, account, group_entity) if not joined: account.set_is_used(False) client.disconnect() return {'success': False, 'error': _('Error joining group.')} elif isinstance(joined, dict): # means there was an error account.set_is_used(False) client.disconnect() return joined try: members = client.get_participants( group_entity, aggressive=True, filter=ChannelParticipantsRecent()) admins = client.get_participants( group_entity, aggressive=True, filter=ChannelParticipantsAdmins()) members = [ m for m in members if not m.bot and # skip bots m not in admins and # skip admins m.username and # skip without usernames not m.is_self ] # skip if members is current client user except: account.set_is_used(False) client.disconnect() return { 'success': False, 'error': _('Error getting list of group ' 'members.') } client.disconnect() account.set_is_used(False) with transaction.atomic(): for i, m in enumerate(members): TelegramContact.objects.get_or_create(user=user, group=group, username=m.username, priority=i + 1) message = _('Scrapped {} users.'.format(len(members))) return {'success': True, 'error': None, 'message': message} except Exception as e: logger.exception(e) return { 'success': True, 'error': _('Error getting list of group ' 'members.') }
async def spamschutz( event: Union[ChatAction.Event, NewMessage.Event] ) -> None: # pylint: disable = R0911 """Automatically gban spamwatch banned users. This plugin gban users banned in Spamwatch upon joining,getting added to the group or when writing a message. A message will be sent to notify Users of the action, this message will be deleted after 2 minutes. Tags: polizei: exclude: Don't ban spamwatched users grenschutz: silent: Don't send the notification message exclude: Don't ban spamwatched users """ if event.is_private: return if isinstance(event, ChatAction.Event): if event.user_left or event.user_kicked: return if event.action_message is None: return elif not isinstance( event.action_message.action, (MessageActionChatJoinedByLink, MessageActionChatAddUser)): return client: Client = event.client chat: Channel = await event.get_chat() config = Config() db = client.db swoclient = client.swo tags = await Tags.from_event(event) polizei_tag = tags.get('polizei') grenzschutz_tag = tags.get('grenzschutz') silent = grenzschutz_tag == 'silent' if swoclient is None: return if isinstance(event, ChatAction.Event): uid = event.user_id elif isinstance(event, NewMessage.Event): uid = event.message.sender_id else: return if uid is None: return if uid < 0: return ban = swoclient.get_ban(uid) if not ban: result = await db.banlist.get(uid) if result: ban_reason = result.reason if '[SW]' in ban_reason: await client.ungban(uid) return reason = '[SW] ' + ban.reason if 'Kriminalamt' in reason: return await client.gban(uid, reason) if grenzschutz_tag == 'exclude' or polizei_tag == 'exclude': return if not chat.creator and not chat.admin_rights: return if chat.admin_rights and not chat.admin_rights.ban_users: return admins = [ p.id for p in await client.get_participants( event.chat_id, filter=ChannelParticipantsAdmins()) ] if uid not in admins: try: await client.ban(chat, uid) except UserIdInvalidError as err: logger.error("Error occurred while banning %s", err) return await event.delete() if not silent: try: user = await client.get_entity(uid) message = KanTeXDocument( Section( Bold('SpamSchutz Grenzschutz Ban'), KeyValueItem( Bold("User"), f'{Mention(user.first_name, uid)} [{Code(uid)}]'), KeyValueItem(Bold("Reason"), reason))) await client.respond(event, str(message), reply=False, delete='2m') except ValueError as err: logger.error(err)
async def fetch_info(chat, event): # chat.chats is a list so we use get_entity() to avoid IndexError chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False chat_type = "Channel" if broadcast else "Group" chat_title = chat_obj_info.title warn_emoji = emojize(":warning:") try: msg_info = await event.client( GetHistoryRequest(peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0)) except Exception as e: msg_info = None print("Exception:", e) # No chance for IndexError as it checks for msg_info.messages first first_msg_valid = True if msg_info and msg_info.messages and msg_info.messages[ 0].id == 1 else False # Same for msg_info.users creator_valid = True if first_msg_valid and msg_info.users else False creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = msg_info.users[ 0].first_name if creator_valid and msg_info.users[ 0].first_name is not None else "Deleted Account" creator_username = msg_info.users[ 0].username if creator_valid and msg_info.users[ 0].username is not None else None created = msg_info.messages[0].date if first_msg_valid else None former_title = msg_info.messages[ 0].action.title if first_msg_valid and type( msg_info.messages[0].action ) is MessageActionChannelMigrateFrom and msg_info.messages[ 0].action.title != chat_title else None try: dc_id, location = get_input_location(chat.full_chat.chat_photo) except Exception as e: dc_id = "Unknown" location = str(e) #this is some spaghetti I need to change description = chat.full_chat.about members = chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count admins = chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None banned_users = chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None restrcited_users = chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None members_online = chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0 group_stickers = chat.full_chat.stickerset.title if hasattr( chat.full_chat, "stickerset") and chat.full_chat.stickerset else None messages_viewable = msg_info.count if msg_info else None messages_sent = chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None messages_sent_alt = chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = "<b>Yes</b>" if hasattr( chat_obj_info, "megagroup") and chat_obj_info.megagroup else "No" slowmode = "<b>Yes</b>" if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else "No" slowmode_time = chat.full_chat.slowmode_seconds if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None restricted = "<b>Yes</b>" if hasattr( chat_obj_info, "restricted") and chat_obj_info.restricted else "No" verified = "<b>Yes</b>" if hasattr( chat_obj_info, "verified") and chat_obj_info.verified else "No" username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None #end of spaghetti block if admins is None: # use this alternative way if chat.full_chat.admins_count is None, works even without being an admin try: participants_admins = await event.client( GetParticipantsRequest(channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0)) admins = participants_admins.count if participants_admins else None except Exception as e: print("Exception:", e) if bots_list: for bot in bots_list: bots += 1 caption = "<b>معلومات المحادثة:</b>\n" caption += f"ايدي: <code>{chat_obj_info.id}</code>\n" if chat_title is not None: caption += f"{chat_type} الاسم: {chat_title}\n" if former_title is not None: # Meant is the very first title caption += f"الاسم السابق: {former_title}\n" if username is not None: caption += f"{chat_type} type: Public\n" caption += f"الرابط: {username}\n" else: caption += f"{chat_type} type: Private\n" if creator_username is not None: caption += f"المنشئ: {creator_username}\n" elif creator_valid: caption += f"المنشئ: <a href=\"tg://user?id={creator_id}\">{creator_firstname}</a>\n" if created is not None: caption += f"انشئت: <code>{created.date().strftime('%b %d, %Y')} - {created.time()}</code>\n" else: caption += f"انشئت: <code>{chat_obj_info.date.date().strftime('%b %d, %Y')} - {chat_obj_info.date.time()}</code> {warn_emoji}\n" caption += f"معرف مركز البيانات: {dc_id}\n" if exp_count is not None: chat_level = int((1 + sqrt(1 + 7 * exp_count / 14)) / 2) caption += f"{chat_type} مستوى: <code>{chat_level}</code>\n" if messages_viewable is not None: caption += f"رسائل قابلة للعرض: <code>{messages_viewable}</code>\n" if messages_sent: caption += f"تم إرسال الرسائل: <code>{messages_sent}</code>\n" elif messages_sent_alt: caption += f"تم إرسال الرسائل: <code>{messages_sent_alt}</code> {warn_emoji}\n" if members is not None: caption += f"الاعضاء: <code>{members}</code>\n" if admins is not None: caption += f"المسؤولون: <code>{admins}</code>\n" if bots_list: caption += f"البوتات: <code>{bots}</code>\n" if members_online: caption += f"عبر الانترنيت الان: <code>{members_online}</code>\n" if restrcited_users is not None: caption += f"المستخدمون المقيّدون: <code>{restrcited_users}</code>\n" if banned_users is not None: caption += f"المستخدمون المحظورون: <code>{banned_users}</code>\n" if group_stickers is not None: caption += f"{chat_type} ملصقات: <a href=\"t.me/addstickers/{chat.full_chat.stickerset.short_name}\">{group_stickers}</a>\n" caption += "\n" if not broadcast: caption += f"وضع بطيء: {slowmode}" if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled: caption += f", <code>{slowmode_time}s</code>\n\n" else: caption += "\n\n" if not broadcast: caption += f"المجموعة الفائقة: {supergroup}\n\n" if hasattr(chat_obj_info, "restricted"): caption += f"محدد: {restricted}\n" if chat_obj_info.restricted: caption += f"> منصة: {chat_obj_info.restriction_reason[0].platform}\n" caption += f"> السبب: {chat_obj_info.restriction_reason[0].reason}\n" caption += f"> النص: {chat_obj_info.restriction_reason[0].text}\n\n" else: caption += "\n" if hasattr(chat_obj_info, "scam") and chat_obj_info.scam: caption += "احتيال: <b>Yes</b>\n\n" if hasattr(chat_obj_info, "verified"): caption += f"موثوق من تيليكرام: {verified}\n\n" if description: caption += f"وصف: \n<code>{description}</code>\n" return caption
async def fetch_info(chat, event): chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False chat_type = "Channel" if broadcast else "Group" chat_title = chat_obj_info.title warn_emoji = emojize(":warning:") try: msg_info = await event.client( GetHistoryRequest(peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0)) except Exception as e: msg_info = None print("Exception:", e) first_msg_valid = True if msg_info and msg_info.messages and msg_info.messages[ 0].id == 1 else False creator_valid = True if first_msg_valid and msg_info.users else False creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = msg_info.users[ 0].first_name if creator_valid and msg_info.users[ 0].first_name is not None else "Deleted Account" creator_username = msg_info.users[ 0].username if creator_valid and msg_info.users[ 0].username is not None else None created = msg_info.messages[0].date if first_msg_valid else None former_title = msg_info.messages[ 0].action.title if first_msg_valid and type( msg_info.messages[0].action ) is MessageActionChannelMigrateFrom and msg_info.messages[ 0].action.title != chat_title else None try: dc_id, location = get_input_location(chat.full_chat.chat_photo) except Exception as e: dc_id = "Unknown" location = str(e) description = chat.full_chat.about members = chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count admins = chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None banned_users = chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None restrcited_users = chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None members_online = chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0 group_stickers = chat.full_chat.stickerset.title if hasattr( chat.full_chat, "stickerset") and chat.full_chat.stickerset else None messages_viewable = msg_info.count if msg_info else None messages_sent = chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None messages_sent_alt = chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = "<b>Bəli</b>" if hasattr( chat_obj_info, "megagroup") and chat_obj_info.megagroup else "No" slowmode = "<b>Bəli</b>" if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else "No" slowmode_time = chat.full_chat.slowmode_seconds if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None restricted = "<b>Bəli</b>" if hasattr( chat_obj_info, "restricted") and chat_obj_info.restricted else "No" verified = "<b>Bəli</b>" if hasattr( chat_obj_info, "verified") and chat_obj_info.verified else "No" username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None if admins is None: try: participants_admins = await event.client( GetParticipantsRequest(channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0)) admins = participants_admins.count if participants_admins else None except Exception as e: print("Exception:", e) if bots_list: for bot in bots_list: bots += 1 caption = "<b>Qrup məlumatı:</b>\n" caption += f"ID: <code>{chat_obj_info.id}</code>\n" if chat_title is not None: caption += f"{chat_type} ismi: {chat_title}\n" if former_title is not None: caption += f"Əvvəlki ad: {former_title}\n" if username is not None: caption += f"{chat_type} türü: Açık\n" caption += f"Link: {username}\n" else: caption += f"{chat_type} Türü: Gizli\n" if creator_username is not None: caption += f"Qurucu: {creator_username}\n" elif creator_valid: caption += f"Qurucu: <a href=\"tg://user?id={creator_id}\">{creator_firstname}</a>\n" if created is not None: caption += f"Qurulum vaxtı: <code>{created.date().strftime('%b %d, %Y')} - {created.time()}</code>\n" else: caption += f"Qurulum vaxtı: <code>{chat_obj_info.date.date().strftime('%b %d, %Y')} - {chat_obj_info.date.time()}</code> {warn_emoji}\n" caption += f"Veri Mərkəzi ID: {dc_id}\n" if exp_count is not None: chat_level = int((1 + sqrt(1 + 7 * exp_count / 14)) / 2) caption += f"{chat_type} səviyyəsi: <code>{chat_level}</code>\n" if messages_viewable is not None: caption += f"Görünən mesajlar: <code>{messages_viewable}</code>\n" if messages_sent: caption += f"Mesajlar göndərildi: <code>{messages_sent}</code>\n" elif messages_sent_alt: caption += f"Mesajlar göndərildi: <code>{messages_sent_alt}</code> {warn_emoji}\n" if members is not None: caption += f"Üzvlər: <code>{members}</code>\n" if admins is not None: caption += f"Adminlər: <code>{admins}</code>\n" if bots_list: caption += f"Botlar: <code>{bots}</code>\n" if members_online: caption += f"İndi aktivdir: <code>{members_online}</code>\n" if restrcited_users is not None: caption += f"Məhdud üzvlər: <code>{restrcited_users}</code>\n" if banned_users is not None: caption += f"Üzvlər qadağan edildi: <code>{banned_users}</code>\n" if group_stickers is not None: caption += f"{chat_type} stickerləri: <a href=\"t.me/addstickers/{chat.full_chat.stickerset.short_name}\">{group_stickers}</a>\n" caption += "\n" if not broadcast: caption += f"Yavaş mod: {slowmode}" if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled: caption += f", <code>{slowmode_time}s</code>\n\n" else: caption += "\n\n" if not broadcast: caption += f"Supergroup: {supergroup}\n\n" if hasattr(chat_obj_info, "restricted"): caption += f"Məhduddur: {restricted}\n" if chat_obj_info.restricted: caption += f"> Platforma: {chat_obj_info.restriction_reason[0].platform}\n" caption += f"> Səbəb: {chat_obj_info.restriction_reason[0].reason}\n" caption += f"> Yazı: {chat_obj_info.restriction_reason[0].text}\n\n" else: caption += "\n" if hasattr(chat_obj_info, "scam") and chat_obj_info.scam: caption += "Scam: <b>Bəli</b>\n\n" if hasattr(chat_obj_info, "verified"): caption += f"Telegram tərəfindən doğrulandı: {verified}\n\n" if description: caption += f"Açıqlama: \n<code>{description}</code>\n" return caption
async def fetch_info(chat, event): # chat.chats is a list so we use get_entity() to avoid IndexError chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = (chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False) chat_type = "Channel" if broadcast else "Group" chat_title = chat_obj_info.title warn_emoji = emojize(":warning:") try: msg_info = await event.client( GetHistoryRequest( peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0, )) except Exception as e: msg_info = None print("Exception:", e) # No chance for IndexError as it checks for msg_info.messages first first_msg_valid = bool(msg_info and msg_info.messages and msg_info.messages[0].id == 1) # Same for msg_info.users creator_valid = bool(first_msg_valid and msg_info.users) creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = (msg_info.users[0].first_name if creator_valid and msg_info.users[0].first_name is not None else "Deleted Account") creator_username = (msg_info.users[0].username if creator_valid and msg_info.users[0].username is not None else None) created = msg_info.messages[0].date if first_msg_valid else None former_title = ( msg_info.messages[0].action.title if first_msg_valid and isinstance( msg_info.messages[0].action, MessageActionChannelMigrateFrom) and msg_info.messages[0].action.title != chat_title else None) try: dc_id, _ = get_input_location(chat.full_chat.chat_photo) except Exception as e: dc_id = "Unknown" str(e) # this is some spaghetti I need to change description = chat.full_chat.about members = (chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count) admins = (chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None) banned_users = (chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None) restrcited_users = (chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None) members_online = (chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0) group_stickers = (chat.full_chat.stickerset.title if hasattr(chat.full_chat, "stickerset") and chat.full_chat.stickerset else None) messages_viewable = msg_info.count if msg_info else None messages_sent = (chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None) messages_sent_alt = (chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None) exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = ("<b>Ya</b>" if hasattr(chat_obj_info, "megagroup") and chat_obj_info.megagroup else "Tidak") slowmode = ("<b>Ya</b>" if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else "Tidak") slowmode_time = (chat.full_chat.slowmode_seconds if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None) restricted = ("<b>Ya</b>" if hasattr(chat_obj_info, "restricted") and chat_obj_info.restricted else "Tidak") verified = ("<b>Ya</b>" if hasattr(chat_obj_info, "verified") and chat_obj_info.verified else "Tidak") username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None # end of spaghetti block if admins is None: # use this alternative way if chat.full_chat.admins_count is None, # works even without being an admin try: participants_admins = await event.client( GetParticipantsRequest( channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0, )) admins = participants_admins.count if participants_admins else None except Exception as e: print("Exception:", e) if bots_list: for _ in bots_list: bots += 1 caption = "<b>INFO OBROLAN</b>\n" caption += f"ID : <code>{chat_obj_info.id}</code>\n" if chat_title is not None: caption += f"Nama {chat_type} : {chat_title}\n" if former_title is not None: # Meant is the very first title caption += f"Nama lama : {former_title}\n" if username is not None: caption += f"Tipe {chat_type} : Publik\n" caption += f"Tautan : {username}\n" else: caption += f"Tipe {chat_type} : Pribadi\n" if creator_username is not None: caption += f"Pembuat : {creator_username}\n" elif creator_valid: caption += ( f'Pembuat : <a href="tg://user?id={creator_id}">{creator_firstname}</a>\n' ) if created is not None: caption += f"Dibuat : <code>{created.date().strftime('%b %d, %Y')} - {created.time()}</code>\n" else: caption += f"Dibuat : <code>{chat_obj_info.date.date().strftime('%b %d, %Y')} - {chat_obj_info.date.time()}</code> {warn_emoji}\n" caption += f"ID Pusat Data : {dc_id}\n" if exp_count is not None: chat_level = int((1 + sqrt(1 + 7 * exp_count / 14)) / 2) caption += f"Tingkat {chat_type} : <code>{chat_level}</code>\n" if messages_viewable is not None: caption += f"Pesan yang dapat dilihat : <code>{messages_viewable}</code>\n" if messages_sent: caption += f"Pesan terkirim : <code>{messages_sent}</code>\n" elif messages_sent_alt: caption += f"Pesan terkirim : <code>{messages_sent_alt}</code> {warn_emoji}\n" if members is not None: caption += f"Anggota : <code>{members}</code>\n" if admins is not None: caption += f"Administrator : <code>{admins}</code>\n" if bots_list: caption += f"Bot : <code>{bots}</code>\n" if members_online: caption += f"Sedang online : <code>{members_online}</code>\n" if restrcited_users is not None: caption += f"Pengguna yang dibatasi : <code>{restrcited_users}</code>\n" if banned_users is not None: caption += f"Pengguna yang dilarang : <code>{banned_users}</code>\n" if group_stickers is not None: caption += f'Stiker {chat_type} : <a href="t.me/addstickers/{chat.full_chat.stickerset.short_name}">{group_stickers}</a>\n' caption += "\n" if not broadcast: caption += f"Mode lambat : {slowmode}" if (hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled): caption += f", <code>{slowmode_time}s</code>\n\n" else: caption += "\n\n" if not broadcast: caption += f"Supergrup : {supergroup}\n\n" if hasattr(chat_obj_info, "restricted"): caption += f"Terbatas : {restricted}\n" if chat_obj_info.restricted: caption += f"> Platform : {chat_obj_info.restriction_reason[0].platform}\n" caption += f"> Alasan : {chat_obj_info.restriction_reason[0].reason}\n" caption += f"> Teks : {chat_obj_info.restriction_reason[0].text}\n\n" else: caption += "\n" if hasattr(chat_obj_info, "scam") and chat_obj_info.scam: caption += "Penipuan : <b>Ya</b>\n\n" if hasattr(chat_obj_info, "verified"): caption += f"Diverifikasi oleh Telegram : {verified}\n\n" if description: caption += f"Deskripsi : \n<code>{description}</code>\n" return caption
async def fetch_info(chat, event): # chat.chats is a list so we use get_entity() to avoid IndexError chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False chat_type = "Channel" if broadcast else "Group" chat_title = chat_obj_info.title warn_emoji = emojize(":warning:") try: msg_info = await event.client( GetHistoryRequest(peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0)) except Exception as e: msg_info = None print("Exception:", e) # No chance for IndexError as it checks for msg_info.messages first first_msg_valid = True if msg_info and msg_info.messages and msg_info.messages[ 0].id == 1 else False # Same for msg_info.users creator_valid = True if first_msg_valid and msg_info.users else False creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = msg_info.users[ 0].first_name if creator_valid and msg_info.users[ 0].first_name is not None else "Deleted Account" creator_username = msg_info.users[ 0].username if creator_valid and msg_info.users[ 0].username is not None else None created = msg_info.messages[0].date if first_msg_valid else None former_title = msg_info.messages[ 0].action.title if first_msg_valid and type( msg_info.messages[0].action ) is MessageActionChannelMigrateFrom and msg_info.messages[ 0].action.title != chat_title else None try: dc_id, location = get_input_location(chat.full_chat.chat_photo) except Exception as e: dc_id = "Unknown" location = str(e) #this is some spaghetti I need to change description = chat.full_chat.about members = chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count admins = chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None banned_users = chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None restrcited_users = chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None members_online = chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0 group_stickers = chat.full_chat.stickerset.title if hasattr( chat.full_chat, "stickerset") and chat.full_chat.stickerset else None messages_viewable = msg_info.count if msg_info else None messages_sent = chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None messages_sent_alt = chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = "<b>Evet</b>" if hasattr( chat_obj_info, "megagroup") and chat_obj_info.megagroup else "No" slowmode = "<b>Evet</b>" if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else "No" slowmode_time = chat.full_chat.slowmode_seconds if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None restricted = "<b>Evet</b>" if hasattr( chat_obj_info, "restricted") and chat_obj_info.restricted else "No" verified = "<b>Evet</b>" if hasattr( chat_obj_info, "verified") and chat_obj_info.verified else "No" username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None #end of spaghetti block if admins is None: # use this alternative way if chat.full_chat.admins_count is None, works even without being an admin try: participants_admins = await event.client( GetParticipantsRequest(channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0)) admins = participants_admins.count if participants_admins else None except Exception as e: print("Exception:", e) if bots_list: for bot in bots_list: bots += 1 caption = "<b>Grup İstatistikleri:</b>\n" caption += f"ID: <code>{chat_obj_info.id}</code>\n" if messages_viewable is not None: caption += f"Görünen mesajlar: <code>{messages_viewable}</code>\n" if messages_sent: caption += f"Gönderilen mesajlar: <code>{messages_sent}</code>\n" elif messages_sent_alt: caption += f"Gönderilen mesajlar: <code>{messages_sent_alt}</code> {warn_emoji}\n"
async def grenzschutz( event: Union[ChatAction.Event, NewMessage.Event] ) -> None: # pylint: disable = R0911 """Automatically ban gbanned users. This plugin will ban gbanned users upon joining,getting added to the group or when writing a message. A message will be sent to notify Users of the action, this message will be deleted after 5 minutes. Tags: polizei: exclude: Don't ban gbanned users grenschutz: silent: Don't send the notification message exclude: Don't ban gbanned users """ if event.is_private: return if isinstance(event, ChatAction.Event): if event.user_left or event.user_kicked: return if event.action_message is None: return elif not isinstance( event.action_message.action, (MessageActionChatJoinedByLink, MessageActionChatAddUser)): return client: Client = event.client try: chat: Channel = await event.get_chat() except ChannelPrivateError: return if not chat.creator and not chat.admin_rights: return if chat.admin_rights and not chat.admin_rights.ban_users: return db: Database = client.db tags = await Tags.from_event(event) polizei_tag = tags.get('polizei') grenzschutz_tag = tags.get('grenzschutz', 'silent') silent = grenzschutz_tag == 'silent' if grenzschutz_tag == 'exclude' or polizei_tag == 'exclude': return if isinstance(event, ChatAction.Event): uid = event.user_id elif isinstance(event, NewMessage.Event): uid = event.message.sender_id else: return if uid is None: return try: entity = await client.get_entity(uid) name = get_display_name(entity) except GET_ENTITY_ERRORS: name = uid return result = await db.banlist.get(uid) if not result: return else: ban_reason = result.reason admins = [ p.id for p in await client.get_participants( event.chat_id, filter=ChannelParticipantsAdmins()) ] if uid not in admins: try: await client.ban(chat, uid) except UserIdInvalidError as err: logger.error("Error occured while banning %s", err) return await event.delete() if not silent: message = KanTeXDocument( Section( Bold('EBGWatch Grenzschutz Ban'), KeyValueItem(Bold("User"), f'{Mention(name, uid)} [{Code(uid)}]'), KeyValueItem(Bold("Reason"), ban_reason))) delete_time = '1m30s' if 'kriminalamt' not in ban_reason.lower( ) else '10s' await client.respond(event, str(message), reply=False, delete=delete_time)
async def fetch_info(chat, event): # chat.chats is a list so we use get_entity() to avoid IndexError chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = (chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False) chat_type = "Channel" if broadcast else "Group" chat_title = chat_obj_info.title warn_emoji = emojize(":warning:") try: msg_info = await event.client( GetHistoryRequest( peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0, )) except Exception as e: msg_info = None print("Exception:", e) # No chance for IndexError as it checks for msg_info.messages first first_msg_valid = bool(msg_info and msg_info.messages and msg_info.messages[0].id == 1) # Same for msg_info.users creator_valid = bool(first_msg_valid and msg_info.users) creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = (msg_info.users[0].first_name if creator_valid and msg_info.users[0].first_name is not None else "Deleted Account") creator_username = (msg_info.users[0].username if creator_valid and msg_info.users[0].username is not None else None) created = msg_info.messages[0].date if first_msg_valid else None former_title = ( msg_info.messages[0].action.title if first_msg_valid and isinstance( msg_info.messages[0].action, MessageActionChannelMigrateFrom) and msg_info.messages[0].action.title != chat_title else None) try: dc_id, location = get_input_location(chat.full_chat.chat_photo) except Exception as e: dc_id = "Unknown" str(e) # this is some spaghetti I need to change description = chat.full_chat.about members = (chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count) admins = (chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None) banned_users = (chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None) restrcited_users = (chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None) members_online = (chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0) group_stickers = (chat.full_chat.stickerset.title if hasattr(chat.full_chat, "stickerset") and chat.full_chat.stickerset else None) messages_viewable = msg_info.count if msg_info else None messages_sent = (chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None) messages_sent_alt = (chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None) exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = ("<b>Yes</b>" if hasattr(chat_obj_info, "megagroup") and chat_obj_info.megagroup else "No") slowmode = ("<b>Yes</b>" if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else "No") slowmode_time = (chat.full_chat.slowmode_seconds if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None) restricted = ("<b>Yes</b>" if hasattr(chat_obj_info, "restricted") and chat_obj_info.restricted else "No") verified = ("<b>Yes</b>" if hasattr(chat_obj_info, "verified") and chat_obj_info.verified else "No") username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None # end of spaghetti block if admins is None: # use this alternative way if chat.full_chat.admins_count is None, # works even without being an admin try: participants_admins = await event.client( GetParticipantsRequest( channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0, )) admins = participants_admins.count if participants_admins else None except Exception as e: print("Exception:", e) if bots_list: for _ in bots_list: bots += 1 caption = "<b> معـلومات المحـادثة:</b>\n" caption += f"ايدي المجمـوعة : <code>{chat_obj_info.id}</code>\n" if chat_title is not None: caption += f"{chat_type} name: {chat_title}\n" if former_title is not None: # Meant is the very first title caption += f"Former name: {former_title}\n" if username is not None: caption += f"{chat_type} نـوع المجـموعة : Public\n" caption += f"رابـط المجـموعة : {username}\n" else: caption += f"{chat_type} نـوع المجـموعة: Private\n" if creator_username is not None: caption += f"تـاريخ الأنشاء : {creator_username}\n" elif creator_valid: caption += ( f'المنـشـئ : <a href="tg://user?id={creator_id}">{creator_firstname}</a>\n' ) if created is not None: caption += f"الـتاريـخ : <code>{created.date().strftime('%b %d, %Y')} - {created.time()}</code>\n" else: caption += f"الـتاريخ: <code>{chat_obj_info.date.date().strftime('%b %d, %Y')} - {chat_obj_info.date.time()}</code> {warn_emoji}\n" caption += f"Data Centre ID: {dc_id}\n" if exp_count is not None: chat_level = int((1 + sqrt(1 + 7 * exp_count / 14)) / 2) caption += f"{chat_type} level: <code>{chat_level}</code>\n" if messages_viewable is not None: caption += f"الرسائل القابلة للعرض : <code>{messages_viewable}</code>\n" if messages_sent: caption += f"تم إرسال الرسائل : <code>{messages_sent}</code>\n" elif messages_sent_alt: caption += f"تم إرسال الرسائل : <code>{messages_sent_alt}</code> {warn_emoji}\n" if members is not None: caption += f"الاعـضاء : <code>{members}</code>\n" if admins is not None: caption += f"المسؤولين : <code>{admins}</code>\n" if bots_list: caption += f"البوتات : <code>{bots}</code>\n" if members_online: caption += f"الشغالين حاليا : <code>{members_online}</code>\n" if restrcited_users is not None: caption += f"المقيدون : <code>{restrcited_users}</code>\n" if banned_users is not None: caption += f"المحظوريـن : <code>{banned_users}</code>\n" if group_stickers is not None: caption += f'{chat_type} المـلصقات : <a href="t.me/addstickers/{chat.full_chat.stickerset.short_name}">{group_stickers}</a>\n' caption += "\n" if not broadcast: caption += f"الـوضع البـطئ : {slowmode}" if (hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled): caption += f", <code>{slowmode_time}s</code>\n\n" else: caption += "\n\n" caption += f"المجـموعات الـخارقة : {supergroup}\n\n" if hasattr(chat_obj_info, "restricted"): caption += f"الاسـباب : {restricted}\n" if chat_obj_info.restricted: caption += f"> البـرنامج : {chat_obj_info.restriction_reason[0].platform}\n" caption += f"> السـبب : {chat_obj_info.restriction_reason[0].reason}\n" caption += f"> الكـتابة : {chat_obj_info.restriction_reason[0].text}\n\n" else: caption += "\n" if hasattr(chat_obj_info, "scam") and chat_obj_info.scam: caption += "Scam: <b>Yes</b>\n\n" if hasattr(chat_obj_info, "verified"): caption += f"الـتوثيق : {verified}\n\n" if description: caption += f"وصـف المجموعـة : \n<code>{description}</code>\n" return caption
async def fetch_info(chat, event): chat_obj_info = await event.client.get_entity(chat.full_chat.id) chat_title = chat_obj_info.title try: msg_info = await event.client( GetHistoryRequest(peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0)) except Exception: msg_info = None await event.edit("<b>Произошла непредвиденная ошибка.</b>") first_msg_valid = True if msg_info and msg_info.messages and msg_info.messages[ 0].id == 1 else False creator_valid = True if first_msg_valid and msg_info.users else False creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = msg_info.users[ 0].first_name if creator_valid and msg_info.users[ 0].first_name is not None else "Удалённый аккаунт" creator_username = msg_info.users[ 0].username if creator_valid and msg_info.users[ 0].username is not None else None created = msg_info.messages[0].date if first_msg_valid else None former_title = msg_info.messages[ 0].action.title if first_msg_valid and type( msg_info.messages[0].action ) is MessageActionChannelMigrateFrom and msg_info.messages[ 0].action.title != chat_title else None description = chat.full_chat.about members = chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count admins = chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None banned_users = chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None restrcited_users = chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None users_online = 0 async for i in event.client.iter_participants(event.chat_id): if isinstance(i.status, UserStatusOnline): users_online = users_online + 1 group_stickers = chat.full_chat.stickerset.title if hasattr( chat.full_chat, "stickerset") and chat.full_chat.stickerset else None messages_viewable = msg_info.count if msg_info else None messages_sent = chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None messages_sent_alt = chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info bots = 0 slowmode = "Да" if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else "Нет" slowmode_time = chat.full_chat.slowmode_seconds if hasattr( chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None restricted = "Да" if hasattr( chat_obj_info, "restricted") and chat_obj_info.restricted else "Нет" verified = "Да" if hasattr( chat_obj_info, "verified") and chat_obj_info.verified else "Нет" username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None if admins is None: try: participants_admins = await event.client( GetParticipantsRequest(channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0)) admins = participants_admins.count if participants_admins else None except Exception: await event.edit("<b>Произошла непредвиденная ошибка.</b>") if bots_list: for bot in bots_list: bots += 1 caption = "<b>ИНФОРМАЦИЯ О ЧАТЕ:</b>\n\n" caption += f"<b>ID:</b> {chat_obj_info.id}\n" if chat_title is not None: caption += f"<b>Название группы:</b> {chat_title}\n" if former_title is not None: caption += f"<b>Предыдущее название:</b> {former_title}\n" if username is not None: caption += f"<b>Тип группы:</b> Публичный\n" caption += f"<b>Линк:</b> {username}\n" else: caption += f"<b>Тип группы:</b> Приватный\n" if creator_username is not None: caption += f"<b>Создатель:</b> <code>{creator_username}</code>\n" elif creator_valid: caption += f"<b>Создатель:</b> <code><a href=\"tg://user?id={creator_id}\">{creator_firstname}</a></code>\n" if created is not None: caption += f"<b>Создан:</b> {created.date().strftime('%b %d, %Y')} - {created.time()}\n" else: caption += f"<b>Создан:</b> {chat_obj_info.date.date().strftime('%b %d, %Y')} - {chat_obj_info.date.time()}\n" if messages_viewable is not None: caption += f"<b>Видимые сообщения:</b> {messages_viewable}\n" if messages_sent: caption += f"<b>Всего сообщений:</b> {messages_sent}\n" elif messages_sent_alt: caption += f"<b>Всего сообщений:</b> {messages_sent_alt}\n" if members is not None: caption += f"<b>Участников:</b> {members}\n" if admins is not None: caption += f"<b>Админов:</b> {admins}\n" if bots_list: caption += f"<b>Ботов:</b> {bots}\n" if users_online: caption += f"<b>Сейчас онлайн:</b> {users_online}\n" if restrcited_users is not None: caption += f"<b>Ограниченных пользователей:</b> {restrcited_users}\n" if banned_users is not None: caption += f"<b>Забаненных пользователей:</b> {banned_users}\n" if group_stickers is not None: caption += f"<b>Стикеры группы:</b> <a href=\"t.me/addstickers/{chat.full_chat.stickerset.short_name}\">{group_stickers}</a>\n" caption += "\n" caption += f"<b>Слоумод:</b> {slowmode}" if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled: caption += f", {slowmode_time} секунд\n" else: caption += "\n" caption += f"<b>Ограничен:</b> {restricted}\n" if chat_obj_info.restricted: caption += f"> Платформа: {chat_obj_info.restriction_reason[0].platform}\n" caption += f"> Причина: {chat_obj_info.restriction_reason[0].reason}\n" caption += f"> Текст: {chat_obj_info.restriction_reason[0].text}\n\n" else: caption += "" if hasattr(chat_obj_info, "scam") and chat_obj_info.scam: caption += "<b>Скам</b>: да\n\n" if hasattr(chat_obj_info, "verified"): caption += f"<b>Верифицирован:</b> {verified}\n\n" if description: caption += f"<b>Описание:</b> \n\n<code>{description}</code>\n" return caption
async def fetch_info(chat, event): # chat.chats is a list so we use get_entity() to avoid IndexError chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = (chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False) chat_type = "Channel" if broadcast else "Group" chat_title = chat_obj_info.title warn_emoji = "⚠️" try: msg_info = await event.client( GetHistoryRequest( peer=chat_obj_info.id, offset_id=0, offset_date=datetime(2010, 1, 1), add_offset=-1, limit=1, max_id=0, min_id=0, hash=0, )) except Exception as e: msg_info = None print("Exception:", e) # No chance for IndexError as it checks for msg_info.messages first first_msg_valid = (True if msg_info and msg_info.messages and msg_info.messages[0].id == 1 else False) # Same for msg_info.users creator_valid = True if first_msg_valid and msg_info.users else False creator_id = msg_info.users[0].id if creator_valid else None creator_firstname = (msg_info.users[0].first_name if creator_valid and msg_info.users[0].first_name is not None else "Deleted Account") creator_username = (msg_info.users[0].username if creator_valid and msg_info.users[0].username is not None else None) created = msg_info.messages[0].date if first_msg_valid else None former_title = ( msg_info.messages[0].action.title if first_msg_valid and type(msg_info.messages[0].action) is MessageActionChannelMigrateFrom and msg_info.messages[0].action.title != chat_title else None) try: dc_id, location = get_input_location(chat.full_chat.chat_photo) except Exception as e: dc_id = "Unknown" str(e) # this is some spaghetti I need to change description = chat.full_chat.about members = (chat.full_chat.participants_count if hasattr( chat.full_chat, "participants_count") else chat_obj_info.participants_count) admins = (chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None) banned_users = (chat.full_chat.kicked_count if hasattr( chat.full_chat, "kicked_count") else None) restrcited_users = (chat.full_chat.banned_count if hasattr( chat.full_chat, "banned_count") else None) members_online = (chat.full_chat.online_count if hasattr( chat.full_chat, "online_count") else 0) group_stickers = (chat.full_chat.stickerset.title if hasattr(chat.full_chat, "stickerset") and chat.full_chat.stickerset else None) messages_viewable = msg_info.count if msg_info else None messages_sent = (chat.full_chat.read_inbox_max_id if hasattr( chat.full_chat, "read_inbox_max_id") else None) messages_sent_alt = (chat.full_chat.read_outbox_max_id if hasattr( chat.full_chat, "read_outbox_max_id") else None) exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = ("<b>Yes</b>" if hasattr(chat_obj_info, "megagroup") and chat_obj_info.megagroup else "No") slowmode = ("<b>Yes</b>" if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else "No") slowmode_time = (chat.full_chat.slowmode_seconds if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled else None) restricted = ("<b>Yes</b>" if hasattr(chat_obj_info, "restricted") and chat_obj_info.restricted else "No") verified = ("<b>Yes</b>" if hasattr(chat_obj_info, "verified") and chat_obj_info.verified else "No") username = "******".format(username) if username else None creator_username = "******".format( creator_username) if creator_username else None # end of spaghetti block if admins is None: # use this alternative way if chat.full_chat.admins_count is None, works even without being an admin try: participants_admins = await event.client( GetParticipantsRequest( channel=chat.full_chat.id, filter=ChannelParticipantsAdmins(), offset=0, limit=0, hash=0, )) admins = participants_admins.count if participants_admins else None except Exception as e: print("Exception:", e) if bots_list: for bot in bots_list: bots += 1 caption = "<b>CHAT INFO:</b>\n" caption += f"ID: <code>{chat_obj_info.id}</code>\n" if chat_title is not None: caption += f"{chat_type} name: {chat_title}\n" if former_title is not None: # Meant is the very first title caption += f"Former name: {former_title}\n" if username is not None: caption += f"{chat_type} type: Public\n" caption += f"Link: {username}\n" else: caption += f"{chat_type} type: Private\n" if creator_username is not None: caption += f"Creator: {creator_username}\n" elif creator_valid: caption += ( f'Creator: <a href="tg://user?id={creator_id}">{creator_firstname}</a>\n' ) if created is not None: caption += f"Created: <code>{created.date().strftime('%b %d, %Y')} - {created.time()}</code>\n" else: caption += f"Created: <code>{chat_obj_info.date.date().strftime('%b %d, %Y')} - {chat_obj_info.date.time()}</code> {warn_emoji}\n" caption += f"Data Centre ID: {dc_id}\n" if exp_count is not None: chat_level = int((1 + sqrt(1 + 7 * exp_count / 14)) / 2) caption += f"{chat_type} level: <code>{chat_level}</code>\n" if messages_viewable is not None: caption += f"Viewable messages: <code>{messages_viewable}</code>\n" if messages_sent: caption += f"Messages sent: <code>{messages_sent}</code>\n" elif messages_sent_alt: caption += f"Messages sent: <code>{messages_sent_alt}</code> {warn_emoji}\n" if members is not None: caption += f"Members: <code>{members}</code>\n" if admins is not None: caption += f"Administrators: <code>{admins}</code>\n" if bots_list: caption += f"Bots: <code>{bots}</code>\n" if members_online: caption += f"Currently online: <code>{members_online}</code>\n" if restrcited_users is not None: caption += f"Restricted users: <code>{restrcited_users}</code>\n" if banned_users is not None: caption += f"Banned users: <code>{banned_users}</code>\n" if group_stickers is not None: caption += f'{chat_type} stickers: <a href="t.me/addstickers/{chat.full_chat.stickerset.short_name}">{group_stickers}</a>\n' caption += "\n" if not broadcast: caption += f"Slow mode: {slowmode}" if (hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled): caption += f", <code>{slowmode_time}s</code>\n\n" else: caption += "\n\n" if not broadcast: caption += f"Supergroup: {supergroup}\n\n" if hasattr(chat_obj_info, "restricted"): caption += f"Restricted: {restricted}\n" if chat_obj_info.restricted: caption += f"> Platform: {chat_obj_info.restriction_reason[0].platform}\n" caption += f"> Reason: {chat_obj_info.restriction_reason[0].reason}\n" caption += f"> Text: {chat_obj_info.restriction_reason[0].text}\n\n" else: caption += "\n" if hasattr(chat_obj_info, "scam") and chat_obj_info.scam: caption += "Scam: <b>Yes</b>\n\n" if hasattr(chat_obj_info, "verified"): caption += f"Verified by Telegram: {verified}\n\n" if description: caption += f"Description: \n<code>{description}</code>\n" return caption
async def get_admins(chat_id: int, only_ids=False) -> tuple: admins = await bot.get_participants(chat_id, filter=ChannelParticipantsAdmins()) if only_ids: admins = tuple(map(lambda admin: admin.id, admins)) return admins