Telegram error badrequest inline keyboard expected

To help you get started, we've selected a few aiogram.utils.exceptions.BadRequest examples, based on popular ways it is used in public projects.
github aiogram / aiogram / aiogram / utils / exceptions.py View on Github external
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
github aiogram / aiogram / aiogram / utils / exceptions.py View on Github external
"""
    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'

github aiogram / aiogram / aiogram / utils / exceptions.py View on Github external
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'
github aiogram / aiogram / aiogram / utils / exceptions.py View on Github external
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'
github aiogram / aiogram / aiogram / bot / api.py View on Github external
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}]")
github aiogram / aiogram / aiogram / utils / exceptions.py View on Github external
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'
github aiogram / aiogram / aiogram / utils / exceptions.py View on Github external
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):
github aiogram / aiogram / aiogram / utils / exceptions.py View on Github external
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'
github aiogram / aiogram / aiogram / utils / exceptions.py View on Github external
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
github aiogram / aiogram / aiogram / utils / exceptions.py View on Github external
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». Я так понимаю что указал несуществующую клавиатуру, но дважды пробежал глазами по коду и не вижу ошибки. Помогите пожалуйста.

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
mport telebot
import configure
from telebot import types
 
client = telebot.TeleBot(configure.config['token'])
 
 
@client.message_handler(commands=['get_info', 'info'])
def get_user_info(message):
    markup_inline = types.InlineKeyboardMarkup()
    item_yes = types.InlineKeyboardButton(text='ДА', callback_bata='yes')
    item_no = types.InlineKeyboardButton(text='НЕТ', callback_bata='no')
 
    markup_inline.add(item_yes, item_no)
    client.send_message(message.chat.id, 'you know',
                        reply_markup=markup_inline
                        )
 
 
@client.callback_query_handler(func=lambda call: True)
def answer(call):
    if call.data == 'yes':
        markup_reply = types.ReplyKeyboardMarkup(resize_keyboard=True)
        item_id = types.KeyboardButton('ID')
        item_username = types.KeyboardButton('name')
 
        markup_reply.add(item_id, item_username)
        client.send_message(call.message.chat.id, 'press button',
                            reply_markup=markup_reply
                            )
    elif call.data == 'no':
        pass
 
 
@client.message_handler(content_types=['text'])
def get_text(message):
    if message.text == 'ID':
        client.send_message(message.chat.id, f'Your ID: {message.from_user.id}')
    elif message.text == 'name':
        client.send_message(message.chat.id, f'Your name: {message.from_user.first_name} {message.from_user.last_name}')
 
 
client.polling(none_stop=True, interval=0)

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

23.12.2021, 17:04

Ответы с готовыми решениями:

Как написать регулярное выражение для выдергивания английских букв и символов: «+», «,», «:», «-«, » «, «!», «?» и «.»
Не могу ни как собразить как написать регулярное выражение для выдергивания английских букв и…

Составить программу по управлению манипулятором «мышь». Выбор типа курсора организовать по нажатию на клавиши «q»,»w»,»r
Составить программу по управлению манипулятором &quot;мышь&quot;. Выбор типа курсора организовать по нажатию…

Не работают следующие клавиши — «ю», «д», «щ», «9», «Ф10», «Ф11».
У меня проблема с клавиатурой:cry:, не работают следующие клавиши — &quot;ю&quot;, &quot;д&quot;, &quot;щ&quot;, &quot;9&quot;,…

делаю бота телеграм на python, Traceback (most recent call last): File «D:/bott/bot.py», line 3, in <module> impor
делаю бота телеграм на python
вот ошибки
Traceback (most recent call last):
File…

Цель — при нажатии на кнопку создать еще одну кнопку. Ошибка «Button» не содержит определения для «Location» и «Text»»
int Control ;
private void Button2_Click(object sender, RoutedEventArgs e)
{…

2

Автоматизируй это!

Эксперт Python

6481 / 4174 / 1140

Регистрация: 30.03.2015

Сообщений: 12,325

Записей в блоге: 29

23.12.2021, 17:51

2

Цитата
Сообщение от lol_and_lol
Посмотреть сообщение

не селён

Цитата
Сообщение от lol_and_lol
Посмотреть сообщение

Я так понимаю что указал несуществующую клавиатуру

нет. просто переведи текст, это просто.

Цитата
Сообщение от lol_and_lol
Посмотреть сообщение

Text buttons are unallowed in the inline keyboard

вот этот



0



3425 / 2069 / 558

Регистрация: 02.09.2015

Сообщений: 5,298

23.12.2021, 18:03

3

Не по теме:

Цитата
Сообщение от lol_and_lol
Посмотреть сообщение

я в python не селён

Кликните здесь для просмотра всего текста

Ошибка "несуществующей клавиши" для бота Telegram на python



1



Понравилась статья? Поделить с друзьями:
  • Telegram error 403 forbidden bot was blocked by the user
  • Telegram error 401 bot token is required
  • Telegram connection error
  • Telegram bot webhook wrong response from the webhook 500 internal server error
  • Telegram bot ssl error