Published: Aug 4, 2025

How to Create a Telegram Bot and Send Automatic Notifications

In this post, I'll show you how to create a Telegram bot in just a few simple steps and connect it to your system to get automatic notifications about new user registrations 🚀

1. Why a Telegram Bot? 🤔

When I was building my app, I wanted to stay updated every time a new user signed up. Email notifications were getting lost in my inbox, and I needed something more immediate and reliable.

My goals were:

  • Get instant notifications on my phone 📱
  • Simple setup without complex infrastructure
  • Reliable delivery (Telegram is super reliable)
  • Easy to extend for other notifications later

2. Creating Your First Telegram Bot 🤖

Step 1: Talk to BotFather

Open Telegram and search for @BotFather - this is Telegram's official bot for creating bots.

Screenshot of the BotFather conversation - your gateway to creating Telegram bots

Step 2: Create Your Bot

Send /newbot to BotFather and follow these steps:

  1. Choose a name - This is the display name (e.g., "My App Notifications")
  2. Choose a username - Must end with "bot" (e.g., "myapp_notifications_bot")
BotFather Commands
/newbot
My App Notifications
myapp_notifications_bot

🎉 BotFather will give you a bot token - save this! It looks like: 1234567890:ABCdefGhIJKlmNoPQRsTuVwXyZ

Step 3: Get Your Chat ID

To send messages to yourself, you need your Chat ID:

  1. Start a conversation with your new bot
  2. Send any message to your bot
  3. Copy and paste this URL into your browser (replace <YOUR_BOT_TOKEN> with your actual token):
Get Updates URL
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
  1. Look for the chat.id in the response
Example API Response
{
  "result": [
    {
      "update_id": 123456789,
      "message": {
        "message_id": 1,
        "from": { "id": 987654321, "first_name": "Your Name" },
        "chat": { "id": 987654321, "type": "private" },
        "text": "Hello bot!"
      }
    }
  ]
}

📝 Your Chat ID is the number in "chat": { "id": 987654321 }

3. Setting Up Environment Variables 🔧

Add these to your .env file:

.env
TELEGRAM_BOT_TOKEN=1234567890:ABCdefGhIJKlmNoPQRsTuVwXyZ
TELEGRAM_CHAT_ID=987654321

🔒 Never commit your bot token - keep .env private!

4. Creating the Notification Function 📨

Here's a simple function to send messages via your bot:

lib/telegram.ts
export async function sendTelegramMessage(message: string) {
  const botToken = process.env.TELEGRAM_BOT_TOKEN;
  const chatId = process.env.TELEGRAM_CHAT_ID;

  if (!botToken || !chatId) {
    console.error('Missing Telegram credentials');
    return false;
  }

  try {
    const response = await fetch(
      `https://api.telegram.org/bot${botToken}/sendMessage`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          chat_id: chatId,
          text: message,
          parse_mode: 'HTML', // Allows basic HTML formatting
        }),
      }
    );

    if (!response.ok) {
      console.error('Telegram API error:', data);
      return false;
    }
    
    const data = await response.json();

    console.log('Message sent successfully:', data);
    return true;
  } catch (error) {
    console.error('Error sending Telegram message:', error);
    return false;
  }
}

5. Integrating with User Registration 👥

Now let's add this to your user registration flow. Here's how I integrated it with my Next.js app:

actions/register-user.ts
'use server';

import { db } from '@/lib/db';
import { sendTelegramMessage } from '@/lib/telegram';

export async function registerUser(userData: {
  email: string;
  name: string;
}) {
  try {
    // 1. Create the user in your database
    const user = await db.user.create({
      data: {
        email: userData.email,
        name: userData.name,
        createdAt: new Date(),
      },
    });

    // 2. Send Telegram notification
    const message = `
🎉 <b>New User Registration!</b>

👤 <b>Name:</b> ${user.name}
📧 <b>Email:</b> ${user.email}
📅 <b>Date:</b> ${new Date().toLocaleDateString()}

Total users: ${await db.user.count()}
    `;

    await sendTelegramMessage(message);

    return { success: true, user };
  } catch (error) {
    console.error('Registration error:', error);
    return { 
      success: false, 
      error: 'Failed to register user' 
    };
  }
}

