Python telethon.tl.types.User() Examples
The following are 19
code examples of telethon.tl.types.User().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
telethon.tl.types
, or try the search function
.
Example #1
Source File: utils.py From friendly-telegram with GNU Affero General Public License v3.0 | 6 votes |
def get_target(message, arg_no=0): if any(isinstance(ent, MessageEntityMentionName) for ent in (message.entities or [])): e = sorted(filter(lambda x: isinstance(x, MessageEntityMentionName), message.entities), key=lambda x: x.offset)[0] return e.user_id elif len(get_args(message)) > arg_no: user = get_args(message)[arg_no] elif message.is_reply: return (await message.get_reply_message()).from_id elif hasattr(message.to_id, "user_id"): user = message.to_id.user_id else: return None try: ent = await message.client.get_entity(user) except ValueError: return None else: if isinstance(ent, User): return ent.id
Example #2
Source File: auth.py From mautrix-telegram with GNU Affero General Public License v3.0 | 6 votes |
def _finish_sign_in(evt: CommandEvent, user: User, login_as: 'u.User' = None) -> EventID: login_as = login_as or evt.sender existing_user = u.User.get_by_tgid(TelegramID(user.id)) if existing_user and existing_user != login_as: await existing_user.log_out() await evt.reply(f"[{existing_user.displayname}]" f"(https://matrix.to/#/{existing_user.mxid})" " was logged out from the account.") asyncio.ensure_future(login_as.post_login(user, first_login=True), loop=evt.loop) evt.sender.command_status = None name = f"@{user.username}" if user.username else f"+{user.phone}" if login_as != evt.sender: msg = (f"Successfully logged in [{login_as.mxid}](https://matrix.to/#/{login_as.mxid})" f" as {name}") else: msg = f"Successfully logged in as {name}" return await evt.reply(msg)
Example #3
Source File: auth.py From mautrix-telegram with GNU Affero General Public License v3.0 | 6 votes |
def _sign_in(evt: CommandEvent, login_as: 'u.User' = None, **sign_in_info) -> EventID: login_as = login_as or evt.sender try: await login_as.ensure_started(even_if_no_session=True) user = await login_as.client.sign_in(**sign_in_info) await _finish_sign_in(evt, user) except PhoneCodeExpiredError: return await evt.reply("Phone code expired. Try again with `$cmdprefix+sp login`.") except PhoneCodeInvalidError: return await evt.reply("Invalid phone code.") except PasswordHashInvalidError: return await evt.reply("Incorrect password.") except SessionPasswordNeededError: evt.sender.command_status = { "next": enter_password, "action": "Login (password entry)", } return await evt.reply("Your account has two-factor authentication. " "Please send your password here.")
Example #4
Source File: chat.py From xiaomi_uranus_chatbot with GNU General Public License v3.0 | 6 votes |
def get_user_info(event) -> dict: """Returns a dictionary of user information""" chat_type = "user" if event.is_private else "group" if event.is_group else "channel" chat = await event.get_chat() if isinstance(chat, User): sender = await event.get_sender() name = '' if sender.first_name: name += sender.first_name.strip() if sender.last_name: name += ' ' + sender.last_name.strip() username = sender.username if sender.username else None chat_id = sender.id else: name = chat.title try: username = chat.username if chat.username else None except AttributeError: username = None chat_id = chat.id return {'id': chat_id, 'username': username, 'name': name, 'type': chat_type}
Example #5
Source File: pmpermit.py From TG-UserBot with GNU General Public License v3.0 | 6 votes |
def get_users(event: NewMessage.Event) -> types.User or None: match = event.matches[0].group(1) users = [] if match: matches, _ = await client.parse_arguments(match) for match in matches: try: entity = await client.get_entity(match) if isinstance(entity, types.User): users.append(entity) except (TypeError, ValueError): pass elif event.is_private and event.out: users = [await event.get_chat()] elif event.reply_to_msg_id: reply = await event.get_reply_message() users = [await reply.get_sender()] return users
Example #6
Source File: tests.py From telegram-export with Mozilla Public License 2.0 | 5 votes |
def login_client(client, username): """ Logs-in the given client and sets the desired username. This method will sign up, sign in, or delete existing 2FA-protected accounts as required. """ client.session.set_dc(0, '149.154.167.40', 80) assert client.connect() phone = '+999662' + str(random.randint(0, 9999)).zfill(4) client.send_code_request(phone) while True: try: print('Signing up as', phone) client.sign_up('22222', username, 'User') break except PhoneNumberOccupiedError: try: print('Signing in as', phone) client.sign_in(phone, '22222') break except SessionPasswordNeededError: print('Occupied', phone, 'had password! Deleting!') client(functions.account.DeleteAccountRequest('')) print('Changing', phone, 'username to', username) client(functions.account.UpdateUsernameRequest(username))
Example #7
Source File: auth.py From mautrix-telegram with GNU Affero General Public License v3.0 | 5 votes |
def login(evt: CommandEvent) -> EventID: override_sender = False if len(evt.args) > 0 and evt.sender.is_admin: evt.sender = await u.User.get_by_mxid(UserID(evt.args[0])).ensure_started() override_sender = True if await evt.sender.is_logged_in(): return await evt.reply(f"You are already logged in as {evt.sender.human_tg_id}.") allow_matrix_login = evt.config["bridge.allow_matrix_login"] if allow_matrix_login and not override_sender: evt.sender.command_status = { "next": enter_phone_or_token, "action": "Login", } nb = "**N.B. Logging in grants the bridge full access to your Telegram account.**" if evt.config["appservice.public.enabled"]: prefix = evt.config["appservice.public.external"] url = f"{prefix}/login?token={evt.public_website.make_token(evt.sender.mxid, '/login')}" if override_sender: return await evt.reply(f"[Click here to log in]({url}) as " f"[{evt.sender.mxid}](https://matrix.to/#/{evt.sender.mxid}).") elif allow_matrix_login: return await evt.reply(f"[Click here to log in]({url}). Alternatively, send your phone" f" number (or bot auth token) here to log in.\n\n{nb}") return await evt.reply(f"[Click here to log in]({url}).\n\n{nb}") elif allow_matrix_login: if override_sender: return await evt.reply( "This bridge instance does not allow you to log in outside of Matrix. " "Logging in as another user inside Matrix is not currently possible.") return await evt.reply("Please send your phone number (or bot auth token) here to start " f"the login process.\n\n{nb}") return await evt.reply("This bridge instance has been configured to not allow logging in.")
Example #8
Source File: ids.py From BotHub with Apache License 2.0 | 5 votes |
def get_entity_from_msg( event: NewMessage.Event ) -> Tuple[Union[None, types.User], Union[None, bool, str], Union[None, bool, str]]: """Get a User entity and/or a reason from the event's regex pattern""" exception = False entity = None match = event.matches[0].group(1) # TODO: Find better logic to differentiate user and reason pattern = re.compile(r"(@?\w+|\d+)(?: |$)(.*)") user = pattern.match(match).group(1) if match else None extra = pattern.match(match).group(2) if match else None reply = await event.get_reply_message() if reply and not (user and extra): user = reply.from_id extra = match.strip() user = int(user) if isinstance(user, str) and user.isdigit() else user if not user: return None, None, "Couldn't fetch an entity from your message!" try: entity = await event.client.get_entity(user) except Exception as e: exception = True LOGGER.exception(e) return entity, extra, exception
Example #9
Source File: helpers.py From BotHub with Apache License 2.0 | 5 votes |
def get_chat_link(arg: Union[types.User, types.Chat, types.Channel, NewMessage.Event], reply=None) -> str: if isinstance(arg, (types.User, types.Chat, types.Channel)): entity = arg else: entity = await arg.get_chat() if isinstance(entity, types.User): if entity.is_self: name = "your 'Saved Messages'" else: name = get_display_name(entity) or "Deleted Account?" extra = f"[{name}](tg://user?id={entity.id})" else: if hasattr(entity, 'username') and entity.username is not None: username = '@' + entity.username else: username = entity.id if reply is not None: if isinstance(username, str) and username.startswith('@'): username = username[1:] else: username = f"c/{username}" extra = f"[{entity.title}](https://t.me/{username}/{reply})" else: if isinstance(username, int): username = f"`{username}`" extra = f"{entity.title} ( {username} )" else: extra = f"[{entity.title}](tg://resolve?domain={username})" return extra
Example #10
Source File: helpers.py From BotHub with Apache License 2.0 | 5 votes |
def printUser(entity: types.User) -> None: """Print the user's first name + last name upon start""" user = get_display_name(entity) print() LOGGER.warning("Successfully logged in as {0}{2}{1}".format( CUSR, CEND, user))
Example #11
Source File: who.py From BotHub with Apache License 2.0 | 5 votes |
def get_who_string(who): who_string = html.escape(utils.get_display_name(who)) if isinstance(who, (types.User, types.Channel)) and who.username: who_string += f" is Party & Party's username <i>(@{who.username})</i>" who_string += f"& Party's ID <a href='tg://user?id={who.id}'> {who.id}</a>" return who_string
Example #12
Source File: ids.py From TG-UserBot with GNU General Public License v3.0 | 5 votes |
def get_entity_from_msg(event: NewMessage.Event) -> Tuple[ Union[None, types.User], Union[None, bool, str], Union[None, bool, str] ]: """Get a User entity and/or a reason from the event's regex pattern""" exception = False entity = None match = event.matches[0].group(1) # TODO: Find better logic to differentiate user and reason pattern = re.compile(r"(@?\w+|\d+)(?: |$)(.*)") user = pattern.match(match).group(1) if match else None extra = pattern.match(match).group(2) if match else None reply = await event.get_reply_message() if reply and not (user and extra): user = reply.from_id extra = match.strip() user = int(user) if isinstance(user, str) and user.isdigit() else user if not user: return None, None, "Couldn't fetch an entity from your message!" try: entity = await event.client.get_entity(user) except Exception as e: exception = True LOGGER.exception(e) return entity, extra, exception
Example #13
Source File: helpers.py From TG-UserBot with GNU General Public License v3.0 | 5 votes |
def get_chat_link( arg: Union[types.User, types.Chat, types.Channel, NewMessage.Event], reply=None ) -> str: if isinstance(arg, (types.User, types.Chat, types.Channel)): entity = arg else: entity = await arg.get_chat() if isinstance(entity, types.User): if entity.is_self: name = "yourself" else: name = get_display_name(entity) or "Deleted Account?" extra = f"[{name}](tg://user?id={entity.id})" else: if hasattr(entity, 'username') and entity.username is not None: username = '@' + entity.username else: username = entity.id if reply is not None: if isinstance(username, str) and username.startswith('@'): username = username[1:] else: username = f"c/{username}" extra = f"[{entity.title}](https://t.me/{username}/{reply})" else: if isinstance(username, int): username = f"`{username}`" extra = f"{entity.title} ( {username} )" else: extra = f"[{entity.title}](tg://resolve?domain={username})" return extra
Example #14
Source File: helpers.py From TG-UserBot with GNU General Public License v3.0 | 5 votes |
def printUser(entity: types.User) -> None: """Print the user's first name + last name upon start""" user = get_display_name(entity) print() LOGGER.warning("Successfully logged in as {0}".format(user))
Example #15
Source File: __init__.py From TG-UserBot with GNU General Public License v3.0 | 5 votes |
def verifyLoggerGroup(client: UserBotClient) -> None: client.logger = True def disable_logger(error: str): if LOGGER_CHAT_ID != 0: LOGGER.error(error) client.logger = False try: entity = client.loop.run_until_complete( client.get_entity(LOGGER_CHAT_ID) ) if not isinstance(entity, types.User): if not entity.creator: if entity.default_banned_rights.send_messages: disable_logger( "Permissions missing to send messages " "for the specified Logger group." ) client.logger = entity except ValueError: disable_logger( "Logger group ID cannot be found. " "Make sure it's correct." ) except TypeError: disable_logger( "Logger group ID is unsupported. " "Make sure it's correct." ) except Exception as e: disable_logger( "An Exception occured upon trying to verify " "the logger group.\n" + str(e) )
Example #16
Source File: downloader.py From telegram-export with Mozilla Public License 2.0 | 5 votes |
def enqueue_entities(self, entities): """ Enqueues the given iterable of entities to be dumped later by a different coroutine. These in turn might enqueue profile photos. """ for entity in entities: eid = utils.get_peer_id(entity) self._displays[eid] = utils.get_display_name(entity) if isinstance(entity, types.User): if entity.deleted or entity.min: continue # Empty name would cause IntegrityError elif isinstance(entity, types.Channel): if entity.left: continue # Getting full info triggers ChannelPrivateError elif not isinstance(entity, (types.Chat, types.InputPeerUser, types.InputPeerChat, types.InputPeerChannel)): # Drop UserEmpty, ChatEmpty, ChatForbidden and ChannelForbidden continue if eid in self._checked_entity_ids: continue else: self._checked_entity_ids.add(eid) if isinstance(entity, (types.User, types.InputPeerUser)): self._user_queue.put_nowait(entity) else: self._chat_queue.put_nowait(entity)
Example #17
Source File: blacklist.py From TG-UserBot with GNU General Public License v3.0 | 4 votes |
def unblacklistuser(event: NewMessage.Event) -> None: """ Unblacklist the blacklisted users. `{prefix}unblacklist` or **{prefix}unblacklist (users)** """ if not redis: await event.answer( "`You need to use a Redis session to use blacklists.`" ) return match = event.matches[0].group('match') or '' users = [] skipped = [] if match: args, _ = await client.parse_arguments(match) for user in args: if user in blacklistedUsers: users.append(user) continue try: entity = await client.get_entity(user) if isinstance(entity, types.User): if not entity.is_self: users.append(entity.id) else: skipped.append(f"`{user}`") except Exception: skipped.append(f"`{user}`") else: if event.reply_to_msg_id: entity = (await event.get_reply_message()).from_id users.append(entity) else: entity = await event.get_chat() if event.is_private: users.append(entity.id) if users and blacklistedUsers: text = "**Un-blacklisted users:**\n" targets = [] for user in users: if user in blacklistedUsers: blacklistedUsers.pop(user) targets.append(f"[{user}](tg://user?id={user})") if blacklistedUsers: redis.set('blacklist:users', dill.dumps(blacklistedUsers)) else: redis.delete('blacklist:users') text += ", ".join(targets) await event.answer(text, log=('unblacklist', text)) if skipped: text = "**Skipped users:**\n" text += ', '.join(skipped) await event.answer(text, reply=True)
Example #18
Source File: auth.py From mautrix-telegram with GNU Affero General Public License v3.0 | 4 votes |
def login_qr(evt: CommandEvent) -> EventID: login_as = evt.sender if len(evt.args) > 0 and evt.sender.is_admin: login_as = u.User.get_by_mxid(UserID(evt.args[0])) if not qrcode or not QRLogin: return await evt.reply("This bridge instance does not support logging in with a QR code.") if await login_as.is_logged_in(): return await evt.reply(f"You are already logged in as {login_as.human_tg_id}.") await login_as.ensure_started(even_if_no_session=True) qr_login = QRLogin(login_as.client, ignored_ids=[]) qr_event_id: Optional[EventID] = None async def upload_qr() -> None: nonlocal qr_event_id buffer = io.BytesIO() image = qrcode.make(qr_login.url) size = image.pixel_size image.save(buffer, "PNG") qr = buffer.getvalue() mxc = await evt.az.intent.upload_media(qr, "image/png", "login-qr.png", len(qr)) content = MediaMessageEventContent(body=qr_login.url, url=mxc, msgtype=MessageType.IMAGE, info=ImageInfo(mimetype="image/png", size=len(qr), width=size, height=size)) if qr_event_id: content.set_edit(qr_event_id) await evt.az.intent.send_message(evt.room_id, content) else: content.set_reply(evt.event_id) qr_event_id = await evt.az.intent.send_message(evt.room_id, content) retries = 4 while retries > 0: await qr_login.recreate() await upload_qr() try: user = await qr_login.wait() break except asyncio.TimeoutError: retries -= 1 except SessionPasswordNeededError: evt.sender.command_status = { "next": enter_password, "login_as": login_as if login_as != evt.sender else None, "action": "Login (password entry)", } return await evt.reply("Your account has two-factor authentication. " "Please send your password here.") else: timeout = TextMessageEventContent(body="Login timed out", msgtype=MessageType.TEXT) timeout.set_edit(qr_event_id) return await evt.az.intent.send_message(evt.room_id, timeout) return await _finish_sign_in(evt, user, login_as=login_as)
Example #19
Source File: downloader.py From telegram-export with Mozilla Public License 2.0 | 4 votes |
def _get_name(self, peer_id): if peer_id is None: return '' name = self._displays.get(peer_id) if name: return name c = self.dumper.conn.cursor() _, kind = utils.resolve_id(peer_id) if kind == types.PeerUser: row = c.execute('SELECT FirstName, LastName FROM User ' 'WHERE ID = ?', (peer_id,)).fetchone() if row: return '{} {}'.format(row[0] or '', row[1] or '').strip() elif kind == types.PeerChat: row = c.execute('SELECT Title FROM Chat ' 'WHERE ID = ?', (peer_id,)).fetchone() if row: return row[0] elif kind == types.PeerChannel: row = c.execute('SELECT Title FROM Channel ' 'WHERE ID = ?', (peer_id,)).fetchone() if row: return row[0] row = c.execute('SELECT Title FROM Supergroup ' 'WHERE ID = ?', (peer_id,)).fetchone() if row: return row[0] return ''