Send message with Telegram bot in Nuxt
To send a message via Telegram bot in a Nuxt application, create a server API route that uses the native fetch method to call the Telegram Bot API sendMessage endpoint. Secure your bot token using Nuxt runtime configuration, then trigger the message from your frontend component.
Sodara Sou
Create Telegram bot
- Search for BotFather in Telegram
- Type in
/newbotin the BotFather chat to create a bot - Type in the bot name
- Type in the bot username which end with the word bot
- Finally copy the bot access token and keep it securly
Setup Telegram bot in Nuxt
Create an .env file and store the bot access token in there:
NUXT_TELEGRAM_BOT_TOKEN=<bot_access_token>
In the nuxt.config.ts file put this in:
runtimeConfig: {
telegramBotToken: "",
}
Nuxt config will pick up the the value of the variables in the
.envfile that start with theNUXT_automatically but you have to register it like in the snippet above so that you can access it fromuseRuntimeConfig()in our app.
Create an API endpoint to send message to Telegram
Create a file at server/api/send-telegram.post.ts to securely handle the request on the server side:
export default defineEventHandler(async (event) => {
const body = await readBody(event)
const config = useRuntimeConfig(event)
const token = config.telegramBotToken
const message = body.message
const url = `https://telegram.org/bot${token}/sendMessage`
try {
const response = await $fetch(url, {
method: 'POST',
body: {
chat_id: <your_chat_id>,
text: message,
},
})
return { success: true, data: response }
} catch (error) {
throw createError({
statusCode: 500,
statusMessage: 'Failed to send Telegram message',
})
}
})
To get the chat id you can check it out in the the browser URL of the chat you have with the bot.
Trigger it from Vue component
Call the server endpoint from your page or component using $fetch:
<script setup lang="ts">
const messageText = ref('')
const status = ref('')
const sendMessage = async () => {
try {
status.value = 'Sending...'
await $fetch('/api/send-telegram', {
method: 'POST',
body: { message: messageText.value },
})
status.value = 'Message sent successfully!'
messageText.value = ''
} catch (err) {
status.value = 'Error sending message.'
}
}
</script>
<template>
<div>
<textarea v-model="messageText" placeholder="Type your message..."></textarea>
<button @click="sendMessage">Send to Telegram</button>
<p>{{ status }}</p>
</div>
</template>
That it!