DEV Community

Alexander Kim
Alexander Kim

Posted on

5 1 1 1 1

Using Nuxt 3 server routes for telegram bot api

In this short article, we're going to use telegram setWebhook, instead of getUpdates polling mechanism. I omit the steps where you have to set up a new bot in telegram UI, using BotFather

Nuxt 3 setup

Create telegram-webhook.post.ts in "server/api" directory with the following contents:

import TelegramBot from 'node-telegram-bot-api'

export default defineEventHandler(async event => {
  const config = useRuntimeConfig()
  const token = config.telegramBotToken

  // Create a new TelegramBot instance (without polling)
  const bot = new TelegramBot(token)

  // Read the incoming request body
  const body = await readBody(event)

  // Extract the message
  const { message } = body

  if (message) {
    const chatId = message.chat.id
    const text = message.text

    // Respond to the received message
    if (text) {
      await bot.sendMessage(chatId, `Ты сказал: ${text}`)
    }

    // Handle /start command
    if (text && text.startsWith('/start')) {
      await bot.sendMessage(
        chatId,
        'Hi, i am bot, how can i help you?',
      )
    }
  }

  return { status: 'ok', message }
})

Enter fullscreen mode Exit fullscreen mode

don't forget to add "node-telegram-bot-api" npm package. The we start Nuxt3 instance. Now we need to set up a webhook.

We have to call:
curl https://api.telegram.org/bot<telegram_bot_token>/setWebhook?url=https://<your-domain.com>/api/telegram-webhook
this command will set up our POST API endpoint as webhook for telegram. Official documentation on hooks

If you're done everything corretly, then whenever you type a message to your bot, you'll get a response.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay