Sending notifications or form submissions directly to your Telegram can be a very useful feature in a web application. For example, you might want to receive contact form submissions or system notifications instantly in your Telegram account or group. In this tutorial, we’ll show how to send messages directly to Telegram from a Next.js app using the Telegram Bot API.
What is the Telegram Bot API?
The Telegram Bot API allows developers to control bots and send messages via HTTP requests. A bot is an automated account on Telegram that can send and receive messages, and using it to notify you or your team of new submissions from your web app is a great use case.
Step 1: Setting Up Your Telegram Bot
To send messages via the Telegram Bot API, you first need to create a bot and get its Bot Token.
1.1 Create a Bot Using BotFather
Open Telegram and search for @botfather. BotFather is the official bot used to create and manage Telegram bots.
Start a chat with BotFather and type /start.
To create a new bot, type /newbot and follow the instructions:
Choose a name for your bot (e.g., MyNotificationBot).
Choose a username for your bot (must end with bot, like MyNotifBot_bot).
- Once the bot is created, BotFather will give you a Bot Token. This token looks something like this:
123456789:ABCdefGhIJKlmNOPqrsTUVwxyz123456789
Save this token because you'll need it later.
1.2 Get Your Chat ID
The Chat ID is the ID of the user or group where the bot will send messages.
- For a Personal Chat: Start a conversation with your bot in Telegram and send any message. Then, visit the following URL to get updates from the bot:
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
Replace with your actual bot token. The JSON response will include a chat object that contains the id. This is your Chat ID.
- For a Group Chat: Add your bot to a group, send a message, and use the same URL above to get the group Chat ID. Group Chat IDs typically start with a - (e.g., -987654321).
Step 2: Set Up a Next.js API Route
Now that you have your bot's token and chat ID, you can set up a Next.js API route to send messages via Telegram.
2.1 Create an API Route
In Next.js, you can create an API route to handle the message sending logic. In this case, we’ll send a POST request to the Telegram Bot API whenever someone submits a form on the website.
// pages/api/contact.js
import axios from 'axios';
export default async function handler(req, res) {
if (req.method === 'POST') {
const { name, email, message } = req.body;
// Replace with your actual bot token and chat ID
const botToken = process.env.TELEGRAM_BOT_TOKEN;
const chatId = process.env.TELEGRAM_CHAT_ID;
const telegramUrl = `https://api.telegram.org/bot${botToken}/sendMessage`;
const text = `
New message from ${name} \n
Email: ${email} \n
Message: ${message}
`;
try {
// Send the message via the Telegram Bot API
const response = await axios.post(telegramUrl, {
chat_id: chatId,
text: text,
});
if (response.data.ok) {
return res.status(200).json({ success: true, message: 'Message sent successfully!' });
} else {
return res.status(500).json({ success: false, message: 'Failed to send message.' });
}
} catch (error) {
console.error('Error sending message to Telegram:', error);
return res.status(500).json({ success: false, message: 'Error sending message.' });
}
} else {
return res.status(405).json({ message: 'Method not allowed' });
}
}
Breakdown:
- Telegram Bot Token and Chat ID: We use environment variables to store sensitive data like the bot token and chat ID.
- POST Request to Telegram API: We send the message via the Telegram Bot API using the /sendMessage endpoint.
- Axios: The axios library is used to make the HTTP request to Telegram's API.
2.2 Add Environment Variables
To avoid hardcoding sensitive data in your code, store your bot token and chat ID in environment variables. In your .env.local file, add:
TELEGRAM_BOT_TOKEN=your_bot_token
TELEGRAM_CHAT_ID=your_chat_id
Make sure to restart your development server after adding or updating the environment variables.
Step 3: Create a Contact Form
Now that the API route is ready, let's create a Contact Form component to allow users to submit messages.
"use client";
import { useState } from 'react';
import axios from 'axios';
import { toast } from 'react-toastify'; // Optional for notifications
function ContactForm() {
const [userInput, setUserInput] = useState({
name: '',
email: '',
message: ''
});
const handleChange = (e) => {
const { name, value } = e.target;
setUserInput({ ...userInput, [name]: value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('/api/contact', userInput);
if (response.status === 200) {
toast.success('Message sent successfully!');
setUserInput({ name: '', email: '', message: '' });
} else {
toast.error('Failed to send message.');
}
} catch (error) {
toast.error('Error sending message.');
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Your Name:</label>
<input
type="text"
name="name"
value={userInput.name}
onChange={handleChange}
required
/>
</div>
<div>
<label>Your Email:</label>
<input
type="email"
name="email"
value={userInput.email}
onChange={handleChange}
required
/>
</div>
<div>
<label>Your Message:</label>
<textarea
name="message"
value={userInput.message}
onChange={handleChange}
required
/>
</div>
<button type="submit">Send Message</button>
</form>
);
}
export default ContactForm;
Breakdown:
- useState: Handles form state for the user’s name, email, and message.
- handleSubmit: Sends a POST request to your /api/contact endpoint with the form data.
- axios: We use axios to send the form data to the server-side API route.
Step 4: Deploy Your Application
Once your contact form and API route are set up, you can deploy your app. If you’re using Vercel or Netlify, the deployment process is seamless. Don't forget to add your environment variables in your production settings.
For Vercel:
Navigate to the Project Settings.
Add your environment variables (TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID) in the Environment Variables section.
Conclusion
Integrating the Telegram Bot API with Next.js is an excellent way to receive notifications and contact form submissions without the need for complicated backend infrastructure. By leveraging Telegram's Bot API, you can automate messages and stay updated on user interactions instantly.
With this setup, you’ll have your contact form submissions sent directly to your personal or group Telegram chat. 🚀
If you have any questions or feedback, feel free to drop a comment below. Happy coding!
Top comments (0)