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

Для настройки Входящих запросов необходимо сгенерировать API токен (Бот — Настройки — Интеграции — Входящие запросы).
Важно! Не путать с API ключом от бота из @BotFather или API ключом от бота в MAX. API токен принадлежит проекту и действует одновременно для бота в Telegram и для бота в MAX.
Формат
Формат запроса для Telegram: https://api.puzzlebot.top/?token=ТОКЕН_API&method=НАЗВАНИЕ_МЕТОДА&platform=tg
Формат запроса для Max: https://api.puzzlebot.top/?token=ТОКЕН_API&method=НАЗВАНИЕ_МЕТОДА&platform=max
Отличие формата для мессенджеров в параметре platform, в котором значение в "tg" для Telegram и "max" для Max. Если параметр platform не указан, то значение по умолчанию будет "tg".
Пример запроса:https://api.puzzlebot.top/?token=WOPJL9thftfGtw65NBfVEXEj24qvZ1bj&method=getLinkActivations&link_id=5556&page=1&platform=tg
С помощью данного запроса можно получить Список пользователей перешедших по ссылке (getLinkActivations) с конкретным идентификатором (link_id=5556) состоящий из данных вмещающихся на первую страницу (page=1), для платформы Telegram (platform=tg).
В адрес для отправки запросов необходимо подставить (без пробелов):
ТОКЕН_API — генерируется в Настройках Бота на вкладке Интеграции.
НАЗВАНИЕ_МЕТОДА — все методы (пример:
getLinkActivations,max.sendMessage,tg.sendMessage)) и их параметры (пример:link_idиpage).platform — целевая платформа:
tg(Telegram) илиmax(MAX).
Если параметр не передан, то по умолчанию равенtg, (нужно для сохранения обратной совместимости старых интеграций).
Если запрос выполняется к боту или пользователю в MAX, передача параметраplatform=maxявляется обязательной.
Параметры передаются через POST или GET методы, а ответ приходит в формате JSON.
Важно! Всего можно выполнить 120 запросов в минуту.
Формат ответов (JSON) и универсальные поля:
Для указания идентификатора чата или ресурса в методах puzzlebot используется универсальный параметр platform_chat_id (для Telegram также сохраняется поддержка tg_chat_id).
В ответах на запросы идентификаторы чатов и ботов теперь возвращаются с префиксом соответствующей платформы (tg_chat_id для Telegram или max_chat_id для MAX), а также дублируются в универсальных полях platform_*:
platform_chat_id— ID пользователя/чата/ресурса на платформе;platform_bot_id— ID бота на платформе.
Адресация в MAX:
В личные сообщения пользователю: передавайте ID пользователя в параметр
platform_chat_id(platform_chat_id=АЙДИ_ЮЗЕРА&platform=max).В группу / канал / ресурс: передавайте ID группы или канала в параметр
platform_chat_id(platform_chat_id=АЙДИ_РЕСУРСА&platform=max).Действия с участником в группе (бан, статус, права): передавайте ID группы в
platform_chat_id, а ID участника — вuser_id(platform_chat_id=АЙДИ_РЕСУРСА&user_id=АЙДИ_ЮЗЕРА&platform=max).
Методы
Telegram
tg.*— любой запрос из Telegram Bot API, где на месте*любой запрос из Telegram Bot API с использованием формата официальной документации, например:method:tg.unpinAllChatMessagesparams:chat_id - number, Telegram id of chat, bot id for privatesuccess result: ok = true, result = true
Важно! Через методы sendPhoto, sendAudio, sendDocument, sendVideo, sendAnimation, sendVoice, sendVideoNote, sendPaidMedia, sendMediaGroup отправлять файлы в формате
multipart/form-dataНЕЛЬЗЯ! Используйте для этого API Telegram и соответствующие методы, либо передавайтеfile_id/URL.
MAX
max.* — любой запрос из MAX API, где на месте * запрос из официальной документации MAX API с использованием формата параметров, аналогичного Telegram Bot API, например:
method: max.sendMessage
params:
chat_id - number (MAX id of chat or user id for private)
text - string (message text)
platform - string ("max")
success result: ok = true, result = Object, error_code = 0, http_code = 200
Список доступных методов MAX:
max.sendMessage, max.sendPhoto, max.sendAudio, max.sendDocument, max.sendSticker, max.sendVideo, max.sendLocation, max.sendContact, max.deleteMessage, max.editMessage, max.getMe, max.getChat, max.getMeInChat, max.getVideoInfo, max.getUploadUrl, max.getChats, max.leaveChat, max.setChatTitle, max.setChatPhoto, max.pinChatMessage, max.unpinAllChatMessages, max.sendChatAction, max.banChatMember, max.promoteChatMember, max.demoteChatMember, max.getChatMember, max.addChatMember, max.getChatAdministrators, max.setWebhook, max.deleteWebhook, max.getMessage, max.answerCallbackQuery, max.sendVideoNote, max.sendMediaGroup, max.sendVoice, max.sendAnimation, max.forwardMessage
Системные
Помощь (вывод доступных методов):
method:helpparams: nosuccess result: code = 0, data = Array of all API methods
Тест:
method:testparams: nosuccess result: code = 0, data = test text with your request params
Общие методы puzzlebot
Мoдерация
Получение списка пользователей:
method: getUsersInChatparams:
platform_chat_id- number, Telegram/MAX 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
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = Array of users [user_id, first_name, last_name, username]Получение информации о пользователе:
method: getUserInChatStatusparams:
user_id- number, id of user
platform_chat_id- number, Telegram/MAX id of chat, bot id for private
page- number, page number starts with 1, a page have max 50 rows
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = Object[user_id, platform_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: userBanparams:
platform_chat_id- number, Telegram/MAX id of chat
user_id- number, id of user
until_date- number, timestamp of end ban date, optional param
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"Разблокировка пользователя (разбан):
method: userUnbanparams:
platform_chat_id- number, Telegram/MAX id of chat
user_id- number, id of user
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"
Постинг
Получение списка отправленных постов:
method: getPostsListparams:
page- number, page number starts with 1, a page have max 50 rows
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = Array of posts [id, date_sent]Отправка поста:
method: postSendparams:
chats_ids- array of platform_chat_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/MAX 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
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"Удалить отправленный пост:
method: postDeleteparams:
post_id- number, post_id for deletesuccess result: code = 0, data = "ok"
Кaтегории
Получение списка категорий:
method: getChatCategoriesparams:
platform_chat_id- number, Telegram/MAX id of chat, bot id for private
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = Array of categories [id, name, is_main]Изменить категории пользователю (за один запрос):
method: categoriesChangeparams:
user_id- number, id of user
categories- JSON encoded Object[add_categories = Array[[platform_chat_id, category_id],[...]], delete_categories = Array[[platform_chat_id, category_id],[...]], replace = boolean]
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"Создание категории:
method: createChatCategoryparams:
platform_chat_id- number, Telegram/MAX id of chat, bot id for private
name- string, name for new category
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = id of new categoryДобавить категорию пользователю:
method: categoryAddparams:
user_id- number, id of user
platform_chat_id- number, Telegram/MAX id of chat, bot id for private
category_id- number, id of category
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"Удалить категорию пользователю:
method: categoryDeleteparams:
user_id- number, id of user
platform_chat_id- number, Telegram/MAX id of chat, bot id for private
category_id- number, id of category
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"Заменить все категории пользователя на указанную:
method: categoryReplaceparams:
user_id- number, id of user
platform_chat_id- number, Telegram/MAX id of chat, bot id for private
category_id- number, id of category
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"
Сцeнарии
Получение списка сценариев:
method: getScenariosListparams:
page- number, page number starts with 1, a page have max 50 rows
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = Array of scenarios [id, name]Изменить состояние сценариев пользователю:
method: scenariosChangeparams:
user_id- number, id of user
scenarios- JSON encoded Array[scenario_id : state (0 - for stop, 1 - for start)]
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"Запустить сценарий пользователю:
method: scenarioRunparams:
user_id- number, id of user
scenario_id- number, id of scenario
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"Остановить сценарий пользователю:
method: scenarioStopparams:
user_id- number, id of user
scenario_id- number, id of scenario
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"
Вход
Получение списка ссылок:
method: getLinksListparams:
page- number, page number starts with 1, a page have max 50 rows
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = Array of links [id, name, type, variable, max_activations, max_links, enabled]Получение списка пользователей по конкретной ссылке:
method: getLinkActivationsparams:
link_id- number, id of link
page- number, page number starts with 1, a page have max 50 rows
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = Array of links activations [link_id, link_key, link_owner_tg_user_id, user_id, date]
Переменные
Изменить переменную:
method: variableChangeparams:
variable- string, name of variable
expression- string, expression for calc value
user_id- number, id of user for change personal variable (optional)
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"Получение значения переменной:
method: getVariableValueparams:
variable- string, name of variable
user_id- number, id of user for get personal variable value (optional)
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "Variable value"Очистить переменную:
method: variableClearparams:
variable- string, name of variable
user_id- number, id of user for change personal variable (optional)
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"
Таблицы Google
Получить содержимое Google таблицы в формате JSON (только для привязанных аккаунтов):
method: getSpreadSheetRowsparams:
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]
Мaгазин 2.0
Получение списка товаров:
method: getShop2ItemsListparams:
page- number, page number starts with 1, a page have max 50 rowssuccess result: code = 0, data = Array of items [id, name, article, count_left]Изменить остатки товара:
method: shop2ItemChangeCountLeftparams:
item_id- number, id of shop item
count_left- number, new count left for item (-1 for infinity)success result: code = 0, data = "ok"
Мaгазин (старая версия)
Получение списка товаров:
method: getShopItemsListparams:
page- number, page number starts with 1, a page have max 50 rowssuccess result: code = 0, data = Array of items [id, name, article, count_left]Изменить остатки товара:
method: shopItemChangeCountLeftparams:
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: botConnectparams: nosuccess result: code = 0, data = "ok"Отвязать бота:
method: botDisconnectparams: nosuccess result: code = 0, data = "ok"Включить бота:
method: botEnableparams: nosuccess result: code = 0, data = "ok"Выключить бота:
method: botDisableparams: nosuccess result: code = 0, data = "ok"Получить список чатов:
method: getChatsListparams: nosuccess result: code = 0, data = Array of chats [chat_id, platform_chat_id, tg_chat_id, max_chat_id, title, description, type]Скачать файл:
method: downloadFileparams:
file_id- string, Telegram/MAX id of file to download
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: Output file with "Content-Type: application/octet-stream"
Кoнструктор
Получить список команд и условий:
method: getCommandsListparams: nosuccess result: code = 0, data = Array of commands [id, name, group_id]Получить список групп команд:
method: getCommandsGroupsListparams: nosuccess result: code = 0, data = Array of commands groups [id, name]Отправка команды или условия:
method: sendCommandparams:
command_name- string, name of command or condition
platform_chat_id- number, Telegram/MAX id of resource or user
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"
Диaлоги
Начать диалог:
method: dialogStartparams:
user_id- number, id of user
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"Завершить диалог:
method: dialogEndparams:
user_id- number, id of user
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"
Только для ресурсов
Принять заявку на вступление в ресурс:
method: joinRequestApproveparams:
user_id- number, id of user
platform_chat_id- number, Telegram/MAX id of resource
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"Отклонить заявку на вступление в ресурс:
method: joinRequestDeclineparams:
user_id- number, id of user
platform_chat_id- number, Telegram/MAX id of resource
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"Удаление пользователя (кик):
method: userKickparams:
platform_chat_id- number, Telegram/MAX id of chat
user_id- number, id of user
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = "ok"
Триггeры (только для групп)
Получение списка триггеров:
method: getTriggersListparams:
page- number, page number starts with 1, a page have max 50 rows
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")success result: code = 0, data = Array of triggers [id, platform_chat_id, name, enabled]Отправка триггера:
method: triggerSendparams:
trigger_id- number, id of trigger
user_id- number, id of user
platform- string, optional (обязателен для MAX: "max", по умолчанию: "tg")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 platform_chat_id / 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!