Alexander Kim
Posted on July 21, 2024
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 }
})
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.
Posted on July 21, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.