What's happening here:

  • User gets created in the database first
  • A nicely formatted message is sent to Telegram
  • HTML formatting makes it look professional
  • We include a user count for extra context

6. Advanced: Rich Notifications with Buttons 🎛️

Want to make your notifications interactive? Add inline buttons:

lib/telegram-advanced.ts
export async function sendUserRegistrationNotification(user: {
  id: string;
  name: string;
  email: string;
}) {
  const message = `
🆕 <b>New User Registered!</b>

👤 ${user.name}
📧 ${user.email}
🕐 ${new Date().toLocaleString()}
  `;

  const keyboard = {
    inline_keyboard: [
      [
        {
          text: '👀 View Profile',
          url: `https://yourapp.com/admin/users/${user.id}`
        },
        {
          text: '📊 Dashboard',
          url: 'https://yourapp.com/admin'
        }
      ]
    ]
  };

  try {
    const response = await fetch(
      `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/sendMessage`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          chat_id: process.env.TELEGRAM_CHAT_ID,
          text: message,
          parse_mode: 'HTML',
          reply_markup: keyboard,
        }),
      }
    );

    return response.ok;
  } catch (error) {
    console.error('Telegram notification failed:', error);
    return false;
  }
}

7. Testing Your Setup 🧪

Create a simple test function to make sure everything works:

scripts/test-telegram.ts
import { sendTelegramMessage } from '@/lib/telegram';

async function testTelegramBot() {
  const testMessage = `
🧪 <b>Bot Test</b>

This is a test message to verify your Telegram bot is working!

✅ Bot token: Connected
✅ Chat ID: Valid
🕐 ${new Date().toLocaleString()}
  `;

  const success = await sendTelegramMessage(testMessage);
  
  if (success) {
    console.log('✅ Telegram bot is working!');
  } else {
    console.log('❌ Something went wrong');
  }
}

testTelegramBot();

Run it with: npx tsx scripts/test-telegram.ts

8. Visual Flow Overview 📊

Complete flow: User registers → Database saves → Telegram notification sent → You get instant alert on your phone

9. Pro Tips & Best Practices 💡

Rate Limiting

Telegram has rate limits. If you're sending lots of messages, add a queue:

lib/telegram-queue.ts
class TelegramQueue {
  private queue: string[] = [];
  private processing = false;

  async add(message: string) {
    this.queue.push(message);
    if (!this.processing) {
      this.process();
    }
  }

  private async process() {
    this.processing = true;
    while (this.queue.length > 0) {
      const message = this.queue.shift()!;
      await sendTelegramMessage(message);
      // Wait 1 second between messages
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
    this.processing = false;
  }
}

export const telegramQueue = new TelegramQueue();

Error Handling

Always handle failures gracefully:

// Don't let Telegram failures break user registration
try {
  await sendTelegramMessage(message);
} catch (error) {
  // Log but don't throw - user registration should still work
  console.error('Telegram notification failed:', error);
}

Multiple Chat IDs

Send to different people for different events:

.env
TELEGRAM_BOT_TOKEN=your_bot_token
TELEGRAM_ADMIN_CHAT_ID=123456789    # For admin notifications
TELEGRAM_SALES_CHAT_ID=987654321    # For sales notifications

10. What's Next? 🚀

Now that you have the basics working, you can extend this to:

  • 💰 Payment notifications
  • 🐛 Error alerts
  • 📈 Daily/weekly reports
  • 🔔 Custom user actions
  • 📊 Analytics summaries

The possibilities are endless! Telegram bots are incredibly versatile and this foundation will serve you well for all kinds of notifications.


Got questions? Drop me a message - I love helping fellow developers build cool stuff!