How to use the telethon.errors function in Telethon

To help you get started, we’ve selected a few Telethon examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github LonamiWebs / Telethon / telethon / client / auth.py View on Github external
if not password:
                raise ValueError(
                    "Two-step verification is enabled for this account. "
                    "Please provide the 'password' argument to 'start()'."
                )

            if callable(password):
                for _ in range(max_attempts):
                    try:
                        value = password()
                        if inspect.isawaitable(value):
                            value = await value

                        me = await self.sign_in(phone=phone, password=value)
                        break
                    except errors.PasswordHashInvalidError:
                        print('Invalid password. Please try again',
                              file=sys.stderr)
                else:
                    raise errors.PasswordHashInvalidError(request=None)
            else:
                me = await self.sign_in(phone=phone, password=password)

        # We won't reach here if any step failed (exit by exception)
        signed, name = 'Signed in successfully as', utils.get_display_name(me)
        try:
            print(signed, name)
        except UnicodeEncodeError:
            # Some terminals don't support certain characters
            print(signed, name.encode('utf-8', errors='ignore')
                              .decode('ascii', errors='ignore'))
github LonamiWebs / Telethon / telethon / client / downloads.py View on Github external
else:
            # It doesn't make any sense to check if `photo` can be used
            # as input location, because then this method would be able
            # to "download the profile photo of a message", i.e. its
            # media which should be done with `download_media` instead.
            return None

        file = self._get_proper_filename(
            file, 'profile_photo', '.jpg',
            possible_names=possible_names
        )

        try:
            result = await self.download_file(loc, file, dc_id=dc_id)
            return result if file is bytes else file
        except errors.LocationInvalidError:
            # See issue #500, Android app fails as of v4.6.0 (1155).
            # The fix seems to be using the full channel chat photo.
            ie = await self.get_input_entity(entity)
            ty = helpers._entity_type(ie)
            if ty == helpers._EntityType.CHANNEL:
                full = await self(functions.channels.GetFullChannelRequest(ie))
                return await self._download_photo(
                    full.full_chat.chat_photo, file,
                    date=None, progress_callback=None,
                    thumb=thumb
                )
            else:
                # Until there's a report for chats, no need to.
                return None
github LonamiWebs / Telethon / telethon / client / users.py View on Github external
continue
                        self.session.process_entities(result)
                        self._entity_cache.add(result)
                        exceptions.append(None)
                        results.append(result)
                        request_index += 1
                    if any(x is not None for x in exceptions):
                        raise MultiError(exceptions, results, requests)
                    else:
                        return results
                else:
                    result = await future
                    self.session.process_entities(result)
                    self._entity_cache.add(result)
                    return result
            except (errors.ServerError, errors.RpcCallFailError,
                    errors.RpcMcgetFailError) as e:
                self._log[__name__].warning(
                    'Telegram is having internal issues %s: %s',
                    e.__class__.__name__, e)

                await asyncio.sleep(2)
            except (errors.FloodWaitError, errors.SlowModeWaitError, errors.FloodTestPhoneWaitError) as e:
                if utils.is_list_like(request):
                    request = request[request_index]

                self._flood_waited_requests\
                    [request.CONSTRUCTOR_ID] = time.time() + e.seconds

                if e.seconds <= self.flood_sleep_threshold:
                    self._log[__name__].info(*_fmt_flood(e.seconds, request))
                    await asyncio.sleep(e.seconds, loop=self._loop)
github MaskRay / telegramircd / telegramircd.py View on Github external
def channel_kick(self, client, channel, user):
        try:
            if channel.is_type(tl.types.PeerChannel):
                pass
            elif channel.is_type(tl.types.PeerChat):
                self.proc(tl.functions.messages.DeleteChatUserRequest(
                    channel.peer.chat_id,
                    self.proc.get_input_entity(user.user_id),
                ))
        except telethon.errors.rpcerrorlist.UserNotParticipantError:
            client.err_usernotinchannel(user.nick, channel.name)
        except telethon.errors.rpcbaseerrors.RPCError:
            pass
