Back to top
Edit this page
Toggle table of contents sidebar
This module contains classes that represent Telegram errors.
Changed in version 20.0: Replaced Unauthorized
by Forbidden
.
- exception telegram.error.BadRequest(message)[source]¶
-
Bases:
telegram.error.NetworkError
Raised when Telegram could not process the request correctly.
- exception telegram.error.ChatMigrated(new_chat_id)[source]¶
-
Bases:
telegram.error.TelegramError
Raised when the requested group chat migrated to supergroup and has a new chat id.
- Parameters:
-
new_chat_id (
int
) – The new chat id of the group.
- new_chat_id[source]¶
-
The new chat id of the group.
- Type:
-
int
- exception telegram.error.Conflict(message)[source]¶
-
Bases:
telegram.error.TelegramError
Raised when a long poll or webhook conflicts with another one.
- exception telegram.error.Forbidden(message)[source]¶
-
Bases:
telegram.error.TelegramError
Raised when the bot has not enough rights to perform the requested action.
Changed in version 20.0: This class was previously named
Unauthorized
.
- exception telegram.error.InvalidToken(message=None)[source]¶
-
Bases:
telegram.error.TelegramError
Raised when the token is invalid.
- Parameters:
-
message (
str
, optional) –Any additional information about the exception.
New in version 20.0.
- exception telegram.error.NetworkError(message)[source]¶
-
Bases:
telegram.error.TelegramError
Base class for exceptions due to networking errors.
- exception telegram.error.PassportDecryptionError(message)[source]¶
-
Bases:
telegram.error.TelegramError
Something went wrong with decryption.
Changed in version 20.0: This class was previously named
TelegramDecryptionError
and was available via
telegram.TelegramDecryptionError
.
- exception telegram.error.RetryAfter(retry_after)[source]¶
-
Bases:
telegram.error.TelegramError
Raised when flood limits where exceeded.
Changed in version 20.0:
retry_after
is now an integer to comply with the Bot API.- Parameters:
-
retry_after (
int
) – Time in seconds, after which the bot can retry the request.
- retry_after[source]¶
-
Time in seconds, after which the bot can retry the request.
- Type:
-
int
- exception telegram.error.TelegramError(message)[source]¶
-
Bases:
Exception
Base class for Telegram errors.
- exception telegram.error.TimedOut(message=None)[source]¶
-
Bases:
telegram.error.NetworkError
Raised when a request took too long to finish.
- Parameters:
-
message (
str
, optional) –Any additional information about the exception.
New in version 20.0.
Реализация собственного обработчика ошибок для Telegram бота.
Внимание! Пакеты
python-telegram-bot
версии 13.x будут придерживаться многопоточной парадигмы программирования (на данный момент актуальна версия 13.14). Пакеты версий 20.x и новее будут полностью асинхронными и на октябрь 2022 года, первый из них находится в предрелизе. Дополнительно смотрите основные изменения в пакетеpython-telegram-bot
версии 20.x.
В python-telegram-bot
все ошибки, связанные с Telegram, инкапсулируются в класс исключения TelegramError
и его подклассы, расположенные в модуле telegram.error
.
Любая ошибка, включая TelegramError
, которая возникает в одном из обработчиков сообщений или при вызове Updater.get_updates()
, перенаправляется всем зарегистрированным обработчикам ошибок, чтобы можно было на них отреагировать.
Что бы зарегистрировать обработчик ошибок, необходимо вызвать Dispatcher.add_error_handler(callback)
, где обратный вызов callback
— это функция, которая принимает обновление update
и контекст context
. Объект update
будет обновлением, вызвавшим ошибку (или None
, если ошибка не была вызвана update
, например, для Jobs
), а context.error
— возникшей ошибкой.
: пытаемся отправить сообщение, но пользователь заблокировал бота. Будет вызвано исключение Unauthorized
, подкласса TelegramError
, которое будет доставлено обработчику ошибок. В обработчике ошибок можно удалить этот контакт из списка контактов бота.
. Можно обрабатывать исключения по мере их возникновения. Обработчику ошибок python-telegram-bot
перенаправляются только неперехваченные исключения.
Пример собственного обработчика ошибок.
Очень простой пример того, как можно реализовать собственный обработчик ошибок.
import html import json import logging import traceback from telegram import Update, ParseMode from telegram.ext import Updater, CommandHandler logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) # Токен, который получен от @botfather при создании бота BOT_TOKEN = "TOKEN" # Это может быть ваш собственный идентификатор # или идентификатор группы/канала. # Можно использовать команду `/start` этого бота, # чтобы увидеть свой идентификатор чата. CHAT_ID = 123456789 # Функция-обработчик ошибок def error_handler(update, context): """ Регистрирует ошибку и уведомляет разработчика сообщением telegram. """ # Пишем ошибку, прежде чем что-то делать. Вдруг что-то сломается. logger.error(msg="Исключение при обработке сообщения:", exc_info=context.error) # `traceback.format_exception` возвращает обычное сообщение python # об исключении в виде списка строк, поэтому объединяем их вместе. tb_list = traceback.format_exception(None, context.error, context.error.__traceback__) tb_string = ''.join(tb_list) # Создаем сообщение с некоторой разметкой и дополнительной # информацией о том, что произошло. Возможно, придется добавить некоторую # логику для работы с сообщениями длиной более 4096 символов. update_str = update.to_dict() if isinstance(update, Update) else str(update) message = ( f'Возникло исключение при обработке сообщения.n' f'<pre>update = {html.escape(json.dumps(update_str, indent=2, ensure_ascii=False))}' '</pre>nn' f'<pre>context.chat_data = {html.escape(str(context.chat_data))}</pre>nn' f'<pre>context.user_data = {html.escape(str(context.user_data))}</pre>nn' f'<pre>{html.escape(tb_string)}</pre>' ) # Отправляем сообщение разработчику context.bot.send_message(chat_id=CHAT_ID, text=message, parse_mode=ParseMode.HTML) # объект `update` в функции не используется, заменяем его на `_` def bad_command(_, context): """Вызывает ошибку, чтобы вызвать обработчик ошибок.""" context.bot.wrong_method_name() # объект `context` в функции не используется, заменяем его на `_` def start(update, _): update.effective_message.reply_html( 'Принудительный вызов ошибки `/bad_command`n' f'Ваш идентификатор чата <code>{update.effective_chat.id}</code>.' ) if __name__ == '__main__': updater = Updater(BOT_TOKEN) dispatcher = updater.dispatcher # Зарегистрируем команды... dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('bad_command', bad_command)) # ...и обработчик ошибок dispatcher.add_error_handler(error_handler) # Запускаем бота updater.start_polling() updater.idle()
Хороший обработчик ошибок.
Следующий фрагмент кода уведомляет пользователя, когда происходит ошибка, и уведомляет разработчиков об ошибке, включая трассировку и место ее возникновения. Комментарии в коде объясняют, что именно происходит, когда и почему, поэтому редактировать его в соответствии с особыми потребностями должно быть проще простого.
from telegram import ParseMode from telegram.utils.helpers import mention_html import sys import traceback # это общая функция обработчика ошибок. # Если нужна дополнительная информация о конкретном типе сообщения, # добавьте ее в полезную нагрузку в соответствующем предложении `if ...` def error(update, context): # добавьте все идентификаторы разработчиков в этот список. # Можно добавить идентификаторы каналов или групп. devs = [208589966] # Уведомление пользователя об этой проблеме. # Уведомления будут работать, только если сообщение НЕ является # обратным вызовом, встроенным запросом или обновлением опроса. # В случае, если это необходимо, то имейте в виду, что отправка # сообщения может потерпеть неудачу if update.effective_message: text = "К сожалению произошла ошибка в момент обработки сообщения. " "Мы уже работаем над этой проблемой." update.effective_message.reply_text(text) # Трассировка создается из `sys.exc_info`, которая возвращается в # как третье значение возвращаемого кортежа. Затем используется # `traceback.format_tb`, для получения `traceback` в виде строки. trace = "".join(traceback.format_tb(sys.exc_info()[2])) # попробуем получить как можно больше информации из обновления telegram payload = [] # обычно всегда есть пользователь. Если нет, то это # либо канал, либо обновление опроса. if update.effective_user: bad_user = mention_html(update.effective_user.id, update.effective_user.first_name) payload.append(f' с пользователем {bad_user}') # есть ситуаций, когда что то с чатом if update.effective_chat: payload.append(f' внутри чата <i>{update.effective_chat.title}</i>') if update.effective_chat.username: payload.append(f' (@{update.effective_chat.username})') # полезная нагрузка - опрос if update.poll: payload.append(f' с id опроса {update.poll.id}.') # Поместим это в 'хорошо' отформатированный текст text = f"Ошибка <code>{context.error}</code> случилась{''.join(payload)}. " f"Полная трассировка:nn<code>{trace}</code>" # и отправляем все разработчикам for dev_id in devs: context.bot.send_message(dev_id, text, parse_mode=ParseMode.HTML) # Необходимо снова вызывать ошибку, для того, чтобы модуль `logger` ее записал. # Если вы не используете этот модуль, то самое время задуматься. raise
The following are 30
code examples of telegram.error.TelegramError().
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
telegram.error
, or try the search function
.
Example #1
def get_me(self, timeout=None, **kwargs): """A simple method for testing your bot's auth token. Requires no parameters. Args: timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). Returns: :class:`telegram.User`: A :class:`telegram.User` instance representing that bot if the credentials are valid, :obj:`None` otherwise. Raises: :class:`telegram.TelegramError` """ url = '{0}/getMe'.format(self.base_url) result = self._request.get(url, timeout=timeout) self.bot = User.de_json(result, self) return self.bot
Example #2
def delete_webhook(self, timeout=None, **kwargs): """ Use this method to remove webhook integration if you decide to switch back to getUpdates. Requires no parameters. Args: timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :obj:`bool` On success, ``True`` is returned. Raises: :class:`telegram.TelegramError` """ url = '{0}/deleteWebhook'.format(self.base_url) data = kwargs result = self._request.post(url, data, timeout=timeout) return result
Example #3
def delete_sticker_from_set(self, sticker, timeout=None, **kwargs): """Use this method to delete a sticker from a set created by the bot. Args: sticker (:obj:`str`): File identifier of the sticker. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :obj:`bool`: On success, ``True`` is returned. Raises: :class:`telegram.TelegramError` """ url = '{0}/deleteStickerFromSet'.format(self.base_url) data = {'sticker': sticker} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
Example #4
def main(): global update_id bot = telegram.Bot(token=TOKEN) try: update_id = bot.get_updates()[0].update_id except IndexError: update_id = None interface = telegram.ReplyKeyboardMarkup( [["Arabic", "Audio", "English", "Tafsir"], ["Previous", "Random", "Next"]], resize_keyboard=True) data = { "english": Quran("translation"), "tafsir": Quran("tafsir"), "index": make_index(), "interface": interface } data["default_query_results"] = get_default_query_results(data["english"]) while True: try: serve(bot, data) except NetworkError: sleep(1) except Unauthorized: # user has removed or blocked the bot update_id += 1 except TelegramError as e: if "Invalid server response" in str(e): sleep(3) else: raise e
Example #5
def file_id_query_received(update: Update, context: CallbackContext): # get query query = update.inline_query user_id = query.from_user.id results = None try: file = bot.get_file(query.query) _id = uuid.uuid4() title = get_message(user_id, "your_sticker") desc = get_message(user_id, "forward_desc") caption = "@EzStickerBot" results = [InlineQueryResultCachedDocument(_id, title, file.file_id, description=desc, caption=caption)] query.answer(results=results, cache_time=5, is_personal=True) # if file_id wasn't found show share option except TelegramError: share_query_received(update, context)
Example #6
def error_callback(bot, update, error): try: raise error except Unauthorized: print("no nono1") print(error) # remove update.message.chat_id from conversation list except BadRequest: print("no nono2") print("BadRequest caught") print(error) # handle malformed requests - read more below! except TimedOut: print("no nono3") # handle slow connection problems except NetworkError: print("no nono4") # handle other connection problems except ChatMigrated as err: print("no nono5") print(err) # the chat_id of a group has changed, use e.new_chat_id instead except TelegramError: print(error) # handle all other telegram related errors
Example #7
def send_to_list(bot: Bot, send_to: list, message: str, markdown=False, html=False) -> None: if html and markdown: raise Exception("Can only send with either markdown or HTML!") for user_id in set(send_to): try: if markdown: bot.send_message(user_id, message, parse_mode=ParseMode.MARKDOWN) elif html: bot.send_message(user_id, message, parse_mode=ParseMode.HTML) else: bot.send_message(user_id, message) except TelegramError: pass # ignore users who fail
Example #8
def finish(self): # set last update self.channel.last_update = datetime.date.today() self._save_channel() new_bots = Bot.select_new_bots() if not self.silent and len(new_bots) > 0: self.notify_admin("Sending notifications to subscribers...") subscribers = Notifications.select().where(Notifications.enabled == True) notification_count = 0 for sub in subscribers: try: util.send_md_message(self.bot, sub.chat_id, messages.BOTLIST_UPDATE_NOTIFICATION.format( n_bots=len(new_bots), new_bots=Bot.get_new_bots_markdown())) notification_count += 1 sub.last_notification = datetime.date.today() sub.save() except TelegramError: pass self.sent['notifications'] = "Notifications sent to {} users.".format( notification_count) changes_made = len(self.sent) > 1 or len(self.sent['category']) > 0 if changes_made: text = util.success('{}{}'.format('BotList updated successfully:nn', mdformat.results_list(self.sent))) else: text = mdformat.none_action("No changes were necessary.") log.info(self.sent) self.bot.formatter.send_or_edit(self.chat_id, text, to_edit=self.message_id)
Example #9
def check_requirements(self): try: self.bot.get_me() self.bot.send_message(chat_id=self.chat_id, text="Kimsufi Crawler started") except TelegramError as te: _logger.error("Telegram validation failed: {error}".format(error=te.message)) raise
Example #10
def notify(self, title, text, url=None): try: self.bot.send_message(chat_id=self.chat_id, text=text) except TelegramError as te: _logger.error("Something went wrong sending the message to Telegram:") _logger.error(te)
Example #11
def send_to_list(bot: Bot, send_to: list, message: str, markdown=False, html=False) -> None: if html and markdown: raise Exception("Can only send with either markdown or HTML!") for user_id in set(send_to): try: if markdown: bot.send_message(user_id, message, parse_mode=ParseMode.MARKDOWN) elif html: bot.send_message(user_id, message, parse_mode=ParseMode.HTML) else: bot.send_message(user_id, message) except TelegramError: pass # ignore users who fail
Example #12
def delete_message(self, chat_id, message_id, timeout=None, **kwargs): """ Use this method to delete a message. A message can only be deleted if it was sent less than 48 hours ago. Any such recently sent outgoing message may be deleted. Additionally, if the bot is an administrator in a group chat, it can delete any message. If the bot is an administrator in a supergroup, it can delete messages from any other user and service messages about people joining or leaving the group (other types of service messages may only be removed by the group creator). In channels, bots can only remove their own messages. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). message_id (:obj:`int`): Identifier of the message to delete. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :obj:`bool`: On success, ``True`` is returned. Raises: :class:`telegram.TelegramError` """ url = '{0}/deleteMessage'.format(self.base_url) data = {'chat_id': chat_id, 'message_id': message_id} result = self._request.post(url, data, timeout=timeout) return result
Example #13
def send_game(self, chat_id, game_short_name, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=None, **kwargs): """Use this method to send a game. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). game_short_name (:obj:`str`): Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather. disable_notification (:obj:`bool`, optional): Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the original message. reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :class:`telegram.Message`: On success, the sent Message is returned. Raises: :class:`telegram.TelegramError` """ url = '{0}/sendGame'.format(self.base_url) data = {'chat_id': chat_id, 'game_short_name': game_short_name} return url, data
Example #14
def get_user_profile_photos(self, user_id, offset=None, limit=100, timeout=None, **kwargs): """Use this method to get a list of profile pictures for a user. Args: user_id (:obj:`int`): Unique identifier of the target user. offset (:obj:`int`, optional): Sequential number of the first photo to be returned. By default, all photos are returned. limit (:obj:`int`, optional): Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :class:`telegram.UserProfilePhotos` Raises: :class:`telegram.TelegramError` """ url = '{0}/getUserProfilePhotos'.format(self.base_url) data = {'user_id': user_id} if offset is not None: data['offset'] = offset if limit: data['limit'] = limit data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return UserProfilePhotos.de_json(result, self)
Example #15
def get_file(self, file_id, timeout=None, **kwargs): """ Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. The file can then be downloaded with :attr:`telegram.File.download`. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again. Args: file_id (:obj:`str`): File identifier to get info about. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :class:`telegram.File` Raises: :class:`telegram.TelegramError` """ url = '{0}/getFile'.format(self.base_url) data = {'file_id': file_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) if result.get('file_path'): result['file_path'] = '%s/%s' % (self.base_file_url, result['file_path']) return File.de_json(result, self)
Example #16
def unban_chat_member(self, chat_id, user_id, timeout=None, **kwargs): """Use this method to unban a previously kicked user in a supergroup. The user will not return to the group automatically, but will be able to join via link, etc. The bot must be an administrator in the group for this to work. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target channel (in the format @channelusername). user_id (:obj:`int`): Unique identifier of the target user. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :obj:`bool` On success, ``True`` is returned. Raises: :class:`telegram.TelegramError` """ url = '{0}/unbanChatMember'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
Example #17
def leave_chat(self, chat_id, timeout=None, **kwargs): """Use this method for your bot to leave a group, supergroup or channel. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :obj:`bool` On success, ``True`` is returned. Raises: :class:`telegram.TelegramError` """ url = '{0}/leaveChat'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
Example #18
def get_chat(self, chat_id, timeout=None, **kwargs): """ Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :class:`telegram.Chat` Raises: :class:`telegram.TelegramError` """ url = '{0}/getChat'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return Chat.de_json(result, self)
Example #19
def get_chat_members_count(self, chat_id, timeout=None, **kwargs): """Use this method to get the number of members in a chat Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: int: Number of members in the chat. Raises: :class:`telegram.TelegramError` """ url = '{0}/getChatMembersCount'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
Example #20
def get_chat_member(self, chat_id, user_id, timeout=None, **kwargs): """Use this method to get information about a member of a chat. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). user_id (:obj:`int`): Unique identifier of the target user. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :class:`telegram.ChatMember` Raises: :class:`telegram.TelegramError` """ url = '{0}/getChatMember'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return ChatMember.de_json(result, self)
Example #21
def export_chat_invite_link(self, chat_id, timeout=None, **kwargs): """ Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments Returns: :obj:`str`: Exported invite link on success. Raises: :class:`telegram.TelegramError` """ url = '{0}/exportChatInviteLink'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
Example #22
def set_chat_photo(self, chat_id, photo, timeout=None, **kwargs): """Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). photo (`telegram.InputFile`): New chat photo. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments Note: In regular groups (non-supergroups), this method will only work if the 'All Members Are Admins' setting is off in the target group. Returns: :obj:`bool`: Returns True on success. Raises: :class:`telegram.TelegramError` """ url = '{0}/setChatPhoto'.format(self.base_url) data = {'chat_id': chat_id, 'photo': photo} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
Example #23
def delete_chat_photo(self, chat_id, timeout=None, **kwargs): """ Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments Note: In regular groups (non-supergroups), this method will only work if the 'All Members Are Admins' setting is off in the target group. Returns: :obj:`bool`: Returns ``True`` on success. Raises: :class:`telegram.TelegramError` """ url = '{0}/deleteChatPhoto'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
Example #24
def set_chat_title(self, chat_id, title, timeout=None, **kwargs): """ Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). title (:obj:`str`): New chat title, 1-255 characters. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments Note: In regular groups (non-supergroups), this method will only work if the 'All Members Are Admins' setting is off in the target group. Returns: :obj:`bool`: Returns ``True`` on success. Raises: :class:`telegram.TelegramError` """ url = '{0}/setChatTitle'.format(self.base_url) data = {'chat_id': chat_id, 'title': title} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
Example #25
def pin_chat_message(self, chat_id, message_id, disable_notification=None, timeout=None, **kwargs): """ Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). message_id (:obj:`int`): Identifier of a message to pin. disable_notification (:obj:`bool`, optional): Pass True, if it is not necessary to send a notification to all group members about the new pinned message. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments Returns: :obj:`bool`: Returns ``True`` on success. Raises: :class:`telegram.TelegramError` """ url = '{0}/pinChatMessage'.format(self.base_url) data = {'chat_id': chat_id, 'message_id': message_id} if disable_notification is not None: data['disable_notification'] = disable_notification data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
Example #26
def unpin_chat_message(self, chat_id, timeout=None, **kwargs): """ Use this method to unpin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Args: chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username of the target`channel (in the format @channelusername). timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments Returns: :obj:`bool`: Returns ``True`` on success. Raises: :class:`telegram.TelegramError` """ url = '{0}/unpinChatMessage'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
Example #27
def get_sticker_set(self, name, timeout=None, **kwargs): """Use this method to get a sticker set. Args: name (:obj:`str`): Short name of the sticker set that is used in t.me/addstickers/ URLs (e.g., animals) timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :class:`telegram.StickerSet` Raises: :class:`telegram.TelegramError` """ url = '{0}/getStickerSet'.format(self.base_url) data = {'name': name} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return StickerSet.de_json(result, self)
Example #28
def upload_sticker_file(self, user_id, png_sticker, timeout=None, **kwargs): """ Use this method to upload a .png file with a sticker for later use in :attr:`create_new_sticker_set` and :attr:`add_sticker_to_set` methods (can be used multiple times). Note: The png_sticker argument can be either a file_id, an URL or a file from disk ``open(filename, 'rb')`` Args: user_id (:obj:`int`): User identifier of sticker file owner. png_sticker (:obj:`str` | `filelike object`): Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :class:`telegram.File`: The uploaded File Raises: :class:`telegram.TelegramError` """ url = '{0}/uploadStickerFile'.format(self.base_url) data = {'user_id': user_id, 'png_sticker': png_sticker} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return File.de_json(result, self)
Example #29
def set_sticker_position_in_set(self, sticker, position, timeout=None, **kwargs): """Use this method to move a sticker in a set created by the bot to a specific position. Args: sticker (:obj:`str`): File identifier of the sticker. position (:obj:`int`): New sticker position in the set, zero-based. timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). **kwargs (:obj:`dict`): Arbitrary keyword arguments. Returns: :obj:`bool`: On success, ``True`` is returned. Raises: :class:`telegram.TelegramError` """ url = '{0}/setStickerPositionInSet'.format(self.base_url) data = {'sticker': sticker, 'position': position} data.update(kwargs) result = self._request.post(url, data, timeout=timeout) return result
Example #30
def error_callback(bot, update, error): try: raise error except Unauthorized: print("no nono1") print(error) # remove update.message.chat_id from conversation list except BadRequest: print("no nono2") print("BadRequest caught") print(error) # handle malformed requests - read more below! except TimedOut: print("no nono3") # handle slow connection problems except NetworkError: print("no nono4") # handle other connection problems except ChatMigrated as err: print("no nono5") print(err) # the chat_id of a group has changed, use e.new_chat_id instead except TelegramError: print(error) # handle all other telegram related errors
Here are the examples of the python api telegram.TelegramError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3
Example 1
def _check_ssl_cert(self, cert, key):
# Check SSL-Certificate with openssl, if possible
try:
exit_code = subprocess.call(
["openssl", "x509", "-text", "-noout", "-in", cert],
stdout=open(os.devnull, 'wb'),
stderr=subprocess.STDOUT)
except OSError:
exit_code = 0
if exit_code is 0:
try:
self.httpd.socket = ssl.wrap_socket(
self.httpd.socket, certfile=cert, keyfile=key, server_side=True)
except ssl.SSLError as error:
self.logger.exception('Failed to init SSL socket')
raise TelegramError(str(error))
else:
raise TelegramError('SSL Certificate invalid')
3
Example 2
@staticmethod
def is_image(stream):
"""Check if the content file is an image by analyzing its headers.
Args:
stream (str): A str representing the content of a file.
Returns:
str: The str mimetype of an image.
"""
image = imghdr.what(None, stream)
if image:
return 'image/%s' % image
raise TelegramError('Could not parse file content')
3
Example 3
@flaky(3, 1)
@timeout(10)
def test_error_send_audio_empty_file(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['audio'] = open(os.devnull, 'rb')
self.assertRaises(
telegram.TelegramError,
lambda: self._bot.sendAudio(chat_id=self._chat_id, **json_dict))
3
Example 4
@flaky(3, 1)
@timeout(10)
def test_error_send_audio_empty_file_id(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['audio'] = ''
self.assertRaises(
telegram.TelegramError,
lambda: self._bot.sendAudio(chat_id=self._chat_id, **json_dict))
3
Example 5
def testInvalidSrvResp(self):
with self.assertRaisesRegexp(telegram.TelegramError, 'Invalid server response'):
# bypass the valid token check
newbot_cls = type(
'NoTokenValidateBot', (telegram.Bot,), dict(_validate_token=lambda x, y: None))
bot = newbot_cls('0xdeadbeef')
bot.base_url = 'https://api.telegram.org/bot{0}'.format('12')
bot.getMe()
3
Example 6
@flaky(3, 1)
@timeout(10)
def test_error_send_docuement_empty_file(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['docuement'] = open(os.devnull, 'rb')
self.assertRaises(telegram.TelegramError,
lambda: self._bot.sendDocuement(chat_id=self._chat_id,
**json_dict))
3
Example 7
@flaky(3, 1)
@timeout(10)
def test_error_send_docuement_empty_file_id(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['docuement'] = ''
self.assertRaises(telegram.TelegramError,
lambda: self._bot.sendDocuement(chat_id=self._chat_id,
**json_dict))
3
Example 8
def test_error_get_empty_file_id(self):
json_dict = self.json_dict
json_dict['file_id'] = ''
del (json_dict['file_path'])
del (json_dict['file_size'])
self.assertRaises(telegram.TelegramError, lambda: self._bot.getFile(**json_dict))
3
Example 9
def test_error_send_location_empty_args(self):
json_dict = self.json_dict
json_dict['latitude'] = ''
json_dict['longitude'] = ''
self.assertRaises(telegram.TelegramError,
lambda: self._bot.sendLocation(chat_id=self._chat_id,
**json_dict))
3
Example 10
@flaky(3, 1)
@timeout(10)
def test_error_send_photo_empty_file(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['photo'] = open(os.devnull, 'rb')
self.assertRaises(
telegram.TelegramError,
lambda: self._bot.sendPhoto(chat_id=self._chat_id, **json_dict))
3
Example 11
@flaky(3, 1)
@timeout(10)
def test_error_send_photo_empty_file_id(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['photo'] = ''
self.assertRaises(
telegram.TelegramError,
lambda: self._bot.sendPhoto(chat_id=self._chat_id, **json_dict))
3
Example 12
@flaky(3, 1)
@timeout(10)
def test_error_send_sticker_empty_file(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['sticker'] = open(os.devnull, 'rb')
self.assertRaises(
telegram.TelegramError,
lambda: self._bot.sendSticker(chat_id=self._chat_id, **json_dict))
3
Example 13
@flaky(3, 1)
@timeout(10)
def test_error_send_sticker_empty_file_id(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['sticker'] = ''
self.assertRaises(
telegram.TelegramError,
lambda: self._bot.sendSticker(chat_id=self._chat_id, **json_dict))
3
Example 14
def test_addRemoveErrorHandler(self):
self._setup_updater('', messages=0)
d = self.updater.dispatcher
d.add_error_handler(self.errorHandlerTest)
queue = self.updater.start_polling(0.01)
error = TelegramError("Unauthorized.")
queue.put(error)
sleep(.1)
self.assertEqual(self.received_message, "Unauthorized.")
# Remove handler
d.remove_error_handler(self.errorHandlerTest)
self.reset()
queue.put(error)
sleep(.1)
self.assertTrue(None is self.received_message)
3
Example 15
def getUpdates(self, offset=None, limit=100, timeout=0, network_delay=2.):
if self.raise_error:
raise TelegramError('Test Error 2')
elif self.send_messages >= 2:
self.send_messages -= 2
return self.mockUpdate(self.text), self.mockUpdate(self.text)
elif self.send_messages == 1:
self.send_messages -= 1
return self.mockUpdate(self.text),
else:
return []
3
Example 16
@flaky(3, 1)
@timeout(10)
def test_error_send_video_empty_file(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['video'] = open(os.devnull, 'rb')
self.assertRaises(telegram.TelegramError,
lambda: self._bot.sendVideo(chat_id=self._chat_id,
timeout=10,
**json_dict))
3
Example 17
@flaky(3, 1)
@timeout(10)
def test_error_send_video_empty_file_id(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['video'] = ''
self.assertRaises(telegram.TelegramError,
lambda: self._bot.sendVideo(chat_id=self._chat_id,
timeout=10,
**json_dict))
3
Example 18
@flaky(3, 1)
@timeout(10)
def test_error_send_voice_empty_file(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['voice'] = open(os.devnull, 'rb')
self.assertRaises(
telegram.TelegramError,
lambda: self._bot.sendVoice(chat_id=self._chat_id, **json_dict))
3
Example 19
@flaky(3, 1)
@timeout(10)
def test_error_send_voice_empty_file_id(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['voice'] = ''
self.assertRaises(
telegram.TelegramError,
lambda: self._bot.sendVoice(chat_id=self._chat_id, **json_dict))
0
Example 20
def start(self):
"""
Thread target of thread 'dispatcher'. Runs in background and processes
the update queue.
"""
if self.running:
self.logger.warning('already running')
return
if self.__exception_event.is_set():
msg = 'reusing dispatcher after exception event is forbidden'
self.logger.error(msg)
raise TelegramError(msg)
self._init_async_threads(uuid4(), self.workers)
self.running = True
self.logger.debug('Dispatcher started')
while 1:
try:
# Pop update from update queue.
update = self.update_queue.get(True, 1)
except Empty:
if self.__stop_event.is_set():
self.logger.debug('orderly stopping')
break
elif self.__exception_event.is_set():
self.logger.critical('stopping due to exception in another thread')
break
continue
self.logger.debug('Processing Update: %s' % update)
self.process_update(update)
self.running = False
self.logger.debug('Dispatcher thread stopped')
0
Example 21
def __init__(self, data):
self.data = data
self.boundary = choose_boundary()
if 'audio' in data:
self.input_name = 'audio'
self.input_file = data.pop('audio')
elif 'docuement' in data:
self.input_name = 'docuement'
self.input_file = data.pop('docuement')
elif 'photo' in data:
self.input_name = 'photo'
self.input_file = data.pop('photo')
elif 'sticker' in data:
self.input_name = 'sticker'
self.input_file = data.pop('sticker')
elif 'video' in data:
self.input_name = 'video'
self.input_file = data.pop('video')
elif 'voice' in data:
self.input_name = 'voice'
self.input_file = data.pop('voice')
elif 'certificate' in data:
self.input_name = 'certificate'
self.input_file = data.pop('certificate')
else:
raise TelegramError('Unknown inputfile type')
if hasattr(self.input_file, 'read'):
self.filename = None
self.input_file_content = self.input_file.read()
if 'filename' in data:
self.filename = self.data.pop('filename')
elif hasattr(self.input_file, 'name'):
# on py2.7, pylint fails to understand this properly
# pylint: disable=E1101
self.filename = os.path.basename(self.input_file.name)
try:
self.mimetype = self.is_image(self.input_file_content)
if not self.filename or '.' not in self.filename:
self.filename = self.mimetype.replace('/', '.')
except TelegramError:
self.mimetype = mimetypes.guess_type(self.filename)[0] or DEFAULT_MIME_TYPE
0
Example 22
@staticmethod
def _parse(json_data):
"""Try and parse the JSON returned from Telegram.
Returns:
dict: A JSON parsed as Python dict with results - on error this dict will be empty.
"""
decoded_s = json_data.decode('utf-8')
try:
data = json.loads(decoded_s)
except ValueError:
raise TelegramError('Invalid server response')
if not data.get('ok'):
description = data.get('description')
parameters = data.get('parameters')
if parameters:
migrate_to_chat_id = parameters.get('migrate_to_chat_id')
if migrate_to_chat_id:
raise ChatMigrated(migrate_to_chat_id)
retry_after = parameters.get('retry_after')
if retry_after:
raise RetryAfter(retry_after)
if description:
return description
return data['result']
0
Example 23
def errorRaisingHandlerTest(self, bot, update):
raise TelegramError(update)
0
Example 24
def handle(self, upd):
if upd.message is not None:
self.logger.debug("Got message: " + str(upd.message))
text = upd.message.text
action = None
if len(text)is not 0:
if text[:1] == '/' and len(text) > 1:
command, *args = text[1:].split()
if '@' in command:
command, uname, *_ = command.lower().split('@')
calling_me = (uname == self.tg.username.lower())
if '@' not in command or calling_me:
action = self.handle_cmd, upd.message, command.lower(), args
else:
action = self.handle_chat, upd.message
else:
action = self.handle_other, upd.message
if action is not None:
fn, *args = action
try:
fn(*args)
except telegram.TelegramError as e:
self.logger.warning(
"TelegramError while handling message: " + str(e))
self.ack(upd)
4 / 4 / 0
Регистрация: 10.10.2018
Сообщений: 3
1
19.10.2018, 14:04. Показов 4945. Ответов 0
Добрый день.
Столкнулся с проблемой отправки файлов через Telegram bot.
Пользуюсь библиотекой Python telegram bot.
Пытаюсь отправить файл через бота, сам файл весит 77 КБ
Отправку делаю следующим образом
def systemInCommand(bot, update):
bot.send_document(chat_id=update.message.chat_id, ocument=open(r’C:UsersusernameDocumentsFile.tx t’, ‘rb’))
В логах выдает следующее сообщение:
Traceback (most recent call last):
File «C:UsersuserAppDataLocalProgramsPythonPytho n36-32libsite-packagestelegramutilsrequest.py», line 157, in _parse
data = json.loads(decoded_s)
File «C:UsersuserAppDataLocalProgramsPythonPytho n36-32libjson__init__.py», line 354, in loads
return _default_decoder.decode(s)
File «C:UsersuserAppDataLocalProgramsPythonPytho n36-32libjsondecoder.py», line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File «C:UsersuserAppDataLocalProgramsPythonPytho n36-32libjsondecoder.py», line 357, in raw_decode
raise JSONDecodeError(«Expecting value», s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File «C:UsersuserAppDataLocalProgramsPythonPytho n36-32libsite-packagestelegramextdispatcher.py», line 279, in process_update
handler.handle_update(update, self)
File «C:UsersuserAppDataLocalProgramsPythonPytho n36-32libsite-packagestelegramextcommandhandler.py», line 173, in handle_update
return self.callback(dispatcher.bot, update, **optional_args)
File «c:/Users/user/Documents/Python/MyBot/bot.py», line 71, in checkuserCommand
systemInCommand(bot, update)
File «c:/Users/user/Documents/Python/MyBot/bot.py», line 146, in systemInCommand
File «C:UsersuserAppDataLocalProgramsPythonPytho n36-32libsite-packagestelegrambot.py», line 65, in decorator
result = func(self, *args, **kwargs)
File «C:UsersuserAppDataLocalProgramsPythonPytho n36-32libsite-packagestelegrambot.py», line 90, in decorator
result = self._request.post(url, data, timeout=kwargs.get(‘timeout’))
File «C:UsersuserAppDataLocalProgramsPythonPytho n36-32libsite-packagestelegramutilsrequest.py», line 305, in post
result = self._request_wrapper(‘POST’, url, fields=data, **urlopen_kwargs)
File «C:UsersuserAppDataLocalProgramsPythonPytho n36-32libsite-packagestelegramutilsrequest.py», line 216, in _request_wrapper
message = self._parse(resp.data)
File «C:UsersuserAppDataLocalProgramsPythonPytho n36-32libsite-packagestelegramutilsrequest.py», line 163, in _parse
raise TelegramError(‘Invalid server response’)
telegram.error.TelegramError: Invalid server response
По итогу бот ничего не присылает, но если отправить файл размер которого 25 КБ, то бот его успешно отправляет.
Прошу помочь разобраться с данной проблемой.
Добавлено через 28 минут
Добрый день.
Тема уже не актуальна. Прошу администрацию удалить тему.
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
1
There will be errors when working with the API, and they must be correctly handled on the client.
An error is characterized by several parameters:
Error Code
Numerical value similar to HTTP status. Contains information on the type of error that occurred: for example, a data input error, privacy error, or server error. This is a required parameter.
Error Type
A string literal in the form of /[A-Z_0-9]+/
, which summarizes the problem. For example, AUTH_KEY_UNREGISTERED
. This is an optional parameter.
Error Database
A full machine-readable JSON list of RPC errors that can be returned by all methods in the API can be found here », what follows is a description of its fields:
errors
— All error messages and codes for each method (object).- Keys: Error codes as strings (numeric strings)
- Values: All error messages for each method (object)
- Keys: Error messages (string)
- Values: An array of methods which may emit this error (array of strings)
descriptions
— Descriptions for every error mentioned inerrors
(and a few other errors not related to a specific method)- Keys: Error messages
- Values: Error descriptions
user_only
— A list of methods that can only be used by users, not bots.
Error messages and error descriptions may contain printf
placeholders in key positions, for now only %d
is used to map durations contained in error messages to error descriptions.
Example:
{
"errors": {
"420": {
"2FA_CONFIRM_WAIT_%d": [
"account.deleteAccount"
],
"SLOWMODE_WAIT_%d": [
"messages.forwardMessages",
"messages.sendInlineBotResult",
"messages.sendMedia",
"messages.sendMessage",
"messages.sendMultiMedia"
]
}
},
"descriptions": {
"2FA_CONFIRM_WAIT_%d": "Since this account is active and protected by a 2FA password, we will delete it in 1 week for security purposes. You can cancel this process at any time, you'll be able to reset your account in %d seconds.",
"SLOWMODE_WAIT_%d": "Slowmode is enabled in this chat: wait %d seconds before sending another message to this chat.",
"FLOOD_WAIT_%d": "Please wait %d seconds before repeating the action."
},
"user_only": {
"account.deleteAccount"
}
}
Error Constructors
There should be a way to handle errors that are returned in rpc_error constructors.
Below is a list of error codes and their meanings:
303 SEE_OTHER
The request must be repeated, but directed to a different data center.
Examples of Errors:
- FILE_MIGRATE_X: the file to be accessed is currently stored in a different data center.
- PHONE_MIGRATE_X: the phone number a user is trying to use for authorization is associated with a different data center.
- NETWORK_MIGRATE_X: the source IP address is associated with a different data center (for registration)
- USER_MIGRATE_X: the user whose identity is being used to execute queries is associated with a different data center (for registration)
In all these cases, the error description’s string literal contains the number of the data center (instead of the X) to which the repeated query must be sent.
More information about redirects between data centers »
400 BAD_REQUEST
The query contains errors. In the event that a request was created using a form and contains user generated data, the user should be notified that the data must be corrected before the query is repeated.
Examples of Errors:
- FIRSTNAME_INVALID: The first name is invalid
- LASTNAME_INVALID: The last name is invalid
- PHONE_NUMBER_INVALID: The phone number is invalid
- PHONE_CODE_HASH_EMPTY: phone_code_hash is missing
- PHONE_CODE_EMPTY: phone_code is missing
- PHONE_CODE_EXPIRED: The confirmation code has expired
- API_ID_INVALID: The api_id/api_hash combination is invalid
- PHONE_NUMBER_OCCUPIED: The phone number is already in use
- PHONE_NUMBER_UNOCCUPIED: The phone number is not yet being used
- USERS_TOO_FEW: Not enough users (to create a chat, for example)
- USERS_TOO_MUCH: The maximum number of users has been exceeded (to create a chat, for example)
- TYPE_CONSTRUCTOR_INVALID: The type constructor is invalid
- FILE_PART_INVALID: The file part number is invalid
- FILE_PARTS_INVALID: The number of file parts is invalid
- FILE_PART_X_MISSING: Part X (where X is a number) of the file is missing from storage
- MD5_CHECKSUM_INVALID: The MD5 checksums do not match
- PHOTO_INVALID_DIMENSIONS: The photo dimensions are invalid
- FIELD_NAME_INVALID: The field with the name FIELD_NAME is invalid
- FIELD_NAME_EMPTY: The field with the name FIELD_NAME is missing
- MSG_WAIT_FAILED: A request that must be completed before processing the current request returned an error
- MSG_WAIT_TIMEOUT: A request that must be completed before processing the current request didn’t finish processing yet
401 UNAUTHORIZED
There was an unauthorized attempt to use functionality available only to authorized users.
Examples of Errors:
- AUTH_KEY_UNREGISTERED: The key is not registered in the system
- AUTH_KEY_INVALID: The key is invalid
- USER_DEACTIVATED: The user has been deleted/deactivated
- SESSION_REVOKED: The authorization has been invalidated, because of the user terminating all sessions
- SESSION_EXPIRED: The authorization has expired
- AUTH_KEY_PERM_EMPTY: The method is unavailable for temporary authorization key, not bound to permanent
403 FORBIDDEN
Privacy violation. For example, an attempt to write a message to someone who has blacklisted the current user.
404 NOT_FOUND
An attempt to invoke a non-existent object, such as a method.
406 NOT_ACCEPTABLE
Similar to 400 BAD_REQUEST, but the app must display the error to the user a bit differently.
Do not display any visible error to the user when receiving the rpc_error
constructor: instead, wait for an updateServiceNotification update, and handle it as usual.
Basically, an updateServiceNotification popup
update will be emitted independently (ie NOT as an Updates constructor inside rpc_result
but as a normal update) immediately after emission of a 406 rpc_error
: the update will contain the actual localized error message to show to the user with a UI popup.
An exception to this is the AUTH_KEY_DUPLICATED
error, which is only emitted if any of the non-media DC detects that an authorized session is sending requests in parallel from two separate TCP connections, from the same or different IP addresses.
Note that parallel connections are still allowed and actually recommended for media DCs.
Also note that by session we mean a logged-in session identified by an authorization constructor, fetchable using account.getAuthorizations, not an MTProto session.
If the client receives an AUTH_KEY_DUPLICATED
error, the session is already invalidated by the server and the user must generate a new auth key and login again.
420 FLOOD
The maximum allowed number of attempts to invoke the given method with the given input parameters has been exceeded. For example, in an attempt to request a large number of text messages (SMS) for the same phone number.
Error Example:
- FLOOD_WAIT_X: A wait of X seconds is required (where X is a number)
500 INTERNAL
An internal server error occurred while a request was being processed; for example, there was a disruption while accessing a database or file storage.
If a client receives a 500 error, or you believe this error should not have occurred, please collect as much information as possible about the query and error and send it to the developers.
Other Error Codes
If a server returns an error with a code other than the ones listed above, it may be considered the same as a 500 error and treated as an internal server error.