Quickstart: Telegram Bot

10 minutes

Add pay-as-you-go billing to your Telegram bot

Prerequisites

  • Node.js 18+ installed
  • A Telegram bot token from @BotFather
  • x402Tele account (sign up for free)

Step 1: Install Dependencies

npm install telegraf

Step 2: Create Bot Handler

import { Telegraf } from 'telegraf';

const bot = new Telegraf(process.env.BOT_TOKEN!);

// Handle /analyze command
bot.command('analyze', async (ctx) => {
  const symbol = ctx.message.text.split(' ')[1] || 'BTC';
  const userId = ctx.from.id.toString();
  
  try {
    const result = await executeCommand('analyze', {
      args: { q: symbol },
      userId,
    });
    
    if (result.requiresPayment) {
      await ctx.reply(result.message, {
        reply_markup: {
          inline_keyboard: [
            [{
              text: 'Approve Payment',
              web_app: { url: result.paymentUrl }
            }]
          ]
        }
      });
    } else {
      await ctx.reply(`Analysis for ${symbol}:\n${JSON.stringify(result.result, null, 2)}`);
    }
  } catch (error) {
    await ctx.reply('Error processing command');
  }
});

bot.launch();

Step 3: Implement 402 Handler

async function executeCommand(command: string, data: any) {
  const idempotencyKey = crypto.randomUUID();
  
  let response = await fetch(
    `https://x402tele.app/api/v1/bots/${BOT_ID}/commands/${command}`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`,
        'Idempotency-Key': idempotencyKey,
      },
      body: JSON.stringify({
        args: data.args,
        user_id: `tg:${data.userId}`,
      }),
    }
  );

  if (response.status === 402) {
    const price = response.headers.get('X-402-Price');
    const currency = response.headers.get('X-402-Currency');
    const nonce = response.headers.get('X-402-Nonce');
    
    return {
      requiresPayment: true,
      paymentUrl: `https://x402tele.app/pay?nonce=${nonce}`,
      message: `This command costs ${price} ${currency}. Tap to approve.`,
    };
  }

  const result = await response.json();
  return {
    requiresPayment: false,
    result: result.result,
    receipt: result.receipt,
  };
}

Step 4: Test in Development

Use test mode to develop without real payments:

BOT_TOKEN=your_bot_token
API_KEY=sk_test_your_test_key
BOT_ID=demo
Free Testing
Test mode is completely free with unlimited transactions. Perfect for development!

Step 5: Deploy to Production

Switch to live mode when ready:

API_KEY=sk_live_your_live_key
# Enable live mode in dashboard