Toki

Боты и веб-приложения

Бот получает события из личного чата и отправляет сообщения через HTTP. Код работает на вашем сервере. Вы решаете, что делать с событием: показать анкету, ответить на вопрос, найти трек или добавить товар в корзину. Для экранов с формами, поиском или плеером можно подключить свое веб-приложение. Текущая версия работает в личных чатах. Встроенные платежи и подключение бота к группе пока не доступны.

Первый работающий бот

В Toki откройте Профиль → Мои боты → Создать бота. Если пункта нет, вашему профилю пока не открыт доступ к ботам. Укажите имя для чата и уникальный юзернейм для ссылки. Для текстового бота адрес веб-приложения можно оставить пустым. У профиля может быть до трех ботов.

Создайте отдельную папку для примера и в ней файл .env. Скопируйте токен из настроек своего нового бота вместо значения ниже. Токен нужен только серверу бота. Храните файл вне Git и отдельно от кода страницы, который получает браузер.

TOKI_BOT_TOKEN=toki_bot_…

Установите Node.js 22 или новее. Сохраните starter.mjs в ту же папку и выполните в ней команду. Зависимости устанавливать не требуется.

node --env-file=.env starter.mjs

В терминале появится @ваш_юзернейм is listening. Откройте в Toki профиль этого бота и нажмите «Запустить бота». В чате появится «Что показать?» с кнопкой «Каталог». Нажмите ее: бот пришлет «Зеленый чай · 450 ₽». Пока процесс работает, он отвечает на новые сообщения. Для остановки нажмите Ctrl+C.

Посмотреть весь код starter.mjs
// Node.js 22+. Start with: node --env-file=.env starter.mjs
import { readFile, rename, writeFile } from 'node:fs/promises';
import { setTimeout as sleep } from 'node:timers/promises';

const token = process.env.TOKI_BOT_TOKEN;
const base = process.env.TOKI_BOT_API || 'https://toki.biz/api/bot/v1';
if (!token) throw new Error('Set TOKI_BOT_TOKEN in .env');

