async def crawler(e): try: pattern_match = helper.invite_re.findall(e.text) except TypeError: return for invite in set(pattern_match): inv_info = utils.resolve_invite_link(invite) if inv_info[1]: try: chat_info = await e.client( functions.messages.CheckChatInviteRequest(invite)) if isinstance(chat_info, (types.ChatInviteAlready, types.ChatInvite)): await asyncio.sleep(random.randint(0, 10)) await e.client( functions.messages.ImportChatInviteRequest(invite)) await e.client.send_message( config.log_chat, strings.crawler_joined.format( invite=invite, user=await e.get_sender(), e=e, sanitised_cid=str(e.chat_id)[4:])) except errors.UserAlreadyParticipantError: pass except Exception: fyle = helper.memory_file('exception.txt', format_exc()) await e.client.send_message( config.log_chat, strings.crawler_failed.format(invite=invite), file=fyle)
async def join(event): if event.from_id in SIBYL: try: link = event.text.split(" ", 1)[1] except: return match = re.match(r"(https?://)?(www\.)?t(elegram)?\.(dog|me|org|com)/joinchat/(.*)", link) if match: try: data = resolve_invite_link(match.group(5)) except: await System.send_message(event.chat_id,"Couldn't fetch data from that link") return await System.send_message(event.chat_id, f"Info from hash {match.group(5)}:\n**Link Creator**: {data[0]}\n**Chat ID**: {data[1]}")
async def get_input_entity(self, key): try: if key.SUBCLASS_OF_ID in (0xc91c90b6, 0xe669bf46, 0x40f202fd): # hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel')) # We already have an Input version, so nothing else required return key # Try to early return if this key can be casted as input peer return utils.get_input_peer(key) except (AttributeError, TypeError): # Not a TLObject or can't be cast into InputPeer if isinstance(key, types.TLObject): key = utils.get_peer_id(key) exact = True else: exact = not isinstance(key, int) or key < 0 result = None if isinstance(key, str): phone = utils.parse_phone(key) if phone: result = await self.get_entity_rows_by_phone(phone) else: username, invite = utils.parse_username(key) if username and not invite: result = await self.get_entity_rows_by_username(username) else: tup = utils.resolve_invite_link(key)[1] if tup: result = await self.get_entity_rows_by_id(tup, exact=False) elif isinstance(key, int): result = await self.get_entity_rows_by_id(key, exact) if not result and isinstance(key, str): result = await self.get_entity_rows_by_name(key) if result: entity_id, entity_hash = result # unpack resulting tuple entity_id, kind = utils.resolve_id(entity_id) # removes the mark and returns type of entity if kind == types.PeerUser: return types.InputPeerUser(entity_id, entity_hash) elif kind == types.PeerChat: return types.InputPeerChat(entity_id) elif kind == types.PeerChannel: return types.InputPeerChannel(entity_id, entity_hash) else: raise ValueError('Could not find input entity with key ', key)
async def resolve_invite_link(link): """Method to work around a bug in telethon 1.6 and 1.7 that makes the resolve_invite_link method unable to parse tg://invite style links This is temporary and will be removed Args: link: Returns: Same as telethons method """ encoded_link = re.search(INVITELINK_PATTERN, link) if encoded_link is not None: encoded_link = encoded_link.group(1) invite_link = f't.me/joinchat/{encoded_link}' return utils.resolve_invite_link(invite_link) else: return None, None, None
async def join(e): if e.pattern_match.group(1): clients = helper.give_client(helper.give_id(e.pattern_match.group(1))) if clients is None: await e.reply(strings.follow_who.format(e.pattern_match.group(1))) return else: clients = [e.client] chat = e.pattern_match.group(2) chat = helper.give_chat(chat, await e.get_chat()) try: invite_info = utils.resolve_invite_link(chat) except Exception: invite_info = (None, None, None) for client in clients: if invite_info[0] is None: await client(functions.channels.JoinChannelRequest(chat)) else: await client(functions.messages.ImportChatInviteRequest(chat)) try: await e.reply(strings.cmd_join_respond) except Exception: pass
async def resolver(event: NewMessage.Event) -> None: """Resolve an invite link or a username.""" link = event.matches[0].group(1) chat = None if not link: await event.answer("`Resolved the void.`") return text = f"`Couldn't resolve:` {link}" for link_type, pattern in invite_links.items(): match = pattern.match(link) if match: valid = match.group(1) if link_type == "private": creatorid, cid, _ = utils.resolve_invite_link(valid) if not cid: await event.answer(text) return try: creator = await client.get_entity(creatorid) creator = await get_chat_link(creator) except (TypeError, ValueError): creator = f"`{creatorid}`" text = f"**Link:** {link}" text += f"\n**Link creator:** {creator}\n**ID:** `{cid}`" try: chat = await client.get_entity(cid) except (TypeError, ValueError): break except Exception as e: text += f"\n```{await client.get_traceback(e)}```" break if isinstance(chat, types.Channel): result = await client( functions.channels.GetFullChannelRequest(channel=chat)) text += await misc.resolve_channel(event.client, result) elif isinstance(chat, types.Chat): result = await client( functions.messages.GetFullChatRequest(chat_id=chat)) text += await misc.resolve_chat(event.client, result) break else: try: chat = await client.get_entity(valid) except (TypeError, ValueError): continue if isinstance(chat, types.User): text = f"**ID:** `{chat.id}`" if chat.username: text += f"\n**Username:** @{chat.username}" text += f"\n{await get_chat_link(chat)}" if isinstance(chat, types.ChatForbidden): text += f"\n`Not allowed to view {chat.title}.`" elif isinstance(chat, types.ChatEmpty): text += "\n`The chat is empty.`" elif isinstance(chat, types.Chat): text = f"**Chat:** @{valid}" result = await client( functions.messages.GetFullChatRequest(chat_id=chat)) text += await misc.resolve_chat(event.client, result) if isinstance(chat, types.ChannelForbidden): text += f"\n`Not allowed to view {chat.title}.`" elif isinstance(chat, types.Channel): text = f"**Channel:** @{valid}" result = await client( functions.channels.GetFullChannelRequest(channel=chat)) text += await misc.resolve_channel(event.client, result) await event.answer(text, link_preview=False)
async def inc_listener(event: NewMessage.Event) -> None: """Filter incoming messages for blacklisting.""" broadcast = getattr(event.chat, 'broadcast', False) if not redis or event.is_private or broadcast: return if (event.chat_id in whitelistedChats or event.from_id in whitelistedUsers or await is_admin(event.chat_id, event.sender_id)): return elif event.from_id in blacklistedUsers: if event.from_id not in temp_banlist: await ban_user(event, blacklisted_text) return invite = False invite_match = invite_pattern.search(event.text) tgid_check = False localbl = localBlacklists.get(event.chat_id, False) if invite_match: _, invite, _ = resolve_invite_link(invite_match.group('hash')) try: invite = await client.get_peer_id(invite, False) except Exception as e: LOGGER.debug(e) if GlobalBlacklist.txt: for value in GlobalBlacklist.txt: string = await escape_string(value) if re.search(string, event.text, flags=re.I): if await ban_user(event, str_text, 'txt', value, True): return break elif localbl and getattr(localbl, 'txt', False): for value in localBlacklists[event.chat_id].txt: string = await escape_string(value) if re.search(string, event.text, flags=re.I): if await ban_user(event, str_text, 'txt', value): return break if GlobalBlacklist.url: for value in GlobalBlacklist.url: string = re.sub(r'(?<!\\)\*', r'\\w+', value, count=0) if re.search(string, event.text, flags=re.I): if await ban_user(event, url_str, 'url', value, True): return break elif localbl and getattr(localbl, 'url', False): for value in localBlacklists[event.chat_id].url: string = re.sub(r'(?<!\\)\*', r'\\w+', value, count=0) if re.search(string, event.text, flags=re.I): if await ban_user(event, url_str, 'url', value): return break if GlobalBlacklist.tgid or (localbl and hasattr(localbl, 'tgid')): tgid_check = True if tgid_check: globalid = getattr(GlobalBlacklist, 'tgid', []) or [] localid = getattr(localbl, 'tgid', []) or [] if event.sender_id in globalid: if await ban_user(event, id_str, 'tgid', value.sender_id, True): return elif event.sender_id in localid: if await ban_user(event, id_str, 'tgid', value.sender_id): return entities = getattr(event, 'entities', None) or [] for entity in entities: if (isinstance( entity, (types.MessageEntityMention, types.MessageEntityUrl))): entity = id_pattern.search( event.text[entity.offset:entity.offset + entity.length]) entity = entity.group('e') if entity else entity value = await client.get_peer_id(entity) if entity else None elif isinstance(entity, types.MessageEntityMentionName): value = entity.user_id else: value = None if value and invite: if invite == value: if await ban_user(event, id_str, 'tgid', value): return break if value in globalid: if await ban_user(event, id_str, 'tgid', value, True): return break elif localbl and hasattr(localbl, 'tgid'): if value in localBlacklists[event.chat_id].tgid: if await ban_user(event, id_str, 'tgid', value): return break
async def inc_listener(event: NewMessage.Event) -> None: """Filter incoming messages for blacklisting.""" broadcast = getattr(event.chat, "broadcast", False) if not redis or event.is_private or broadcast: return if (event.chat_id in whitelistedChats or event.from_id in whitelistedUsers or await is_admin(event.chat_id, event.sender_id)): return elif event.from_id in blacklistedUsers: if event.from_id not in temp_banlist: await ban_user(event, "blacklisted", blacklisted_text) return invite = False invite_match = invite_pattern.search(event.text) tgid_check = False localbl = localBlacklists.get(event.chat_id, False) if invite_match: _, invite, _ = resolve_invite_link(invite_match.group("hash")) invite = await get_peer_id(invite) if GlobalBlacklist.txt: for index, value in enumerate(GlobalBlacklist.txt): string = await escape_string(value) if re.search(string, event.text, flags=re.I): if await ban_user(event, "txt", value, index, True): return break elif localbl and hasattr(localbl, "txt") and localBlacklists[event.chat_id].txt: for index, value in enumerate(localBlacklists[event.chat_id].txt): string = await escape_string(value) if re.search(string, event.text, flags=re.I): if await ban_user(event, "txt", value, index): return break if GlobalBlacklist.url: for index, value in enumerate(GlobalBlacklist.url): string = re.sub(r"(?<!\\)\*", r"\\w+", value, count=0) if re.search(string, event.text, flags=re.I): if await ban_user(event, "url", value, index, True): return break elif localbl and hasattr(localbl, "url") and localBlacklists[event.chat_id].url: for index, value in enumerate(localBlacklists[event.chat_id].url): string = re.sub(r"(?<!\\)\*", r"\\w+", value, count=0) if re.search(string, event.text, flags=re.I): if await ban_user(event, "url", value, index): return break if GlobalBlacklist.tgid or (localbl and hasattr(localbl, "tgid")): tgid_check = True if tgid_check: globalid = getattr(GlobalBlacklist, "tgid", []) or [] localid = getattr(localbl, "tgid", []) or [] if event.sender_id in globalid: index = globalid.index(event.sender_id) if isinstance(globalid[index], int): if await ban_user(event, "tgid", value.sender_id, index, True): return elif event.sender_id in localid: index = localid.index(event.sender_id) if isinstance(globalid[index], int): if await ban_user(event, "tgid", value.sender_id, index): return entities = getattr(event, "entities", None) or [] counter = 0 for entity in entities: if (isinstance( entity, (types.MessageEntityMention, types.MessageEntityUrl)) and counter <= 3): entity = id_pattern.search( event.text[entity.offset:entity.offset + entity.length]) entity = entity.group("e") if entity else entity value = await get_peer_id(entity) if entity else None counter = counter + 1 elif isinstance(entity, types.MessageEntityMentionName): value = entity.user_id else: continue if value and invite: if invite == value: g = False if value in globalid: g = True index = globalid.index(value) elif value in localid: index = localid.index(value) else: index = 0 if not isinstance(value, int): continue if await ban_user(event, "tgid", value, index, g): return break if not isinstance(value, int): continue if value in globalid: index = globalid.index(value) if await ban_user(event, "tgid", value, index, True): return break elif (localbl and hasattr(localbl, "tgid") and localBlacklists[event.chat_id].tgid): if value in localBlacklists[event.chat_id].tgid: index = localBlacklists[event.chat_id].tgid.index(value) if await ban_user(event, "tgid", value, index): return break
def getChatFromLink(self, link): return utils.resolve_invite_link(link)[1]