Входящие запросы (API)

В данной статье рассмотрим виды и параметры входящих запросов
В этой статье

В данной статье разобрана документация Входящих запросов от PuzzleBot, при необходимости вы можете ознакомиться с документацией по Исходящим запросам: Исходящие запросы (API).

1d0f2b80c86ce450917950c746a1c7cf.png

Для настройки Входящих запросов необходимо сгенерировать API токен (Бот — Настройки — Интеграции — Входящие запросы).

Важно! Не путать с API ключом от бота из @BotFather.

 

Формат

Формат запроса: 
https://api.puzzlebot.top/?token=ТОКЕН_API&method=НАЗВАНИЕ_МЕТОДА

Пример запроса:
https://api.puzzlebot.top/?token=WOPJL9thftfGtw65NBfVEXEj24qvZ1bj&method=getLinkActivations&link_id=5556&page=1

С помощью данного запроса можно получить Список пользователей перешедших по ссылке (getLinkActivations) с конкретным идентификатором (link_id=5556) состоящий из данных вмещающихся на первую страницу (page=1).

В адрес для отправки запросов необходимо подставить (без пробелов):

  • ТОКЕН_API — генерируется в Настройках Бота на вкладке Интеграции.
  • НАЗВАНИЕ_МЕТОДА — все методы (пример: getLinkActivations) и их параметры (пример: link_id и page).

Параметры передаются через POST или GET методы, а ответ приходит в формате JSON.

Важно! Всего можно выполнить 120 запросов в минуту.

 

Методы

Telegram

  • tg.* — любой запрос из Telegram Bot API, где на месте * любой запрос из Telegram Bot API с использованием формата официальной документации, например:

    method: tg.unpinAllChatMessages
    params:
       chat_id - number, Telegram id of chat, bot id for private

    success result: code = 0, data = Array of all API methods
     

Важно! Через методы sendPhoto, sendAudio, sendDocument, sendVideo, sendAnimation, sendVoice, sendVideoNote, sendPaidMedia, sendMediaGroup отправлять файлы в формате multipart/form-data НЕЛЬЗЯ! Используйте для этого API Telegram и соответствующие методы.

Системные

  • Помощь (вывод доступных методов):
    method: help
    params: no

    success result: code = 0, data = Array of all API methods
     
  • Тест:
    method: test
    params: no

    success result: code = 0, data = test text with your request params
     

Общие

Модерация
 

  • Получение списка пользователей:
    method: getUsersInChat
    params:
       chat_id - number, Telegram id of chat, bot id for private
       page - number, page number starts with 1, a page have max 200 rows
       category_id - number, id of category for filter users, optional param

    success result: code = 0, data = Array of users [user_id, first_name, last_name, username]
     
  • Получение информации о пользователе:
    method: getUserInChatStatus
    params:
       user_id - number, Telegram id of user
       chat_id - number, Telegram id of chat, bot id for private
       page - number, page number starts with 1, a page have max 50 rows

    success result: code = 0, data = Object[user_id, chat_id, first_name, last_name, username, joined (1 = joined, 0 = left, 2 = banned), joined_date, left_date, ban_date, categories - Array of categories ids]
     
  • Блокировка пользователя (бан):
    method: userBan
    params: 
       tg_chat_id - number, Telegram id of chat
       user_id - number, Telegram id of user
       until_date - number, timestamp of end ban date

    success result: code = 0, data = "ok"
     
  • Разблокировка пользователя (разбан):
    method: userUnban
    params:
       tg_chat_id - number, Telegram id of chat
       user_id - number, Telegram id of user

    success result: code = 0, data = "ok"
     

Постинг
 

  • Получение списка отправленных постов:
    method: getPostsList
    params:
       page - number, page number starts with 1, a page have max 50 rows

    success result: code = 0, data = Array of posts [id, date_sent]
     
  • Отправка поста:
    method: postSend
    params:
       chats_ids - array of Telegram chats ids with separator "," (without quotes), "private" for send to all private chats
       categories_ids - array of categories ids with separator "," (without quotes) for filter users in private chats
       type - "message" (for send text message) | "media" (for send video / photo / audio) / "only_command" (for send command from post actions)
       file_id - string, file id from Telegram for media type
       text - string, text of message for message type or caption for media type
       pin_post - boolean, pin post after send if it's true, false by default
       command_name - text, attach command to the post, no by default
       date - string, date in UTC format (19.04.2024 20:30 or 2024-04-19 20:30) or timestamp

    success result: code = 0, data = "ok"
     
  • Удалить отправленный пост:
    method: postDelete
    params:
       post_id - number, post_id for delete

    success result: code = 0, data = "ok"
     

