Telegram Bot — asoslar

~25 daq · NestJS · Qo'shimcha xizmatlar

Muammodan boshlaylik

Siz admin panel yozdingiz. Lekin adminlar har doim brauzerda o'tirishi shart emas. Yangi buyurtma kelsa, server xato bersa — Telegram da darhol bildirishnoma olsalar yaxshi bo'lar edi.

Yoki foydalanuvchilar uchun: bank balansini tekshirish, kurs jadvalini ko'rish, buyurtma holati — bularni Telegram bot orqali qilish mumkin.

Bugungi kunda O'zbekistonda Telegram — eng ko'p ishlatiladigan messenjjer. Ko'pchilik ilovalar Telegram bot orqali ham xizmat ko'rsatadi.


Telegram Bot API qanday ishlaydi?

Telegram serverida bot yaratiladi. Siz o'z serveringizda kod yozasiz. Ikki usulda bog'lanish mumkin:

Polling — siz Telegram serverni har N soniyada so'rab turasiz: "yangi xabar bormi?"

Webhook — Telegram yangi xabar kelganda o'zi sizning serveringizga yuboradi.

  Polling:              Webhook:
  ─────────             ─────────────────────
  Sizning server:       Foydalanuvchi xabar yozdi
  "Yangi xabar bor?"    Telegram → POST /telegram/webhook
  "Yo'q"                Sizning server qayta ishladi
  "Yangi xabar bor?"
  "Ha, mana"
  (har 1-2 soniya)      (darhol, real-time)

Development da — polling qulay. Production da — webhook yaxshiroq.


Bot yaratish

Telegram da @BotFather ga yozing:

/newbot
→ Bot nomi: MyAppBot
→ Username: myapp_bot
→ Token: 1234567890:ABCdefGHIjklMNOpqrSTUvwxyz

Tokenni .env ga saqlang.


O'rnatish

npm install nestjs-telegraf telegraf

AppModule ga ulash (Polling)

// app.module.ts
import { TelegrafModule } from 'nestjs-telegraf';

@Module({
  imports: [
    TelegrafModule.forRoot({
      token: process.env.TELEGRAM_BOT_TOKEN,
    }),
  ],
})
export class AppModule {}

Birinchi bot

// bot/bot.update.ts
import { Update, Start, On, Hears, Ctx } from 'nestjs-telegraf';
import { Context } from 'telegraf';

@Update()
export class BotUpdate {

  // /start buyrug'i
  @Start()
  async start(@Ctx() ctx: Context) {
    await ctx.reply('Salom! Men botman. Yordam uchun /help yozing.');
  }

  // /help buyrug'i
  @Hears('/help')
  async help(@Ctx() ctx: Context) {
    await ctx.reply(
      'Buyruqlar:\n' +
      '/start — boshlanish\n' +
      '/balance — balansni ko\'rish\n' +
      '/orders — buyurtmalar'
    );
  }

  // Matn xabarlarni ushlab olish
  @On('text')
  async onText(@Ctx() ctx: Context) {
    const text = (ctx.message as any).text;
    await ctx.reply(`Siz yozdingiz: "${text}"`);
  }
}

Module ga qo'shish

// bot/bot.module.ts
@Module({
  providers: [BotUpdate],
})
export class BotModule {}
// app.module.ts
@Module({
  imports: [TelegrafModule.forRoot({ ... }), BotModule],
})
export class AppModule {}

Xizmatlar bilan bog'lash

Bot real ma'lumotlarni ko'rsatishi uchun servicelarni inject qiling:

@Update()
export class BotUpdate {
  constructor(private ordersService: OrdersService) {}

  @Hears('/orders')
  async orders(@Ctx() ctx: Context) {
    const userId = ctx.from.id; // Telegram user ID

    // Telegram ID orqali foydalanuvchi topilishi kerak
    const orders = await this.ordersService.findByTelegramId(userId);

    if (!orders.length) {
      return ctx.reply('Buyurtmalar yo\'q');
    }

    const text = orders
      .map(o => `📦 #${o.id} — ${o.status}`)
      .join('\n');

    await ctx.reply(text);
  }
}

Xabar yuborish (bot tomonidan)

Foydalanuvchi yozmasa ham — bot o'zi xabar yuborishi mumkin. Masalan, yangi buyurtma kelganda adminga xabar:

// notification/notification.service.ts
import { InjectBot } from 'nestjs-telegraf';
import { Telegraf } from 'telegraf';

@Injectable()
export class NotificationService {
  constructor(
    @InjectBot() private bot: Telegraf,
  ) {}

  async notifyAdmin(message: string) {
    await this.bot.telegram.sendMessage(
      process.env.ADMIN_CHAT_ID, // admin ning chat ID si
      message,
    );
  }
}
// orders.service.ts
async createOrder(dto: CreateOrderDto) {
  const order = await this.orderRepository.save(dto);

  // Adminga Telegram orqali xabar
  await this.notificationService.notifyAdmin(
    `🆕 Yangi buyurtma!\nID: ${order.id}\nMahsulot: ${order.product}`
  );

  return order;
}

Inline keyboard (tugmalar)

@Start()
async start(@Ctx() ctx: Context) {
  await ctx.reply('Nima qilmoqchisiz?', {
    reply_markup: {
      inline_keyboard: [
        [
          { text: '📦 Buyurtmalarim', callback_data: 'my_orders' },
          { text: '💰 Balansim', callback_data: 'balance' },
        ],
        [
          { text: '🆘 Yordam', callback_data: 'help' },
        ],
      ],
    },
  });
}

@On('callback_query')
async onCallbackQuery(@Ctx() ctx: Context) {
  const data = (ctx.callbackQuery as any).data;

  if (data === 'my_orders') {
    await ctx.reply('Buyurtmalaringiz...');
  } else if (data === 'balance') {
    await ctx.reply('Balans: 50,000 so\'m');
  }

  await ctx.answerCbQuery(); // ← tugmadagi loading ni to'xtatish
}

Tez-tez uchraydigan xatolar

1. Bot javob bermayapti Sababi: BotModule AppModule ga qo'shilmagan, yoki token noto'g'ri. Yechim: .env dagi tokenni tekshiring, BotFather da /mybots bilan tasdiqlang.


2. ctx.from undefined Sababi: Kanaldan kelgan xabar — foydalanuvchi emas. Yechim: ctx.from?.id bilan null tekshirish qiling.


3. Polling conflict

409: Conflict: terminated by other getUpdates request

Sababi: Bir vaqtda ikkita bot instance ishlamoqda. Yechim: Faqat bitta instance ishlasin. Development va production bir vaqtda ishlamasin.


Xulosa

Eslab qoling:

  • @Start() — /start buyrug'i
  • @Hears() — aniq matn yoki buyruqni ushlab olish
  • @On('text') — barcha matn xabarlarini ushlab olish
  • bot.telegram.sendMessage() — bot tomonidan xabar yuborish
  • Inline keyboard — tugmali menyu

Keyingi dars: 50-dars: Telegram Bot — davomi