Примеры кода

Готовые шаблоны ботов. Токен передавайте через переменную окружения BOT_TOKEN.

Node.js (ESM)

// examples/echo-bot.mjs
const TOKEN = process.env.BOT_TOKEN;
if (!TOKEN) {
  console.error('Set BOT_TOKEN');
  process.exit(1);
}

const API = 'https://alphames.duckdns.org/api/bot';
const headers = {
  Authorization: `Bot ${TOKEN}`,
  'Content-Type': 'application/json',
};

let offset = 0;

async function call(path, init = {}) {
  const res = await fetch(`${API}${path}`, { ...init, headers });
  const data = await res.json();
  if (!res.ok) throw new Error(data.error || res.statusText);
  return data;
}

async function poll() {
  const { result } = await call(`/getUpdates?offset=${offset}&limit=50`);
  for (const u of result) {
    offset = u.update_id + 1;
    if (u.type !== 'message') continue;
    const msg = u.message;
    const text = (msg.text || '').trim();
    let reply = 'Отправьте /help';
    if (text === '/start') reply = `Здравствуйте, ${msg.from.displayName}!`;
    else if (text === '/help') reply = 'Команды: /start, /help, /id';
    else if (text === '/id') reply = `Ваш id: ${msg.from.id}, chat: ${msg.chatId}`;
    else if (text) reply = `Echo: ${text}`;
    await call('/sendMessage', {
      method: 'POST',
      body: JSON.stringify({ chat_id: msg.chatId, text: reply }),
    });
  }
}

async function loop() {
  for (;;) {
    try {
      await poll();
    } catch (e) {
      console.error(e.message);
    }
    await new Promise((r) => setTimeout(r, 800));
  }
}

call('/getMe').then(({ result }) => {
  console.log(`Logged in as @${result.username}`);
  loop();
});
node examples/echo-bot.mjs

Python 3

# examples/echo_bot.py
import os, time, json, urllib.request

TOKEN = os.environ.get("BOT_TOKEN")
if not TOKEN:
    raise SystemExit("Set BOT_TOKEN")

API = "https://alphames.duckdns.org/api/bot"
HEADERS = {
    "Authorization": f"Bot {TOKEN}",
    "Content-Type": "application/json",
}

def api(path, data=None):
    req = urllib.request.Request(
        API + path,
        data=json.dumps(data).encode() if data else None,
        headers=HEADERS,
        method="POST" if data else "GET",
    )
    with urllib.request.urlopen(req) as resp:
        body = json.loads(resp.read())
    if not body.get("ok"):
        raise RuntimeError(body.get("error", "API error"))
    return body

offset = 0
me = api("/getMe")["result"]
print(f"Logged in as @{me['username']}")

while True:
    try:
        updates = api(f"/getUpdates?offset={offset}&limit=50")["result"]
        for u in updates:
            offset = u["update_id"] + 1
            if u.get("type") != "message":
                continue
            msg = u["message"]
            text = (msg.get("text") or "").strip()
            if text == "/start":
                reply = f"Привет, {msg['from']['displayName']}!"
            elif text:
                reply = f"Echo: {text}"
            else:
                continue
            api("/sendMessage", {"chat_id": msg["chatId"], "text": reply})
    except Exception as e:
        print("Error:", e)
    time.sleep(0.8)
# PowerShell
$env:BOT_TOKEN="your_token"
python examples/echo_bot.py

curl — ручная проверка

# getMe
curl -s https://alphames.duckdns.org/api/bot/getMe \
  -H "Authorization: Bot $BOT_TOKEN"

# getUpdates
curl -s "https://alphames.duckdns.org/api/bot/getUpdates?offset=0" \
  -H "Authorization: Bot $BOT_TOKEN"

# sendMessage
curl -s https://alphames.duckdns.org/api/bot/sendMessage \
  -H "Authorization: Bot $BOT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"user_id":7,"text":"Hello from curl"}'

Запуск через PM2

# ecosystem.config.cjs
module.exports = {
  apps: [{
    name: 'my-alphames-bot',
    script: 'examples/echo-bot.mjs',
    env: { BOT_TOKEN: 'YOUR_TOKEN' },
  }],
};
pm2 start ecosystem.config.cjs
pm2 logs my-alphames-bot

Рекомендуемая структура проекта

my-bot/
  package.json
  src/
    index.js      # polling loop
    handlers.js   # команды /start, /help
    api.js        # обёртка над Bot API
  .env            # BOT_TOKEN=...
  .gitignore