Категории
 

  • Получение списка категорий:
    method: getChatCategories
    params:
       tg_chat_id - number, Telegram id of chat, bot id for private

    success result: code = 0, data = Array of categories [id, name, is_main]
     
  • Изменить категории пользователю (за один запрос):
    method: categoriesChange
    params:
       user_id - number, Telegram id of user
       categories - JSON encoded Object[add_categories = Array[[chat_id, category_id],[...]], delete_categories = Array[[chat_id, category_id],[...]], replace = boolean]

    success result: code = 0, data = "ok"
     
  • Создание категории:
    method: createChatCategory
    params:
       tg_chat_id - number, Telegram id of chat, bot id for private
       name - string, name for new category

    success result:
    code = 0, data = id of new categor
     
  • Добавить категорию пользователю:
    method: categoryAdd
    params:
       user_id - number, Telegram id of user
       tg_chat_id - number, Telegram id of chat, bot id for private
       category_id - number, id of category

    success result: code = 0, data = "ok"
     
  • Удалить категорию пользователю:
    method: categoryDelete
    params:
       user_id - number, Telegram id of user
       tg_chat_id - number, Telegram id of chat, bot id for private
       category_id - number, id of category

    success result: code = 0, data = "ok"
     
  • Заменить все категории пользователя на указанную:
    method: categoryReplace
    params:
       user_id - number, Telegram id of user
       tg_chat_id - number, Telegram id of chat, bot id for private
       category_id - number, id of category

    success result: code = 0, data = "ok"
     

Сценарии
 

  • Получение списка сценариев:
    method: getScenariosList
    params:
       page - number, page number starts with 1, a page have max 50 rows

    success result: code = 0, data = Array of scenarios [id, name]
     
  • Изменить состояние сценариев пользователю:
    method: scenariosChange
    params:
       user_id - number, Telegram id of user
       scenarios - JSON encoded Array[scenario_id : state (0 - for stop, 1 - for start)] 

    success result: code = 0, data = "ok"
     
  • Запустить сценарий пользователю:
    method: scenarioRun
    params:
       user_id - number, Telegram id of user
       scenario_id - number, id of scenario

    success result: code = 0, data = "ok"
     
  • Остановить сценарий пользователю:
    method: scenarioStop
    params:
       user_id - number, Telegram id of user
       scenario_id - number, id of scenario

    success result: code = 0, data = "ok"
     

Вход
 

  • Получение списка ссылок:
    method: getLinksList
    params:
       page - number, page number starts with 1, a page have max 50 rows

    success result: code = 0, data = Array of links [id, name, type, variable, max_activations, max_links, enabled]
     
  • Получение списка пользователей по конкретной ссылке:
    method: getLinkActivations
    params:
       link_id - number, id of link
       page - number, page number starts with 1, a page have max 50 rows

    success result: code = 0, data = Array of links activations [link_id, link_key, link_owner_tg_user_id, user_id, date]
     

Переменные
 

  • Изменить переменную:
    method: variableChange
    params:
       variable - string, name of variable
       expression - string, expression for calc value
       user_id - number, Telegram id of user for change personal variable

    success result: code = 0, data = "ok"
     
  • Получение значения переменной:
    method: getVariableValue
    params:
       variable - string, name of variable
       user_id - number, Telegram id of user for get personal variable value

    success result: code = 0, data = "Variable value"
     
  • Очистить переменную:
    method: variableClear
    params:
       variable - string, name of variable
       user_id - number, Telegram id of user for change personal variable

    success result: code = 0, data = "ok"
      

Таблицы Google

 

  • Получить содержимое Google таблицы в формате JSON (только для привязанных аккаунтов):  
    method: getSpreadSheetRows
    params:
       spreadsheet_id - string, id of spreadsheet
       email - string, email for request
       sheets_ids - string, ids of sheets with separator "," (without quotes) (default no set, get all sheets)
       get_rows_cache_time - number, cache time of rows in seconds (default 5, max 86400)
       get_sheets_cache_time - number, cache time of sheets in seconds (default 5, max 86400)

    success result: code = 0, data = Array of spreadsheets objects [sheet_id, sheet_title, rows]

 

