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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay