diff --git a/docs/docs_writer.py b/docs/docs_writer.py index f9042f00..9eec6cd7 100644 --- a/docs/docs_writer.py +++ b/docs/docs_writer.py @@ -90,7 +90,7 @@ class DocsWriter: def end_menu(self): """Ends an opened menu""" if not self.menu_began: - raise ValueError('No menu had been started in the first place.') + raise RuntimeError('No menu had been started in the first place.') self.write('') def write_title(self, title, level=1): diff --git a/telethon/errors/__init__.py b/telethon/errors/__init__.py index fbb2f424..9126aca3 100644 --- a/telethon/errors/__init__.py +++ b/telethon/errors/__init__.py @@ -7,9 +7,8 @@ import re from threading import Thread from .common import ( - ReadCancelledError, InvalidParameterError, TypeNotFoundError, - InvalidChecksumError, BrokenAuthKeyError, SecurityError, - CdnFileTamperedError + ReadCancelledError, TypeNotFoundError, InvalidChecksumError, + BrokenAuthKeyError, SecurityError, CdnFileTamperedError ) # This imports the base errors too, as they're imported there diff --git a/telethon/errors/common.py b/telethon/errors/common.py index f2f21840..46b0b52e 100644 --- a/telethon/errors/common.py +++ b/telethon/errors/common.py @@ -7,13 +7,6 @@ class ReadCancelledError(Exception): super().__init__(self, 'The read operation was cancelled.') -class InvalidParameterError(Exception): - """ - Occurs when an invalid parameter is given, for example, - when either A or B are required but none is given. - """ - - class TypeNotFoundError(Exception): """ Occurs when a type is not found, for example, diff --git a/telethon/extensions/binary_reader.py b/telethon/extensions/binary_reader.py index 19fb608b..460bed96 100644 --- a/telethon/extensions/binary_reader.py +++ b/telethon/extensions/binary_reader.py @@ -6,7 +6,7 @@ from datetime import datetime from io import BufferedReader, BytesIO from struct import unpack -from ..errors import InvalidParameterError, TypeNotFoundError +from ..errors import TypeNotFoundError from ..tl.all_tlobjects import tlobjects @@ -22,8 +22,7 @@ class BinaryReader: elif stream: self.stream = stream else: - raise InvalidParameterError( - 'Either bytes or a stream must be provided') + raise ValueError('Either bytes or a stream must be provided') self.reader = BufferedReader(self.stream) self._last = None # Should come in handy to spot -404 errors @@ -110,7 +109,7 @@ class BinaryReader: elif value == 0xbc799737: # boolFalse return False else: - raise ValueError('Invalid boolean code {}'.format(hex(value))) + raise RuntimeError('Invalid boolean code {}'.format(hex(value))) def tgread_date(self): """Reads and converts Unix time (used by Telegram) @@ -141,7 +140,7 @@ class BinaryReader: def tgread_vector(self): """Reads a vector (a list) of Telegram objects.""" if 0x1cb5c415 != self.read_int(signed=False): - raise ValueError('Invalid constructor code, vector was expected') + raise RuntimeError('Invalid constructor code, vector was expected') count = self.read_int() return [self.tgread_object() for _ in range(count)] diff --git a/telethon/extensions/tcp_client.py b/telethon/extensions/tcp_client.py index f59bb9f0..61be30f5 100644 --- a/telethon/extensions/tcp_client.py +++ b/telethon/extensions/tcp_client.py @@ -26,7 +26,7 @@ class TcpClient: elif isinstance(timeout, (int, float)): self.timeout = float(timeout) else: - raise ValueError('Invalid timeout type', type(timeout)) + raise TypeError('Invalid timeout type: {}'.format(type(timeout))) def _recreate_socket(self, mode): if self.proxy is None: diff --git a/telethon/telegram_bare_client.py b/telethon/telegram_bare_client.py index ff493f6c..036aafd2 100644 --- a/telethon/telegram_bare_client.py +++ b/telethon/telegram_bare_client.py @@ -85,7 +85,7 @@ class TelegramBareClient: **kwargs): """Refer to TelegramClient.__init__ for docs on this method""" if not api_id or not api_hash: - raise PermissionError( + raise ValueError( "Your API ID or Hash cannot be empty or None. " "Refer to Telethon's wiki for more information.") @@ -95,7 +95,7 @@ class TelegramBareClient: if isinstance(session, str) or session is None: session = Session(session) elif not isinstance(session, Session): - raise ValueError( + raise TypeError( 'The given session must be a str or a Session instance.' ) @@ -425,11 +425,11 @@ class TelegramBareClient: """Invokes (sends) a MTProtoRequest and returns (receives) its result. The invoke will be retried up to 'retries' times before raising - ValueError(). + RuntimeError(). """ if not all(isinstance(x, TLObject) and x.content_related for x in requests): - raise ValueError('You can only invoke requests, not types!') + raise TypeError('You can only invoke requests, not types!') # For logging purposes if len(requests) == 1: @@ -490,7 +490,7 @@ class TelegramBareClient: else: sender.connect() - raise ValueError('Number of retries reached 0.') + raise RuntimeError('Number of retries reached 0.') finally: if sender != self._sender: sender.disconnect() # Close temporary connections @@ -676,8 +676,8 @@ class TelegramBareClient: if progress_callback: progress_callback(stream.tell(), file_size) else: - raise ValueError('Failed to upload file part {}.' - .format(part_index)) + raise RuntimeError( + 'Failed to upload file part {}.'.format(part_index)) finally: stream.close() @@ -847,7 +847,7 @@ class TelegramBareClient: :return: """ if self._spawn_read_thread and not self._on_read_thread(): - raise ValueError('Can only idle if spawn_read_thread=False') + raise RuntimeError('Can only idle if spawn_read_thread=False') for sig in stop_signals: signal(sig, self._signal_handler) diff --git a/telethon/telegram_client.py b/telethon/telegram_client.py index 8038f484..2f48f7a7 100644 --- a/telethon/telegram_client.py +++ b/telethon/telegram_client.py @@ -13,9 +13,8 @@ except ImportError: from . import TelegramBareClient from . import helpers, utils from .errors import ( - RPCError, UnauthorizedError, InvalidParameterError, PhoneCodeEmptyError, - PhoneCodeExpiredError, PhoneCodeHashEmptyError, PhoneCodeInvalidError, - LocationInvalidError + RPCError, UnauthorizedError, PhoneCodeEmptyError, PhoneCodeExpiredError, + PhoneCodeHashEmptyError, PhoneCodeInvalidError, LocationInvalidError ) from .network import ConnectionMode from .tl import TLObject @@ -380,7 +379,7 @@ class TelegramClient(TelegramBareClient): if parse_mode in {'md', 'markdown'}: message, msg_entities = markdown.parse(message) else: - raise ValueError('Unknown parsing mode', parse_mode) + raise ValueError('Unknown parsing mode: {}'.format(parse_mode)) else: msg_entities = [] @@ -571,7 +570,7 @@ class TelegramClient(TelegramBareClient): """ if max_id is None: if not messages: - raise InvalidParameterError( + raise ValueError( 'Either a message list or a max_id must be provided.') if hasattr(message, '__iter__'): @@ -599,7 +598,7 @@ class TelegramClient(TelegramBareClient): # hex(crc32(b'Message')) = 0x790009e3 return reply_to.id - raise ValueError('Invalid reply_to type: ', type(reply_to)) + raise TypeError('Invalid reply_to type: {}'.format(type(reply_to))) # endregion @@ -1070,9 +1069,15 @@ class TelegramClient(TelegramBareClient): an username, and processes all the found entities on the session. The string may also be a user link, or a channel/chat invite link. +<<<<<<< HEAD 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. +======= + raise TypeError( + 'Cannot turn "{}" into any entity (user or chat)'.format(entity) + ) +>>>>>>> 6ec6967ff9a2e09aae70b500273075bdfbae975c Returns the found entity. """ @@ -1141,7 +1146,7 @@ class TelegramClient(TelegramBareClient): pass if not is_peer: - raise ValueError( + raise TypeError( 'Cannot turn "{}" into an input entity.'.format(peer) ) diff --git a/telethon/tl/custom/draft.py b/telethon/tl/custom/draft.py index c50baa78..abf84548 100644 --- a/telethon/tl/custom/draft.py +++ b/telethon/tl/custom/draft.py @@ -21,7 +21,7 @@ class Draft: @classmethod def _from_update(cls, client, update): if not isinstance(update, UpdateDraftMessage): - raise ValueError( + raise TypeError( 'You can only create a new `Draft` from a corresponding ' '`UpdateDraftMessage` object.' ) diff --git a/telethon/tl/tlobject.py b/telethon/tl/tlobject.py index e2b23018..489765e2 100644 --- a/telethon/tl/tlobject.py +++ b/telethon/tl/tlobject.py @@ -97,7 +97,8 @@ class TLObject: if isinstance(data, str): data = data.encode('utf-8') else: - raise ValueError('bytes or str expected, not', type(data)) + raise TypeError( + 'bytes or str expected, not {}'.format(type(data))) r = [] if len(data) < 254: diff --git a/telethon/utils.py b/telethon/utils.py index 0662a99d..720345db 100644 --- a/telethon/utils.py +++ b/telethon/utils.py @@ -74,13 +74,13 @@ def get_extension(media): def _raise_cast_fail(entity, target): - raise ValueError('Cannot cast {} to any kind of {}.' - .format(type(entity).__name__, target)) + raise TypeError('Cannot cast {} to any kind of {}.'.format( + type(entity).__name__, target)) def get_input_peer(entity, allow_self=True): """Gets the input peer for the given "entity" (user, chat or channel). - A ValueError is raised if the given entity isn't a supported type.""" + A TypeError is raised if the given entity isn't a supported type.""" if not isinstance(entity, TLObject): _raise_cast_fail(entity, 'InputPeer')