Магазин
 

  • Получение списка товаров:
    method: getShopItemsList
    params:
       page - number, page number starts with 1, a page have max 50 rows

    success result: code = 0, data = Array of items [id, name, article, count_left]
     
  • Изменить остатки товара:
    method: shopItemChangeCountLeft
    params:
    item_id - number, id of shop item
    count_left - number, new count left for item (-1 for infinity)

    success result: code = 0, data = "ok"

Только для ботов

  • Привязать бота:
    method: botConnect
    params: no

    success result: code = 0, data = "ok"
     
  • Отвязать бота:
    method: botDisconnect
    params: no

    success result: code = 0, data = "ok"
     
  • Включить бота:
    method: botEnable
    params: no

    success result: code = 0, data = "ok"
     
  • Выключить бота:
    method: botDisable
    params: no

    success result: code = 0, data = "ok"
     
  • Получить список чатов:
    method: getChatsList
    params: no

    success result: code = 0, data = Array of chats [chat_id, tg_chat_id, title, description, type]
     
  • Скачать файл:
    method: downloadFile
    params: file_id - string, Telegram id of file to download

    success result: Output file with "Content-Type: application/octet-stream"
     

Конструктор
 

  • Получить список команд и условий:
    method: getCommandsList
    params: no

    success result: code = 0, data = Array of commands [id, name, group_id]
     
  • Получить список групп команд:
    method: getCommandsGroupsList
    params: no

    success result: code = 0, data = Array of commands groups [id, name]
     
  • Отправка команды или условия:
    method: sendCommand
    params:
      command_name - string, name of command or condition
      tg_chat_id - number, Telegram id of resource or user

    success result: code = 0, data = "ok"
     

Диалоги
 

  • Начать диалог:
    method: dialogStart
    params:
       user_id - number, Telegram id of user

    success result: code = 0, data = "ok"
     
  • Завершить диалог:
    method: dialogEnd
    params:
       user_id - number, Telegram id of user

    success result: code = 0, data = "ok"

Только для ресурсов

  • Принять заявку на вступление в ресурс:
    method: joinRequestApprove
    params:
       user_id - number, Telegram id of user
       tg_chat_id - number, Telegram id of resource

    success result: code = 0, data = "ok"
     
  • Отклонить заявку на вступление в ресурс:
    method: joinRequestDecline
    params:
       user_id - number, Telegram id of user
       tg_chat_id - number, Telegram id of resource

    success result: code = 0, data = "ok"
     
  • Удаление пользователя (кик):
    method: userKick
    params:
       tg_chat_id - number, Telegram id of chat
       user_id - number, Telegram id of user

    success result:code = 0, data = "ok"
     

Триггеры (только для групп)
 

  • Получение списка триггеров:
    method: getTriggersList
    params:
       page - number, page number starts with 1, a page have max 50 rows

    success result: code = 0, data = Array of triggers [id, chat_id, name, enabled]
     
  • Отправка триггера:
    method: triggerSend
    params:
       trigger_id - number, id of trigger
       user_id - number, Telegram id of user

    success result: code = 0, data = "ok"

 

Ошибки

code =   1  — Wrong token format!

code =   2  — Wrong method format!

code =   3  — Token not found!

code =   4  — Unknown method!

code =  40  — No "tg_chat_id" param! | No "user_id" param!

code =  50  — Set webhook error!

code =  51  — Delete webhook error!

code = 100  — Internal error!

code = 102  — Variable evaluate exception!

code = 104  — Variable not found!

code = 200  — Command / condition not found!

code = 201  — User not found!

code = 202  — Chat not found!

code = 203  — User in chat not found!

code = 204  — Post not found!

code = 205  — Post is not sent!

code = 207  — Trigger not found!

code = 208  — Can't approve join request!

code = 209  — Can't decline join request!

code = 210  — Category not found!

code = 211  — Unknown type of post!

code = 212  — Empty chats!

code = 429  — Too many queries per minute!/Too many queries per month