async function api(path, method = 'GET', body) {
  const response = await fetch(base + path, {
    method, redirect: 'error', signal: AbortSignal.timeout(35000),
    headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const result = await response.json();
  if (!response.ok) throw Object.assign(new Error(result.error?.code || 'HTTP ' + response.status), {
    status: response.status, delay: Number(response.headers.get('Retry-After')) || 2,
  });
  return { result, delay: Number(response.headers.get('Retry-After')) || 0 };
}

async function handle(event) {
  const en = event.user?.lang === 'en';
  const send = (suffix, message) => api('/messages', 'POST', {
    chat_id: event.chat_id, client_id: 'starter-' + event.id + '-' + suffix, ...message,
  });
  if (event.type === 'message') {
    await send('menu', {
      text: en ? 'What would you like to see?' : 'Что показать?',
      buttons: [[{ text: en ? 'Catalog' : 'Каталог', callback_data: 'catalog' }]],
    });
  } else if (event.type === 'callback' && event.data === 'catalog') {
    try {
      await api('/updates/' + event.id + '/answer', 'POST', {});
    } catch (error) {
      if (error.message !== 'answer_expired') throw error;
    }
    await send('catalog', { text: en ? 'Green tea · 450 ₽' : 'Зеленый чай · 450 ₽' });
  }
}

const { result: bot } = await api('/me');
const cursorPath = '.toki-cursor-' + bot.id;
let after = 0;
try {
  const saved = (await readFile(cursorPath, 'utf8')).trim();
  if (!/^\d+$/.test(saved) || !Number.isSafeInteger(Number(saved))) throw new Error('Invalid saved cursor');
  after = Number(saved);
} catch (error) {
  if (error.code !== 'ENOENT') throw error;
}
console.log('@' + bot.username + ' is listening');
for (;;) {
  try {
    const { result: page, delay } = await api('/updates?timeout=25&after=' + after);
    for (const event of page.updates) {
      try { await handle(event); }
      catch (error) { if (error.message !== 'chat_unavailable') throw error; }
    }
    if (page.next_cursor !== after) {
      await writeFile(cursorPath + '.tmp', String(page.next_cursor), { mode: 0o600 });
      await rename(cursorPath + '.tmp', cursorPath);
      after = page.next_cursor;
    }
    if (delay) await sleep(delay * 1000);
  } catch (error) {
    if (error.status && error.status < 500 && ![408, 429].includes(error.status)) throw error;
    console.error(error.message);
    await sleep((error.delay || 2) * 1000);
  }
}

Для своего бота начните с функции handle(event). Например, бот знакомств берет следующую анкету из вашей базы, отправляет фото и две кнопки. Магазин по тому же принципу показывает товар, а обработчик кнопки меняет корзину. Персональные данные, остатки и состояние заказа хранит ваш сервис.

Как читать событие

Когда человек запускает бота, приходит событие типа message с текстом /start. Пример ответа GET /updates ниже. Числа приведены для примера, в своем коде берите их из ответа API.

{
  "updates": [{
    "id": 812, "type": "message", "date": 1796385600,
    "chat_id": 41, "user_id": 27, "message_id": 503,
    "user": {"id": 27, "name": "Alex", "username": "alex27", "lang": "en"},
    "text": "/start"
  }],
  "next_cursor": 812
}
ПолеКогда использовать
chat_idКуда отправить ответ. Бот может писать в личный чат после того, как его начал человек.
user.idКлюч пользователя в вашей базе. Имя и юзернейм могут поменяться.
idНомер события в журнале бота. По нему распознают повторную доставку и отвечают на нажатие.
message_idКонкретное сообщение в чате. Передайте его как reply_to_message_id, чтобы процитировать сообщение пользователя.
client_idВаш ключ исходящей отправки, до 64 символов. Для ответа на событие 812 подойдет reply-812. При повторе той же отправки сохраняйте ключ. Для второго сообщения дайте другой.
next_cursorМесто для следующего чтения журнала. Сохраните после обработки всей страницы, включая пустую.

Получение событий

Для запросов ниже нужен Bash и curl с поддержкой --json. В папке примера выполните команды ниже. Первая строка читает ваш собственный файл .env. GET /me вернет юзернейм бота и его настройки. Ответьте в чат с chat_id из вашего события.

. ./.env
API=https://toki.biz/api/bot/v1
AUTH="Authorization: Bearer $TOKI_BOT_TOKEN"
curl -sS -H "$AUTH" "$API/me"
curl -sS -H "$AUTH" "$API/updates?after=0&limit=5"
CHAT_ID=41
curl -sS -H "$AUTH" "$API/messages" --json \
  "{\"chat_id\":$CHAT_ID,\"client_id\":\"manual-1\",\"text\":\"Hello!\"}"

Ожидаемый ответ на отправку: {"id":504,"chat_id":41}. Это ID нового сообщения. Чтобы его изменить, вызовите PATCH /messages/504 с {"text":"Updated"}. Чтобы убрать его, вызовите DELETE /messages/504.

В рабочем боте один процесс читает GET /updates?after=КУРСОР&timeout=25. Пустая страница нормальна. В журнале хранятся события за 30 дней: message, message_edited, callback, blocked, unblocked. В стартовом примере курсор сохраняется в файле .toki-cursor-ID рядом с процессом. Для нескольких рабочих процессов храните обработанные ID и изменения заказа вместе в транзакции вашей БД.

Команды и кнопки

Чтобы показать команду в меню чата, вызовите PUT /commands. Выбор команды отправляет боту обычное сообщение /catalog. Текст команды проверяет ваш обработчик. Для отдельных списков добавьте lang со значением ru или en.

curl -sS -X PUT -H "$AUTH" "$API/commands" --json '{"commands":[{"command":"catalog","description":"Каталог"}]}'

Команд может быть до 30. Кнопки задаются строками: до 8 рядов и до 4 кнопок в ряду. Ниже тело POST /messages для карточки. Каждая внутренняя группа образует один ряд. Замените ID чата на свой. Для кнопки с web_app сначала сохраните HTTPS-адрес веб-приложения в настройках бота.

{
  "chat_id": 41, "client_id": "item-15-card-1", "text": "Tea · 450 ₽",
  "buttons": [
    [{"text":"+1","callback_data":"cart:add:15"}],
    [{"text":"Details","web_app":{"start_param":"item_15"}},
     {"text":"Website","url":"https://shop.example.org/tea"}]
  ]
}

Нажатие «+1» дает событие callback с data:"cart:add:15". Возьмите ID события, прибавьте товар в корзине один раз и за 10 секунд ответьте через POST /updates/ID/answer с {"text":"Добавлено"} или {}. Для долгой операции сначала подтвердите нажатие, а результат пришлите отдельным сообщением. Кнопка url открывает ссылку, web_app запускает вашу страницу с параметром.

Оформление текста передается в entities. Доступны bold, italic, code, quote и link. offset и length измеряются единицами UTF-16. Например, в тексте 🎵 Jazz слово Jazz начинается со смещения 3 и занимает 4 единицы.

Фото, документы, аудио и видео

Для собственного трека передайте kind=audio. Получатель увидит плеер с названием и исполнителем. Трек можно отправить прямо с диска, без публикации в каталоге Toki. В обновленных мобильных клиентах человек также может выбрать свой MP3 через «Скрепка → Файл» в переписке с человеком или ботом.

kindКогда выбратьОграничение
photoФотография товара или анкеты. JPEG, PNG, WebP, GIF. Изображение в ленте чата.10 МиБ, 40 Мп
fileСкачать исходный файл с его именем. Подходит для PDF, ZIP или оригинала MP3.50 МиБ
audioВоспроизвести трек в чате. Поля title и performer задают название и исполнителя.50 МиБ, 10 минут
videoВоспроизвести видео в чате с обложкой и перемоткой.50 МиБ, 10 минут

Сначала отправьте файл с диска в POST /files как multipart/form-data. Запустите одну команду для нужного вида. Возьмите числовой id из ответа и передайте его в POST /messages как file_id.

curl -sS -H "$AUTH" "$API/files" -F kind=photo -F 'file=@cover.jpg'
curl -sS -H "$AUTH" "$API/files" -F kind=file  -F 'file=@menu.pdf'
curl -sS -H "$AUTH" "$API/files" -F kind=audio -F 'file=@track.mp3' -F 'title=Night Walk' -F 'performer=Example Band'
curl -sS -H "$AUTH" "$API/files" -F kind=video -F 'file=@clip.mp4'
FILE_ID=4410
curl -sS -H "$AUTH" "$API/messages" --json \
  "{\"chat_id\":$CHAT_ID,\"client_id\":\"media-1\",\"file_id\":$FILE_ID,\"text\":\"Night Walk\"}"

Один файл на сообщение. Подпись и кнопки можно отправить вместе с file_id. Для другого сообщения заведите новый client_id. Бот может многократно использовать свою загрузку. Если файл сутки не прикреплялся ни к одному сообщению, загрузите его снова при file_not_found.

Для входящих фото, документов и MP3 читайте массив files события. Ссылка url живет 10 минут. Если срок истек, запросите GET /files/ID. Входящий MP3 имеет kind:"audio" и поля title, performer, duration_sec. Ссылку скачивают без токена бота. Для отправки полученного от человека файла другому пользователю сначала загрузите его в хранилище бота.

Веб-приложение и вход

Веб-приложение нужно, если диалога мало: например, для поиска по каталогу или выбора нескольких позиций. Toki открывает ваш HTTPS-сайт внутри чата. Bot API и веб-приложение можно использовать вместе или начать только с диалога.

Скачайте рабочий пример веб-приложения в папку с тем же .env. Запустите его отдельным процессом. В примере уже есть страница, обмен данными запуска и защищенный маршрут текущего пользователя.

node --env-file=.env webapp.mjs

Пример слушает 127.0.0.1:8080 (порт меняет PORT). Направьте на него HTTPS-адрес своего сайта, например https://shop.example.org/, и внесите этот адрес в настройки бота. Нужен отдельный публичный домен, стандартный порт HTTPS и адрес без фрагмента. Для браузерного клиента разрешите https://toki.biz в frame-ancestors.

  1. Человек открывает https://toki.biz/USERNAME?startapp=item_15. При первом входе он запускает бота касанием. Параметр до 64 символов, допустимы буквы латиницы, цифры, _ и -.
  2. Страница подключает SDK и передает строку Toki.WebApp.initData своему серверу. Сервер вызывает POST /webapp/session с Bearer-токеном бота и телом {"initData":"…"}.
  3. Ответ Toki содержит bot_id, chat_id, user, проверенный start_param и auth_date. Для действий с заказами используйте user.id из этого ответа и проверяйте права пользователя на выбранный заказ.
  4. Сервер выдает свою сессию. Пример хранит ее в памяти час, а страница использует ее для GET /account. В окне появятся имя из Toki и item_15. При перезапуске процесса учебные сессии завершаются.

Одноразовые данные запуска действуют 120 секунд. При новом открытии получите новые данные. Обычная ссылка ?start=promo вместо запуска страницы отправляет параметр в событии /start.

<script src="https://toki.biz/assets/toki-webapp-v1.js"></script>
<script>
  const app = Toki.WebApp;
  app.MainButton.setText("OK").show().onClick(() => app.close());
  app.ready();
</script>

В SDK есть главная кнопка, кнопка «Назад», сворачивание, подтверждение закрытия и события смены темы и видимости. Поля safeArea и CSS-переменные --toki-safe-top и --toki-safe-bottom помогают оставить место системным кнопкам. Для плеера обрабатывайте visibilityChanged, чтобы приостановить звук в фоне.

Переход на вебхук

Опрос подходит для первого запуска и локальной разработки. При наличии публичного HTTPS-обработчика Toki может сам присылать страницы событий. Обработчик принимает POST c {updates,next_cursor}. Остановите потребителя опроса после сохранения курсора, зарегистрируйте обработчик и сохраните выданный secret. Повторная регистрация выдает другой секрет.

curl -sS -X PUT -H "$AUTH" "$API/webhook" --json \
  '{"url":"https://shop.example.org/toki-hook","after":812}'

Замените 812 своим сохраненным курсором. Передайте последний обработанный курсор в after, чтобы продолжить доставку при переходе с опроса на вебхук. Без этого поля доставка начинается с новых событий. Перед обработкой проверьте заголовок Toki-Signature по исходным байтам запроса. Для Node.js передавайте в функцию ниже тело типа Buffer.

import { createHmac, timingSafeEqual } from 'node:crypto';
function valid(rawBody, header, secret) {
  const match = /^t=(\d+),v1=([a-f0-9]{64})$/.exec(header || '');
  if (!match || Math.abs(Date.now()/1000 - Number(match[1])) > 300) return false;
  const digest = createHmac('sha256', secret).update(match[1] + '.').update(rawBody).digest();
  return timingSafeEqual(digest, Buffer.from(match[2], 'hex'));
}

Сохраните события по их ID и верните 2xx в течение 8 секунд. Долгую работу можно выполнить из вашей очереди. При ошибке Toki повторяет доставку с последнего подтвержденного места. GET /me показывает курсор вебхука, ошибки и время повтора. Ответ 410 отключает вебхук. Для возврата к опросу сохраните webhook.cursor, вызовите DELETE /webhook и продолжите GET /updates с ним.

Ошибки и справочники

Бот запущен, но в чате тихо. Сверьте юзернейм из GET /me с открытым профилем. Отправьте новое текстовое сообщение. Проверьте, что update_types в настройках включает message и callback. Для получения всех типов отправьте PATCH /me с телом {"update_types":null}. Если событие получено, проверьте ответ на POST /messages и использованный chat_id.

Ошибки API приходят как {"ok":false,"error":{"code":"…","message":"…"}}. В программе проверяйте code. На validation_failed посмотрите также ошибки полей.

СимптомЧто сделать
401 · invalid_tokenПроверьте токен в окружении и перезапустите процесс после замены.
404 · chat_unavailableПользователь должен запустить бота. Проверьте chat_id из события. После блокировки или удаления чата прекратите отправку.
409 · poll_conflictОставьте один процесс с длинным опросом на бота.
401 · invalid_launchЗакройте и заново откройте веб-приложение из Toki. Проверяйте токен именно этого бота.
410 · answer_expiredПрошли 10 секунд для всплывающего ответа. Готовый результат можно отправить через /messages.
413 / 422Проверьте размер, kind, формат по содержимому и диапазоны UTF-16.
429 · rate_limitedПовторите через число секунд из Retry-After с тем же client_id для той же отправки. Лимиты отправки: 20/с на бота и 60/мин в один чат.

Полный состав запросов, ответов, лимиты и типы событий приведены в OpenAPI 3.1. Методы и события окна перечислены в типах TypeScript для SDK.

Bots and web apps

A bot receives events from a direct chat and sends messages over HTTP. Your code runs on your server. It can show a profile, answer a question, find a track or add an item to a cart. You can also attach your own web app for search, forms or a player. This version supports direct chats. Group bots and built-in payments are planned separately.

Run your first bot

In Toki, open Profile → My bots → Create bot. If My bots is missing, your profile does not currently have access. Set a display name and a unique username for the link. A text bot can leave the web app URL empty. Each owner profile can create up to three bots.

Create an empty folder for this example and a file named .env inside it. Replace the value below with the token from your new bot’s settings. Keep the token on the bot server, outside Git and browser code.

TOKI_BOT_TOKEN=toki_bot_…

Use Node.js 22 or later. Save starter.mjs beside the environment file and run the command in that folder. There are no package dependencies.

node --env-file=.env starter.mjs

The terminal prints @your_username is listening. Open that bot’s profile in Toki and select Start bot. The bot sends a menu with a Catalog button. Select it to receive “Green tea · 450 ₽”. Leave the process running to receive new messages. Stop it with Ctrl+C.

Read the complete starter.mjs
// Node.js 22+. Start with: node --env-file=.env starter.mjs
import { readFile, rename, writeFile } from 'node:fs/promises';
import { setTimeout as sleep } from 'node:timers/promises';

const token = process.env.TOKI_BOT_TOKEN;
const base = process.env.TOKI_BOT_API || 'https://toki.biz/api/bot/v1';
if (!token) throw new Error('Set TOKI_BOT_TOKEN in .env');

async function api(path, method = 'GET', body) {
  const response = await fetch(base + path, {
    method, redirect: 'error', signal: AbortSignal.timeout(35000),
    headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const result = await response.json();
  if (!response.ok) throw Object.assign(new Error(result.error?.code || 'HTTP ' + response.status), {
    status: response.status, delay: Number(response.headers.get('Retry-After')) || 2,
  });
  return { result, delay: Number(response.headers.get('Retry-After')) || 0 };
}

async function handle(event) {
  const en = event.user?.lang === 'en';
  const send = (suffix, message) => api('/messages', 'POST', {
    chat_id: event.chat_id, client_id: 'starter-' + event.id + '-' + suffix, ...message,
  });
  if (event.type === 'message') {
    await send('menu', {
      text: en ? 'What would you like to see?' : 'Что показать?',
      buttons: [[{ text: en ? 'Catalog' : 'Каталог', callback_data: 'catalog' }]],
    });
  } else if (event.type === 'callback' && event.data === 'catalog') {
    try {
      await api('/updates/' + event.id + '/answer', 'POST', {});
    } catch (error) {
      if (error.message !== 'answer_expired') throw error;
    }
    await send('catalog', { text: en ? 'Green tea · 450 ₽' : 'Зеленый чай · 450 ₽' });
  }
}

const { result: bot } = await api('/me');
const cursorPath = '.toki-cursor-' + bot.id;
let after = 0;
try {
  const saved = (await readFile(cursorPath, 'utf8')).trim();
  if (!/^\d+$/.test(saved) || !Number.isSafeInteger(Number(saved))) throw new Error('Invalid saved cursor');
  after = Number(saved);
} catch (error) {
  if (error.code !== 'ENOENT') throw error;
}
console.log('@' + bot.username + ' is listening');
for (;;) {
  try {
    const { result: page, delay } = await api('/updates?timeout=25&after=' + after);
    for (const event of page.updates) {
      try { await handle(event); }
      catch (error) { if (error.message !== 'chat_unavailable') throw error; }
    }
    if (page.next_cursor !== after) {
      await writeFile(cursorPath + '.tmp', String(page.next_cursor), { mode: 0o600 });
      await rename(cursorPath + '.tmp', cursorPath);
      after = page.next_cursor;
    }
    if (delay) await sleep(delay * 1000);
  } catch (error) {
    if (error.status && error.status < 500 && ![408, 429].includes(error.status)) throw error;
    console.error(error.message);
    await sleep((error.delay || 2) * 1000);
  }
}

Start customizing handle(event). A dating bot can read the next profile from your database and send a photo with two buttons. A shop can send a product the same way, then update the cart from a button event. Your service owns the personal data, inventory and order state.

Read an update

Starting the bot produces a message update whose text is /start. Below is an example GET /updates response. Use the actual IDs from your response in your code.

{
  "updates": [{
    "id": 812, "type": "message", "date": 1796385600,
    "chat_id": 41, "user_id": 27, "message_id": 503,
    "user": {"id": 27, "name": "Alex", "username": "alex27", "lang": "en"},
    "text": "/start"
  }],
  "next_cursor": 812
}
FieldWhen to use it
chat_idWhere to send the reply. A person must initiate the chat before the bot can send messages.
user.idThe user key in your database. The name and username can change.
idAn update ID. Use it to deduplicate delivery and answer button presses.
message_idIdentifies one chat message. Supply it as reply_to_message_id to reply to a particular message.
client_idYour outgoing send key, up to 64 characters. Use reply-812 for a reply to update 812. Keep it when retrying that send. Give a second message a different key.
next_cursorYour position for reading the next page. Persist it after processing the entire page, including empty pages.

Receive updates

The requests below use Bash and curl with --json. Run them in the example folder. The first line reads your own .env file. GET /me returns the bot username and settings. Replace the sample chat ID with the chat_id from your update.

. ./.env
API=https://toki.biz/api/bot/v1
AUTH="Authorization: Bearer $TOKI_BOT_TOKEN"
curl -sS -H "$AUTH" "$API/me"
curl -sS -H "$AUTH" "$API/updates?after=0&limit=5"
CHAT_ID=41
curl -sS -H "$AUTH" "$API/messages" --json \
  "{\"chat_id\":$CHAT_ID,\"client_id\":\"manual-1\",\"text\":\"Hello!\"}"

A successful send returns, for example, {"id":504,"chat_id":41}. Use the new message ID in PATCH /messages/504 with {"text":"Updated"} to edit it or DELETE /messages/504 to remove it.

Run one long poller with GET /updates?after=CURSOR&timeout=25. Empty pages are expected. Updates are retained for 30 days: message, message_edited, callback, blocked and unblocked. The starter writes its cursor to .toki-cursor-ID in its working directory. For multi-worker processing, commit the processed update ID and order changes together in your database.

Commands and buttons

Use PUT /commands to add a command to the chat menu. Choosing the command sends a normal /catalog message to your handler. Add lang with ru or en for language-specific lists.

curl -sS -X PUT -H "$AUTH" "$API/commands" --json '{"commands":[{"command":"catalog","description":"Catalog"}]}'

A command list accepts up to 30 entries. Buttons are grouped into up to 8 rows of up to 4 buttons each. Here is a POST /messages body for a product card. Each inner array is one row. Substitute your chat ID. Set the web app HTTPS URL in the bot settings before including a web_app button.

{
  "chat_id": 41, "client_id": "item-15-card-1", "text": "Tea · 450 ₽",
  "buttons": [
    [{"text":"+1","callback_data":"cart:add:15"}],
    [{"text":"Details","web_app":{"start_param":"item_15"}},
     {"text":"Website","url":"https://shop.example.org/tea"}]
  ]
}

Pressing “+1” produces a callback update with data:"cart:add:15". Use the update ID to add the item once and call POST /updates/ID/answer within 10 seconds with {"text":"Added"} or {}. For a slow operation, acknowledge first and send the result in a new message. A url button opens a link and web_app opens your page with the parameter.

Send formatting in entities. Supported types are bold, italic, code, quote and link. Both offset and length count UTF-16 code units. In 🎵 Jazz, Jazz starts at offset 3 and spans 4 units.

Photos, documents, audio and video

To send your own track, upload it with kind=audio. The recipient sees a player with the title and performer. The track can come straight from disk without publishing it in the Toki catalog. In updated mobile clients people can also select their own MP3 from Attach → File in chats with people or bots.

kindWhen to use itLimit
photoProduct or profile photo. JPEG, PNG, WebP or GIF, displayed inline.10 MiB, 40 MP
fileDownload the original bytes with a filename, for example a PDF, ZIP or original MP3.50 MiB
audioPlay a track inside the chat. The title and performer fields label the player.50 MiB, 10 minutes
videoPlay a video inline with a poster and seeking.50 MiB, 10 minutes

First send a local file to POST /files as multipart/form-data. Run the command for the kind you want. Take the numeric id from the response and send it as file_id to POST /messages.

curl -sS -H "$AUTH" "$API/files" -F kind=photo -F 'file=@cover.jpg'
curl -sS -H "$AUTH" "$API/files" -F kind=file  -F 'file=@menu.pdf'
curl -sS -H "$AUTH" "$API/files" -F kind=audio -F 'file=@track.mp3' -F 'title=Night Walk' -F 'performer=Example Band'
curl -sS -H "$AUTH" "$API/files" -F kind=video -F 'file=@clip.mp4'
FILE_ID=4410
curl -sS -H "$AUTH" "$API/messages" --json \
  "{\"chat_id\":$CHAT_ID,\"client_id\":\"media-1\",\"file_id\":$FILE_ID,\"text\":\"Night Walk\"}"

Send one file per message; a caption and buttons can accompany file_id. Give each new message its own client_id. Reuse your own upload as often as needed. If an unused upload is removed after 24 hours, upload it again on file_not_found.

Incoming photos, documents and MP3 tracks arrive in the update’s files array. Its download url lasts 10 minutes. Refresh it with GET /files/ID. An incoming MP3 has kind:"audio" and includes title, performer and duration_sec. Download directly without the bot token. To send a user’s file onward, first upload a copy to the bot’s storage.

Web app and sign-in

Use a web app for screens such as a searchable catalog or a multi-item picker. Toki opens your HTTPS site inside the chat. Start with a chat-only bot or combine it with your own web interface.

Save the working web app example beside the same .env and run it as a separate process. It contains the page, the launch exchange and an authenticated current-user route.

node --env-file=.env webapp.mjs

The example listens on 127.0.0.1:8080 (set PORT to change it). Point your public HTTPS reverse proxy at this process, for example https://shop.example.org/, and save that URL in the bot settings. Use a distinct public domain on the standard HTTPS port, without a URL fragment. Allow https://toki.biz in the page’s frame-ancestors policy for browser clients.

  1. Open https://toki.biz/USERNAME?startapp=item_15 in Toki. First-time users start the bot with a tap. Parameters accept up to 64 ASCII letters, digits, underscores or hyphens.
  2. Load the SDK on the page and pass the exact Toki.WebApp.initData string to your server. Your server calls POST /webapp/session with the bot’s Bearer token and {"initData":"…"}.
  3. Toki returns bot_id, chat_id, user, the verified start_param and auth_date. Use this user.id for account operations and check that the user has access to the selected order.
  4. Issue your own session. The example keeps sessions in memory for an hour. Its page uses the session to call GET /account. The screen shows the Toki name and item_15. Restarting this example ends its sessions.

Launch data can be exchanged once within 120 seconds. Reopen the app for fresh data. Use ?start=promo to deliver a parameter in the chat’s /start update instead of opening a page.

<script src="https://toki.biz/assets/toki-webapp-v1.js"></script>
<script>
  const app = Toki.WebApp;
  app.MainButton.setText("OK").show().onClick(() => app.close());
  app.ready();
</script>

The SDK exposes the main and back buttons, minimize, closing confirmation, theme and visibility events. Use safeArea or CSS variables such as --toki-safe-top and --toki-safe-bottom to keep content clear of host controls. A media player can pause on visibilityChanged.

Switch to a webhook

Polling is convenient for local development. If you have a public HTTPS endpoint, Toki can push update pages to it with a POST containing {updates,next_cursor}. Stop the polling consumer after saving its cursor, register the endpoint and store the returned secret. Registering it again replaces that secret.

curl -sS -X PUT -H "$AUTH" "$API/webhook" --json \
  '{"url":"https://shop.example.org/toki-hook","after":812}'

Replace 812 with your saved cursor. Pass the last processed cursor in after to resume delivery when switching from polling to webhooks. Omitting it starts with new updates. Verify Toki-Signature against the original request bytes before handling events. In Node.js pass the raw request body as a Buffer.

import { createHmac, timingSafeEqual } from 'node:crypto';
function valid(rawBody, header, secret) {
  const match = /^t=(\d+),v1=([a-f0-9]{64})$/.exec(header || '');
  if (!match || Math.abs(Date.now()/1000 - Number(match[1])) > 300) return false;
  const digest = createHmac('sha256', secret).update(match[1] + '.').update(rawBody).digest();
  return timingSafeEqual(digest, Buffer.from(match[2], 'hex'));
}

Persist updates by ID and return 2xx within 8 seconds; do slow work using your own queue. On a failure Toki retries from the last acknowledged cursor. GET /me shows the webhook cursor, errors and retry time. A 410 disables delivery. To return to polling, save webhook.cursor, call DELETE /webhook and pass that cursor to GET /updates.

Errors and references

The bot is running but the chat is quiet. Compare the username from GET /me with the open profile and send a fresh text message. Check that the selected update_types include message and callback. Reset to all types with PATCH /me and {"update_types":null}. If the update arrived, check the response to POST /messages and the chat_id you used.

API errors use {"ok":false,"error":{"code":"…","message":"…"}}. Branch on code and inspect field errors for validation_failed.

SymptomWhat to check
401 · invalid_tokenCheck the token in the environment. Restart the process after rotation.
404 · chat_unavailableCheck the event’s chat_id and whether the user started the bot. Stop sending if the user blocked the bot or removed the chat.
409 · poll_conflictKeep one long-polling process per bot.
401 · invalid_launchReopen the web app in Toki. Use the token for the bot that launched it.
410 · answer_expiredThe 10-second callback answer window elapsed. You can still send the result with /messages.
413 / 422Check the size, kind, actual file format and UTF-16 ranges.
429 · rate_limitedWait the number of seconds in Retry-After. Reuse the same client_id for the same send. Send limits are 20/s per bot and 60/min per chat.

See the OpenAPI 3.1 reference for request bodies, response schemas and event types. See the SDK TypeScript definitions for window methods and events.