Перейти к содержанию

Спецификация OpenAPI (Telegram Webhook API)

Спецификация описывает контракты взаимодействия с методами Telegram Bot API для управления вебхуком (setWebhook, getWebhookInfo, deleteWebhook), а также формат входящих событий (обратных вызовов callbacks / Update).


Интерактивная документация

Вы можете просмотреть интерактивную документацию через Swagger UI или скачать файл спецификации:


Описание эндпоинтов

1. POST /bot{token}/setWebhook

Регистрация публичного HTTPS URL для приёма обновлений от Telegram Bot API.

  • Параметры пути:
    • token (string, обязательный) — секретный токен вашего бота.
  • Тело запроса (Content-Type):
    • application/json (BaseWebhook) — стандартная установка без собственного SSL-сертификата.
    • multipart/form-data (WebhookWithCertificate) — установка с передачей файла самоподписанного сертификата (certificate).
  • Callbacks (onUpdate):
    • Telegram отправляет событие Update на указанный в теле запроса url методом POST с передачей секретного токена в заголовке X-Telegram-Bot-Api-Secret-Token.

2. GET /bot{token}/getWebhookInfo

Получение текущего статуса вебхука, адреса, даты последней ошибки и количества ожидающих обновлений.

  • Параметры пути:
    • token (string, обязательный) — токен бота.
  • Ответ (200 OK):
    • WebhookInfo со сведениями о состоянии доставки и синхронизации.

3. POST /bot{token}/deleteWebhook

Удаление текущей интеграции с вебхуком и опциональный сброс очереди сообщений.

  • Query-параметры:
    • drop_pending_updates (boolean, опционально) — сбросить все ожидающие обновления.

Модели данных

Спецификация описывает ключевые схемы данных Telegram Bot API:

  • Update — входящее событие от Telegram (update_id, входящее или изменённое сообщение, пост в канале, нажатие inline-кнопки).
  • CallbackQuery — запрос при нажатии на inline-кнопку (id, автор from, сообщение message, данные data).
  • Message — сообщение (message_id, автор from, чат chat, дата отправки и текст).
  • Chat — данные чата (тип private / group / supergroup / channel, ID и название).
  • User — профиль пользователя или бота (ID, имя, username, статус бота).
  • WebhookInfo — статус вебхука, адрес доставки, дата последней ошибки и число ожидающих сообщений.

Исходная спецификация (OpenAPI 3.0.3)

Показать YAML-спецификацию целиком
openapi: 3.0.3
info:
  title: "Telegram Bot API - Webhook Integration"
  version: 1.0.0
  description: "OpenAPI-спецификация методов управления вебхуком Telegram Bot API (setWebhook, getWebhookInfo, deleteWebhook) и обратного вызова onUpdate."
servers:
  - url: "https://api.telegram.org"
    description: "Сервер Telegram Bot API"
