class TypeOfFileMismatch(BadRequest):
match = 'type of file mismatch'
class WrongRemoteFileIdSpecified(BadRequest):
match = 'wrong remote file id specified'
class PaymentProviderInvalid(BadRequest):
match = 'PAYMENT_PROVIDER_INVALID'
text = 'payment provider invalid'
class CurrencyTotalAmountInvalid(BadRequest):
match = 'currency_total_amount_invalid'
text = 'currency total amount invalid'
class BadWebhook(BadRequest):
__group = True
class WebhookRequireHTTPS(BadWebhook):
match = 'HTTPS url must be provided for webhook'
text = 'bad webhook: ' + match
class BadWebhookPort(BadWebhook):
match = 'Webhook can be set up only on ports 80, 88, 443 or 8443'
text = 'bad webhook: ' + match
"""
match = 'message with poll to stop not found'
class MessageIsNotAPoll(PollError, MessageError):
"""
Will be raised when you try to stop poll with message without poll
"""
match = 'message is not a poll'
class ChatNotFound(BadRequest):
match = 'chat not found'
class ChatIdIsEmpty(BadRequest):
match = 'chat_id is empty'
class InvalidUserId(BadRequest):
match = 'user_id_invalid'
text = 'Invalid user id'
class ChatDescriptionIsNotModified(BadRequest):
match = 'chat description is not modified'
class InvalidQueryID(BadRequest):
match = 'query is too old and response timeout expired or query id is invalid'
class MessageIsNotAPoll(PollError, MessageError):
"""
Will be raised when you try to stop poll with message without poll
"""
match = 'message is not a poll'
class ChatNotFound(BadRequest):
match = 'chat not found'
class ChatIdIsEmpty(BadRequest):
match = 'chat_id is empty'
class InvalidUserId(BadRequest):
match = 'user_id_invalid'
text = 'Invalid user id'
class ChatDescriptionIsNotModified(BadRequest):
match = 'chat description is not modified'
class InvalidQueryID(BadRequest):
match = 'query is too old and response timeout expired or query id is invalid'
class InvalidPeerID(BadRequest):
match = 'PEER_ID_INVALID'
text = 'Invalid peer ID'
class CantDemoteChatCreator(BadRequest):
match = 'can't demote chat creator'
class CantRestrictSelf(BadRequest):
match = "can't restrict self"
text = "Admin can't restrict self."
class NotEnoughRightsToRestrict(BadRequest):
match = 'not enough rights to restrict/unrestrict chat member'
class PhotoDimensions(BadRequest):
match = 'PHOTO_INVALID_DIMENSIONS'
text = 'Invalid photo dimensions'
class UnavailableMembers(BadRequest):
match = 'supergroup members are unavailable'
class TypeOfFileMismatch(BadRequest):
match = 'type of file mismatch'
class WrongRemoteFileIdSpecified(BadRequest):
match = 'wrong remote file id specified'
try:
result_json = json.loads(body)
except ValueError:
result_json = {}
description = result_json.get('description') or body
parameters = types.ResponseParameters(**result_json.get('parameters', {}) or {})
if HTTPStatus.OK <= status_code <= HTTPStatus.IM_USED:
return result_json.get('result')
elif parameters.retry_after:
raise exceptions.RetryAfter(parameters.retry_after)
elif parameters.migrate_to_chat_id:
raise exceptions.MigrateToChat(parameters.migrate_to_chat_id)
elif status_code == HTTPStatus.BAD_REQUEST:
exceptions.BadRequest.detect(description)
elif status_code == HTTPStatus.NOT_FOUND:
exceptions.NotFound.detect(description)
elif status_code == HTTPStatus.CONFLICT:
exceptions.ConflictError.detect(description)
elif status_code in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN]:
exceptions.Unauthorized.detect(description)
elif status_code == HTTPStatus.REQUEST_ENTITY_TOO_LARGE:
raise exceptions.NetworkError('File too large for uploading. '
'Check telegram api limits https://core.telegram.org/bots/api#senddocument')
elif status_code >= HTTPStatus.INTERNAL_SERVER_ERROR:
if 'restart' in description:
raise exceptions.RestartingTelegram()
raise exceptions.TelegramAPIError(description)
raise exceptions.TelegramAPIError(f"{description} [{status_code}]")
class InvalidQueryID(BadRequest):
match = 'query is too old and response timeout expired or query id is invalid'
class InvalidPeerID(BadRequest):
match = 'PEER_ID_INVALID'
text = 'Invalid peer ID'
class InvalidHTTPUrlContent(BadRequest):
match = 'Failed to get HTTP URL content'
class ButtonURLInvalid(BadRequest):
match = 'BUTTON_URL_INVALID'
text = 'Button URL invalid'
class URLHostIsEmpty(BadRequest):
match = 'URL host is empty'
class StartParamInvalid(BadRequest):
match = 'START_PARAM_INVALID'
text = 'Start param invalid'
class ButtonDataInvalid(BadRequest):
match = 'BUTTON_DATA_INVALID'
text = 'Button data invalid'
class MessageIsTooLong(MessageError):
match = 'message is too long'
class ToMuchMessages(MessageError):
"""
Will be raised when you try to send media group with more than 10 items.
"""
match = 'Too much messages to send as an album'
class ObjectExpectedAsReplyMarkup(BadRequest):
match = 'object expected as reply markup'
class InlineKeyboardExpected(BadRequest):
match = 'inline keyboard expected'
class PollError(BadRequest):
__group = True
class PollCantBeStopped(PollError):
match = "poll can't be stopped"
class PollHasAlreadyBeenClosed(PollError):
match = 'poll has already been closed'
class PollsCantBeSentToPrivateChats(PollError):
class ChatNotFound(BadRequest):
match = 'chat not found'
class ChatIdIsEmpty(BadRequest):
match = 'chat_id is empty'
class InvalidUserId(BadRequest):
match = 'user_id_invalid'
text = 'Invalid user id'
class ChatDescriptionIsNotModified(BadRequest):
match = 'chat description is not modified'
class InvalidQueryID(BadRequest):
match = 'query is too old and response timeout expired or query id is invalid'
class InvalidPeerID(BadRequest):
match = 'PEER_ID_INVALID'
text = 'Invalid peer ID'
class InvalidHTTPUrlContent(BadRequest):
match = 'Failed to get HTTP URL content'
class WrongRemoteFileIdSpecified(BadRequest):
match = 'wrong remote file id specified'
class PaymentProviderInvalid(BadRequest):
match = 'PAYMENT_PROVIDER_INVALID'
text = 'payment provider invalid'
class CurrencyTotalAmountInvalid(BadRequest):
match = 'currency_total_amount_invalid'
text = 'currency total amount invalid'
class BadWebhook(BadRequest):
__group = True
class WebhookRequireHTTPS(BadWebhook):
match = 'HTTPS url must be provided for webhook'
text = 'bad webhook: ' + match
class BadWebhookPort(BadWebhook):
match = 'Webhook can be set up only on ports 80, 88, 443 or 8443'
text = 'bad webhook: ' + match
class BadWebhookAddrInfo(BadWebhook):
match = 'getaddrinfo: Temporary failure in name resolution'
text = 'bad webhook: ' + match
class BadWebhookAddrInfo(BadWebhook):
match = 'getaddrinfo: Temporary failure in name resolution'
text = 'bad webhook: ' + match
class BadWebhookNoAddressAssociatedWithHostname(BadWebhook):
match = 'failed to resolve host: no address associated with hostname'
class CantParseUrl(BadRequest):
match = 'can't parse URL'
class UnsupportedUrlProtocol(BadRequest):
match = 'unsupported URL protocol'
class CantParseEntities(BadRequest):
match = 'can't parse entities'
class ResultIdDuplicate(BadRequest):
match = 'result_id_duplicate'
text = 'Result ID duplicate'
class BotDomainInvalid(BadRequest):
match = 'bot_domain_invalid'
text = 'Invalid bot domain'
Can’t parse inline keyboard button (Telegram bot)
При отправке sendMessage с телом
{
«chat_id»: «{{MyChatId}}«,
«text»: «Inline Keyboard markup test-1»,
«reply_markup»: {
«inline_keyboard»: [
[
{
«text»: «Принято»
}
]
]
}
}
возвращает ошибку
{
«ok»: false,
«error_code»: 400,
«description»: «Bad Request: can’t parse inline keyboard button: Text buttons are unallowed in the inline keyboard»
}
Причина в том, что опциональные параметры у типа InlineKeyboardButton — не 100% опциональные. В инструкции https://core.telegram.org/bots/api#inlinekeyboardbutton написано: «You must use exactly one of the optional fields.»
Если поправить запрос:
{
«chat_id»: «{{MyChatId}}«,
«text»: «Inline Keyboard markup test-1»,
«reply_markup»: {
«inline_keyboard»: [
[
{
«text»: «Принято»,
«callback_data»: «yes»
}
]
]
}
}
то все проходит нормально:
{
«ok»: true,
«result»: {
«message_id»: 1152,
«from»: {
«id»: ***,
«is_bot»: true,
«first_name»: «TestBot»,
«username»: «***»
},
«chat»: {
«id»: ***,
«first_name»: «***»,
«last_name»: «***»,
«username»: «***»,
«type»: «private»
},
«date»: 1618994920,
«text»: «Inline Keyboard markup test-1»,
«reply_markup»: {
«inline_keyboard»: [
[
{
«text»: «Принято»,
«callback_data»: «yes»
}
]
]
}
}
}
Популярные сообщения из этого блога
Получение access token и refresh token для работы с API Яндекс.Маркета
Для разнообразия — токены получим для приложения, зарегистрированного на Яндекс-аккаунте, отличном от аккаунта администратора магазина. Сам доступ предоставляется под администратором магазина. Согласно документации https://yandex.ru/dev/oauth/doc/dg/concepts/about.html , реализовать получение токенов можно одним из двух способов. Первый способ — извлечение из URL — согласно документации не дает refresh-токена. Второй способ выдает refresh_token и access_token — поэтому используем его: https://yandex.ru/dev/oauth/doc/dg/reference/auto-code-client.html#auto-code-client . 1) Под учеткой, отличной от xxxxx@yandex.ru, регистрируем приложение как описано в предыдущем сообщении блога . 2) Авторизуемся в браузере на Яндексе под учеткой xxxxx@yandex.ru и переходим по ссылке https://oauth.yandex.ru/authorize?response_type=code&client_id=<AppID>* *<AppID> в URL — это ID приложения, которое можно посмотреть, зайдя под учеткой создателя приложения на страницу https://oauth.ya
Обновление access token с помощью refresh token Яндекс OAuth
На предыдущих шагах создали приложение , получили access и refresh tokens tokens . Когда подойдет срок, чтобы не нарваться на просрочку access token, нужно сделать запрос на его обновление. Действуем согласно инструкции https://yandex.ru/dev/oauth/doc/dg/reference/refresh-client.html Делаем запрос на https://oauth.yandex.ru/token POST /token HTTP/1.1 Host: oauth.yandex.ru Content-Type: application/x-www-form-urlencoded Content-Length: 186 grant_type=refresh_token&refresh_token=1%3AzpzHp0i1****2eo1%3AKIxHrbr1rfW2I4Ee4Smvnj5bSGUJrzM7CaOhCq-rBmyEBpvC7chW%3A3OWudeVnRArytcQ_q1Wh1A&client_id=555960e***&client_secret=5a60e11c*** { «access_token» : «AQ***cLKH0UUTQtw0T7hhbSIC96eHg» , «expires_in» : 31531927 , «refresh_token» : «1:EH2A2px***oGj:dD***x45fBGjgNNa0usqTQz-_wmcgpPNlbyZXXgXOB:ncE1G_bbYZlXriqLl-dFbQ» , «token_type» : «bearer» } Поскольку времени с момента первой выдачи данн
lol_and_lol 0 / 0 / 0 Регистрация: 23.12.2021 Сообщений: 1 |
||||
1 |
||||
23.12.2021, 17:04. Показов 1733. Ответов 2 Метки нет (Все метки)
Проблема следующая, я в python не селён, но пару раз писал ботов для Telegram. А тут у меня вдруг ошибка — ERROR — TeleBot: «A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: can’t parse inline keyboard button: Text buttons are unallowed in the inline keyboard». Я так понимаю что указал несуществующую клавиатуру, но дважды пробежал глазами по коду и не вижу ошибки. Помогите пожалуйста.
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
23.12.2021, 17:04 |
Ответы с готовыми решениями: Как написать регулярное выражение для выдергивания английских букв и символов: «+», «,», «:», «-«, » «, «!», «?» и «.»
Не работают следующие клавиши — «ю», «д», «щ», «9», «Ф10», «Ф11». делаю бота телеграм на python, Traceback (most recent call last): File «D:/bott/bot.py», line 3, in <module> impor Цель — при нажатии на кнопку создать еще одну кнопку. Ошибка «Button» не содержит определения для «Location» и «Text»» 2 |
Автоматизируй это! 6481 / 4174 / 1140 Регистрация: 30.03.2015 Сообщений: 12,325 Записей в блоге: 29 |
|
23.12.2021, 17:51 |
2 |
не селён
Я так понимаю что указал несуществующую клавиатуру нет. просто переведи текст, это просто.
Text buttons are unallowed in the inline keyboard вот этот
0 |
3425 / 2069 / 558 Регистрация: 02.09.2015 Сообщений: 5,298 |
|
23.12.2021, 18:03 |
3 |
Не по теме:
я в python не селён Кликните здесь для просмотра всего текста
1 |