async def join(client: TelegramClient, link: str): username, is_hash = parse_username(link) if is_hash: await client(ImportChatInviteRequest(username)) else: entity = await client.get_entity(username) await client(JoinChannelRequest(entity))
async def get_channel_info_by_url(self, url): logging.info('{}: Getting channel info with url: {}'.format( sys._getframe().f_code.co_name, url)) channel_hash = utils.parse_username(url)[0] # ----------------------------------------- # Test if we can get entity by channel hash # ----------------------------------------- try: channel = await self.client.get_entity(channel_hash) except ValueError: logging.info('{}: Not a valid telegram URL: {}'.format( sys._getframe().f_code.co_name, url)) return False except FloodWaitError as e: logging.info('{}: Got a flood wait error for: {}'.format( sys._getframe().f_code.co_name, url)) await asyncio.sleep(e.seconds * 2) return { 'channel_id': channel.id, 'channel_title': channel.title, 'is_broadcast': channel.broadcast, 'is_mega_group': channel.megagroup, 'channel_access_hash': channel.access_hash, }
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)
client = TelegramClient(session_name, api_id, api_hash, update_workers=4, spawn_read_thread=False) client.connect() client.start(phone) forward_ids = [] download_ids = [] for channel_ids, section in ((forward_ids, 'forwarder'), (download_ids, 'downloader')): for username in config.get(section, 'channels', fallback='').split(','): if username: channel, is_private = utils.parse_username(username) if is_private: try: invite = client(CheckChatInviteRequest(channel)) if isinstance(invite, ChatInviteAlready): channel_ids.append(invite.chat.id) elif isinstance(invite, ChatInvite): updates = client(ImportChatInviteRequest(channel)) channel_ids.append(updates.chats[0].id) except InviteHashInvalidError: txt = 'Invite link "{}" is not valid.' logging.warning(txt.format(username.strip()))
async def _get_entity_from_string(self: 'TelegramClient', string): """ Gets a full entity from the given string, which may be a phone or a username, and processes all the found entities on the session. The string may also be a user link, or a channel/chat invite link. This method has the side effect of adding the found users to the session database, so it can be queried later without API calls, if this option is enabled on the session. Returns the found entity, or raises TypeError if not found. """ phone = utils.parse_phone(string) if phone: try: for user in (await self(functions.contacts.GetContactsRequest(0) )).users: if user.phone == phone: return user except errors.BotMethodInvalidError: raise ValueError('Cannot get entity by phone number as a ' 'bot (try using integer IDs, not strings)') elif string.lower() in ('me', 'self'): return await self.get_me() else: username, is_join_chat = utils.parse_username(string) if is_join_chat: invite = await self( functions.messages.CheckChatInviteRequest(username)) if isinstance(invite, types.ChatInvite): raise ValueError( 'Cannot get entity from a channel (or group) ' 'that you are not part of. Join the group and retry') elif isinstance(invite, types.ChatInviteAlready): return invite.chat elif username: try: result = await self( functions.contacts.ResolveUsernameRequest(username)) except errors.UsernameNotOccupiedError as e: raise ValueError( 'No user has "{}" as username'.format(username)) from e try: pid = utils.get_peer_id(result.peer, add_mark=False) if isinstance(result.peer, types.PeerUser): return next(x for x in result.users if x.id == pid) else: return next(x for x in result.chats if x.id == pid) except StopIteration: pass try: # Nobody with this username, maybe it's an exact name/title return await self.get_entity( await self.session.get_input_entity(string)) except ValueError: pass raise ValueError( 'Cannot find any entity corresponding to "{}"'.format(string))