paths:
  /bot{token}/setWebhook:
    post:
      summary: "Установка вебхука"
      operationId: setWebhook
      tags:
        - Webhook
      parameters:
        - in: path
          name: token
          required: true
          description: "Токен бота Telegram"
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/BaseWebhook"
          multipart/form-data:
            schema:
              $ref: "#/components/schemas/WebhookWithCertificate"
      callbacks:
        onUpdate:
          "{$request.body#/url}":
            post:
              summary: "Входящее обновление от Telegram"
              description: "Telegram отправляет событие Update на переданный URL"
              security:
                - SecretTokenHeader: []
              parameters:
                - in: header
                  name: X-Telegram-Bot-Api-Secret-Token
                  required: true
                  description: "Секретный токен, заданный в поле secret_token при вызове setWebhook, который проверяет Nginx для верификации входящих запросов от Telegram"
                  schema:
                    type: string
                    minLength: 1
                    maxLength: 256
                    pattern: "^[A-Za-z0-9_-]+$"
              requestBody:
                required: true
                content:
                  application/json:
                    schema:
                      $ref: "#/components/schemas/Update"
              responses:
                "200":
                  description: "Сервер успешно принял и обработал обновление"
                "403":
                  description: "Доступ запрещён: неверный или отсутствующий заголовок X-Telegram-Bot-Api-Secret-Token"
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Success"
          description: "Вебхук успешно установлен"
        "400":
          description: "Некорректный запрос (неверный формат параметров или недопустимый URL вебхука)"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                ok: false
                error_code: 400
                description: "Bad Request: HTTPS url must be provided for webhook"
        "401":
          description: "Не авторизован (неверный токен бота)"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                ok: false
                error_code: 401
                description: "Unauthorized"
        "404":
          description: "Бот не найден (несуществующий токен)"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                ok: false
                error_code: 404
                description: "Not Found"
        "429":
          description: "Превышен лимит запросов (Too Many Requests)"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                ok: false
                error_code: 429
                description: "Too Many Requests: retry after 30"
                parameters:
                  retry_after: 30
        default:
          description: "Непредвиденная ошибка"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /bot{token}/deleteWebhook:
    post:
      summary: "Удаление вебхука"
      operationId: deleteWebhook
      tags:
        - Webhook
      parameters:
        - in: path
          name: token
          required: true
          description: "Токен бота Telegram"
          schema:
            type: string
        - in: query
          name: drop_pending_updates
          required: false
          description: "Если передано значение true, сбрасывает все накопившиеся обновления"
          schema:
            type: boolean
            default: false
            example: false
      responses:
        "200":
          description: "Вебхук успешно удалён"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Success"
        "400":
          description: "Некорректный запрос"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                ok: false
                error_code: 400
                description: "Bad Request: query parameter error"
        "401":
          description: "Не авторизован (неверный токен бота)"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                ok: false
                error_code: 401
                description: "Unauthorized"
        "404":
          description: "Бот не найден (несуществующий токен)"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                ok: false
                error_code: 404
                description: "Not Found"
        "429":
          description: "Превышен лимит запросов (Too Many Requests)"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                ok: false
                error_code: 429
                description: "Too Many Requests: retry after 30"
                parameters:
                  retry_after: 30
        default:
          description: "Непредвиденная ошибка"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
  /bot{token}/getWebhookInfo:
    get:
      summary: "Получение статуса вебхука"
      operationId: getWebhookInfo
      tags:
        - Webhook
      parameters:
        - in: path
          name: token
          required: true
          description: "Токен бота Telegram"
          schema:
            type: string
      responses:
        "200":
          description: "Информация о текущем состоянии вебхука"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookInfoResponse"
        "400":
          description: "Некорректный запрос"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                ok: false
                error_code: 400
                description: "Bad Request"
        "401":
          description: "Не авторизован (неверный токен бота)"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                ok: false
                error_code: 401
                description: "Unauthorized"
        "404":
          description: "Бот не найден (несуществующий токен)"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                ok: false
                error_code: 404
                description: "Not Found"
        "429":
          description: "Превышен лимит запросов (Too Many Requests)"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              example:
                ok: false
                error_code: 429
                description: "Too Many Requests: retry after 30"
                parameters:
                  retry_after: 30
        default:
          description: "Непредвиденная ошибка"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

