Files
IdP/apps/docs/lib/bot-examples.ts
2026-06-26 13:01:52 +03:00

188 lines
5.6 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { OAuthExample } from '@/lib/oauth-examples';
export function buildBotExamples(apiBase: string): OAuthExample[] {
const API_BASE = apiBase.replace(/\/+$/, '');
const BOT_TOKEN = '123456789:AAHdqTcvCH1vGWJxfSeofS0As2XJarzRz5Q';
return [
{
id: 'telegraf',
label: 'Telegraf',
language: 'javascript',
code: `import { Telegraf } from 'telegraf';
// Достаточно сменить apiRoot — код бота остаётся без изменений
const bot = new Telegraf(process.env.BOT_TOKEN, {
telegram: {
apiRoot: '${API_BASE}/bot'
}
});
bot.start((ctx) => ctx.reply('Привет! Бот работает через Lendry Bot API.'));
bot.command('ping', (ctx) => ctx.reply('pong'));
// Inline-клавиатура и callback_query
bot.command('menu', (ctx) =>
ctx.reply('Выберите действие:', {
reply_markup: {
inline_keyboard: [
[{ text: '✅ OK', callback_data: 'ok' }, { text: '❌ Cancel', callback_data: 'cancel' }]
]
}
})
);
bot.action('ok', async (ctx) => {
await ctx.answerCbQuery('Принято!');
await ctx.editMessageText('Вы нажали OK ✅');
});
bot.launch();`
},
{
id: 'node-telegram-bot-api',
label: 'node-telegram-bot-api',
language: 'javascript',
code: `import TelegramBot from 'node-telegram-bot-api';
const token = process.env.BOT_TOKEN;
const bot = new TelegramBot(token, {
polling: true,
baseApiUrl: '${API_BASE}/bot'
});
bot.on('message', (msg) => {
bot.sendMessage(msg.chat.id, \`Вы написали: \${msg.text}\`);
});`
},
{
id: 'curl',
label: 'cURL',
language: 'bash',
code: `# getMe — проверка токена
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/getMe' | jq
# sendMessage — chat_id = UUID пользователя Lendry ID
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/sendMessage' \\
-H 'Content-Type: application/json' \\
-d '{
"chat_id": "USER_UUID",
"text": "Привет из Bot API!"
}' | jq
# sendMessage с inline-клавиатурой
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/sendMessage' \\
-H 'Content-Type: application/json' \\
-d '{
"chat_id": "USER_UUID",
"text": "Выберите:",
"reply_markup": {
"inline_keyboard": [[{ "text": "OK", "callback_data": "ok" }]]
}
}' | jq
# editMessageText
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/editMessageText' \\
-H 'Content-Type: application/json' \\
-d '{
"chat_id": 1000000000000,
"message_id": 1,
"text": "Текст обновлён"
}' | jq
# answerCallbackQuery
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/answerCallbackQuery' \\
-H 'Content-Type: application/json' \\
-d '{
"callback_query_id": "CALLBACK_QUERY_ID",
"text": "Готово!"
}' | jq
# setChatMenuButton — глобальная кнопка меню (Web App)
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/setChatMenuButton' \\
-H 'Content-Type: application/json' \\
-d '{
"menu_button": {
"type": "web_app",
"text": "Открыть",
"web_app": { "url": "https://app.example.com" }
}
}' | jq
# setChatMenuButton — per-chat override
curl -s -X POST '${API_BASE}/bot${BOT_TOKEN}/setChatMenuButton' \\
-H 'Content-Type: application/json' \\
-d '{
"chat_id": 1000000000000,
"menu_button": {
"type": "web_app",
"text": "Персонально",
"web_app": { "url": "https://app.example.com/user" }
}
}' | jq`
},
{
id: 'python',
label: 'Python',
language: 'python',
code: `import os
import requests
API_BASE = '${API_BASE}'
TOKEN = os.environ['BOT_TOKEN']
CHAT_ID = 'USER_UUID'
def bot_api(method: str, payload: dict | None = None):
url = f"{API_BASE}/bot{TOKEN}/{method}"
response = requests.post(url, json=payload or {}, timeout=30)
response.raise_for_status()
return response.json()
print(bot_api('getMe'))
print(bot_api('sendMessage', {'chat_id': CHAT_ID, 'text': 'Привет!'}))`
},
{
id: 'botfather',
label: 'BotFather (REST)',
language: 'bash',
code: `# Создание бота (JWT пользователя Lendry ID)
curl -s -X POST '${API_BASE}/bots' \\
-H 'Authorization: Bearer ACCESS_TOKEN' \\
-H 'Content-Type: application/json' \\
-d '{
"name": "Мой сервисный бот",
"username": "my_service"
}' | jq
# Ответ содержит token — сохраните его, повторно не показывается при GET
# BotFather добавляется в семью через поиск и POST /family/groups/{id}/invites.
# Профиль бота через BotFather в чате:
# /setdescription my_service Описание перед /start
# /setabouttext my_service Краткое описание
# /setuserpic my_service https://cdn.example.com/avatar.png
# /setmenubutton my_service https://app.example.com|Открыть приложение`
},
{
id: 'webapp',
label: 'Mini App initData',
language: 'javascript',
code: `// На backend Mini App проверяйте initData через Bot API
const response = await fetch('${API_BASE}/bots/web-app/validate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
initData: window.Telegram.WebApp.initData,
botToken: process.env.BOT_TOKEN
})
});
const result = await response.json();
if (!result.valid) {
throw new Error(result.error ?? 'Невалидный initData');
}
const user = result.userJson ? JSON.parse(result.userJson) : null;`
}
];
}