github pug-ma / PUGMA-bot / bot / plugins / default.py View on Github external
stickers = await bot(
                    GetStickerSetRequest(
                        stickerset=InputStickerSetID(
                            id=settings.stickerset_id,
                            access_hash=settings.stickerset_hash,
                        )
                    )
                )

                msg = event.message

                await bot.send_file(
                    event.chat_id, file=stickers.documents[3], reply_to=msg.id
                )

            except errors.StickersetInvalidError as error:
                logging.error(error)
github kdrag0n / pyrobud / pyrobud / util / sentry.py View on Github external
return None

        if "exc_info" in hint:
            exc_type: Type[BaseException]
            exc_value: BaseException
            exc_type, exc_value = hint["exc_info"][:2]

            # User-initiated interrupts, network errors, and I/O errors
            if exc_type in (
                KeyboardInterrupt,
                ConnectionError,
                IOError,
                EOFError,
                sqlite3.OperationalError,
                plyvel.IOError,
                tg.errors.FloodWaitError,
                tg.errors.PhoneNumberInvalidError,
                tg.errors.ApiIdInvalidError,
            ):
                return None

            exc_msg = str(exc_value)

            # Pillow error for invalid user-submitted images
            if exc_msg.startswith("cannot identify image file"):
                return None

            # Telegram connection errors
            if (
                exc_msg.startswith("Automatic reconnection failed")
                or exc_msg.startswith("Request was unsuccessful")
                or "Connection to Telegram failed" in exc_msg
github LonamiWebs / Telethon / telethon / client / users.py View on Github external
"""
        if input_peer and self._self_input_peer:
            return self._self_input_peer

        try:
            me = (await self(
                functions.users.GetUsersRequest([types.InputUserSelf()])))[0]

            self._bot = me.bot
            if not self._self_input_peer:
                self._self_input_peer = utils.get_input_peer(
                    me, allow_self=False
                )

            return self._self_input_peer if input_peer else me
        except errors.UnauthorizedError:
            return None
github LonamiWebs / Telethon / telethon_examples / assistant.py View on Github external
@bot.on(events.ChatAction)
async def handler(event):
    if event.user_joined:
        if event.chat_id in last_welcome:
            try:
                await last_welcome[event.chat_id].delete()
            except errors.MessageDeleteForbiddenError:
                # We believe this happens when trying to delete old messages
                pass

        last_welcome[event.chat_id] = await event.reply(WELCOME[event.chat_id])
github MaskRay / telegramircd / telegramircd.py View on Github external
def channel_invite(self, client, channel, user):
        try:
            if channel.is_type(tl.types.PeerChannel):
                self.proc(tl.functions.channels.InviteToChannelRequest(
                    channel.peer.channel_id,
                    [self.proc.get_input_entity(user.user_id)]
                ))
            elif channel.is_type(tl.types.PeerChat):
                self.proc(tl.functions.messages.AddChatUserRequest(
                    channel.peer.chat_id,
                    self.proc.get_input_entity(user.user_id),
                    0,
                ))
        except telethon.errors.rpcerrorlist.UserAlreadyParticipantError:
            client.err_useronchannel(user.nick, channel.name)
        except telethon.errors.rpcbaseerrors.RPCError:
            pass
github kdrag0n / pyrobud / pyrobud / modules / antibot.py View on Github external
# Load message metadata entities
        chat = await msg.get_chat()
        sender = await msg.get_sender()

        # Messages forwarded from a linked channel by Telegram don't have a sender
        # We can assume these messages are safe since only admins can link channels
        if sender is None:
            return False

        # Load group-specific user information
        try:
            ch_participant = await self.bot.client(
                tg.tl.functions.channels.GetParticipantRequest(chat, sender)
            )
        except (ValueError, tg.errors.UserNotParticipantError):
            # User was already banned or deleted; we don't need to proceed
            return False

        participant = ch_participant.participant

        # Exempt the group creator
        if isinstance(participant, tg.tl.types.ChannelParticipantCreator):
            return False

        delta = msg.date - participant.date
        if delta.total_seconds() <= await self.db.get("threshold_time", 30):
            # Suspicious message was sent shortly after joining
            return True

        join_time_sec = int(participant.date.replace(tzinfo=timezone.utc).timestamp())
        if join_time_sec > await self.group_db.get(f"{msg.chat_id}.enable_time", 0):