components:
  securitySchemes:
    SecretTokenHeader:
      type: apiKey
      in: header
      name: X-Telegram-Bot-Api-Secret-Token
      description: "Секретный токен для верификации запросов от Telegram на стороне Nginx"
  schemas:
    BaseWebhook:
      type: object
      required:
        - url
      properties:
        url:
          type: string
          format: uri
          description: "HTTPS URL сервера, на который Telegram будет отправлять обновления"
          example: "https://your-domain.com/bot-webhook"
        ip_address:
          type: string
          description: "IP-адрес сервера"
          format: ipv4
          example: "197.0.2.1"
        max_connections:
          type: integer
          description: "Максимальное количество одновременных HTTPS-подключений к вебхуку для доставки обновлений (от 1 до 100, по умолчанию 40)"
          maximum: 100
          minimum: 1
          default: 40
        allowed_updates:
          type: array
          description: "Список типов обновлений, которые должен получать бот. По умолчанию или при передаче пустого массива доставляются все типы обновлений, кроме chat_member, message_reaction и message_reaction_count"
          items:
            type: string
          example:
            - "message"
            - "callback_query"
        drop_pending_updates:
          type: boolean
          description: "Если передано значение true, сбрасывает все накопившиеся обновления"
        secret_token:
          type: string
          description: "Секретный токен для верификации входящих запросов от Telegram"
          maxLength: 256
          minLength: 1
          pattern: "^[A-Za-z0-9_-]+$"
          example: "a1b2c3d4e5f67890123456789abcdef0a1b2c3d4e5f67890123456789abcdef0"
    WebhookWithCertificate:
      allOf:
        - $ref: "#/components/schemas/BaseWebhook"
        - type: object
          properties:
            certificate:
              type: string
              format: binary
              description: "Публичный SSL/TLS-сертификат сервера. Передаётся при использовании самоподписанного сертификата"
    WebhookInfo:
      type: object
      required:
        - url
        - has_custom_certificate
        - pending_update_count
      properties:
        url:
          type: string
          description: "URL сервера, на который Telegram отправляет обновления. Необходимо, чтобы телеграмм отправлял запрос на порты 443, 80, 88 или 8443"
        has_custom_certificate:
          type: boolean
          description: "Принимает значение true, если для проверки вебхука загружен самоподписанный сертификат"
          example: false
        pending_update_count:
          type: integer
          description: "Количество ожидающих доставки обновлений"
          example: 0
        ip_address:
          type: string
          description: "IP-адрес сервера"
          format: ipv4
          example: "197.0.2.1"
        last_error_date:
          type: integer
          format: int64
          description: "Дата и время последней ошибки при доставке обновления (Unix time)"
        last_error_message:
          type: string
          description: "Описание последней ошибки при доставке обновления"
        last_synchronization_error_date:
          type: integer
          format: int64
          description: "Дата и время последней ошибки синхронизации (Unix time)"
          example: 0
        max_connections:
          type: integer
          description: "Максимальное количество одновременных подключений к вебхуку"
          example: 40
        allowed_updates:
          type: array
          description: "Список типов обновлений, на которые подписан бот. По умолчанию или при передаче пустого массива доставляются все типы обновлений, кроме chat_member, message_reaction и message_reaction_count"
          items:
            type: string
          example:
            - "message"
            - "callback_query"
    WebhookInfoResponse:
      type: object
      required:
        - result
        - ok
      properties:
        ok:
          type: boolean
          example: true
        result:
          $ref: "#/components/schemas/WebhookInfo"
    Error:
      type: object
      required:
        - ok
        - error_code
        - description
      properties:
        parameters:
          type: object
          description: "Дополнительные параметры ошибки"
          properties:
            retry_after:
              type: integer
              description: "Время в секундах, через которое можно повторить запрос"
            migrate_to_chat_id:
              type: integer
              format: int64
              description: "ID чата, на который нужно перенаправить запрос"
        ok:
          type: boolean
          example: false
        error_code:
          type: integer
        description:
          type: string
    Success:
      type: object
      required:
        - result
        - ok
      properties:
        result:
          type: boolean
        ok:
          type: boolean
        description:
          type: string
    User:
      type: object
      required:
        - id
        - is_bot
        - first_name
      properties:
        id:
          type: integer
          format: int64
        is_bot:
          type: boolean
        first_name:
          type: string
        last_name:
          type: string
        username:
          type: string
        language_code:
          type: string
        is_premium:
          type: boolean
        added_to_attachment_menu:
          type: boolean
        can_join_groups:
          type: boolean
        can_read_all_group_messages:
          type: boolean
        supports_inline_queries:
          type: boolean
        can_connect_to_business:
          type: boolean
        has_main_web_app:
          type: boolean
        has_topics_enabled:
          type: boolean
        allows_users_to_create_topics:
          type: boolean
        can_manage_bots:
          type: boolean
        supports_join_request_queries:
          type: boolean
    Chat:
      type: object
      required:
        - id
        - type
      properties:
        id:
          type: integer
          format: int64
          description: "Уникальный ID чата (у супергрупп и каналов отрицательный)"
          example: -1001234567890
        type:
          type: string
          description: "Тип чата"
          enum:
            - private
            - group
            - supergroup
            - channel
          example: "private"
        title:
          type: string
          description: "Название (для групп и каналов)"
          example: "Чат разработчиков"
        username:
          type: string
          description: "Username канала/группы (если публичный)"
        first_name:
          type: string
          description: "Имя собеседника (для личных чатов)"
        last_name:
          type: string
          description: "Фамилия собеседника (для личных чатов)"
        is_forum:
          type: boolean
          description: "Принимает значение true, если в супергруппе включены темы (форум)"
        is_direct_messages:
          type: boolean
          description: "Принимает значение true, если чат является чатом личных сообщений канала (Direct Messages)"
    Message:
      type: object
      required:
        - message_id
        - date
        - chat
      properties:
        message_id:
          type: integer
          description: "Уникальный ID сообщения в рамках чата"
          example: 42
        date:
          type: integer
          format: int64
          description: "Дата отправки (Unix timestamp)"
          example: 1716382910
        chat:
          $ref: "#/components/schemas/Chat"
        from:
          $ref: "#/components/schemas/User"
        text:
          type: string
          description: "Текст сообщения"
          example: "Привет, бот!"
    Update:
      type: object
      required:
        - update_id
      properties:
        update_id:
          type: integer
          description: "Уникальный ID обновления (инкрементируется)"
          example: 1000001
        message:
          $ref: "#/components/schemas/Message"
        edited_message:
          $ref: "#/components/schemas/Message"
        channel_post:
          $ref: "#/components/schemas/Message"
        edited_channel_post:
          $ref: "#/components/schemas/Message"
        callback_query:
          $ref: "#/components/schemas/CallbackQuery"
    CallbackQuery:
      type: object
      required:
        - id
        - from
        - chat_instance
      properties:
        id:
          type: string
          description: "Уникальный идентификатор запроса"
        from:
          $ref: "#/components/schemas/User"
        message:
          $ref: "#/components/schemas/Message"
        inline_message_id:
          type: string
          description: "Уникальный идентификатор inline-сообщения."
        chat_instance:
          type: string
          description: "Уникальный идентификатор чата, в котором был вызван запрос"
        data:
          type: string
          description: "Данные, отправленные пользователем при нажатии на inline-кнопку"