DEV Community

Ban My Account
Ban My Account

Posted on

Create Telegram Bot - NextJS and Hosting on Vercel - Free

Here's a more comprehensive guide:

  1. Create a Telegram Bot:

    • Go to Telegram and search for the BotFather.
    • Start a conversation with BotFather and follow the instructions to create a new bot.
    • Once created, BotFather will provide you with a token. Save this token securely; you'll need it later.
  2. Set up a Next.js Project:

    • Install Node.js if you haven't already.
    • Initialize a new Next.js project using create-next-app or any other method you prefer.
  3. Set up Telegram Bot API:

    • Use a library like node-telegram-bot-api to interact with the Telegram Bot API. Install it via npm or yarn.
    • Create a new file in your Next.js project to handle the bot logic.
    • Use the Telegram Bot API library to set up a webhook and handle incoming messages.
  4. Write Your Telegram Bot Code:

    • Here's a basic example:
// Import necessary modules
const { Telegraf } = require('telegraf');

// Create a new Telegraf bot instance with your bot token
const bot = new Telegraf(process.env.TELEGRAM_BOT_TOKEN);

// Handle incoming messages
bot.on('text', (ctx) => {
  ctx.reply('Hello! You said: ' + ctx.message.text);
});

// Set up webhook
bot.telegram.setWebhook('https://your-vercel-url.vercel.app/webhook');

// Start listening for incoming messages
bot.startPolling();
Enter fullscreen mode Exit fullscreen mode
  1. Deploy Your Next.js Project to Vercel:

    • Sign up for Vercel if you haven't already.
    • Install the Vercel CLI if you haven't already (npm install -g vercel).
    • Run vercel login to log in to your Vercel account via CLI.
    • Navigate to your Next.js project directory in the terminal.
    • Run vercel --prod to deploy your project to Vercel.
  2. Set Environment Variables:

    • In your Vercel project settings, set the environment variable TELEGRAM_BOT_TOKEN to the token you obtained from BotFather.
  3. Set Webhook URL using curl:

    • Open a terminal and run the following command, replacing <YOUR_BOT_TOKEN> with your actual bot token and https://your-vercel-url.vercel.app/webhook with your Vercel webhook URL:
   curl -F "url=https://your-vercel-url.vercel.app/webhook" https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook
Enter fullscreen mode Exit fullscreen mode
  1. Verify Webhook Setup:
    • You can verify that the webhook is set up correctly by visiting the following URL in your browser:
   https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getWebhookInfo
Enter fullscreen mode Exit fullscreen mode
  1. Handle Incoming Messages:
    • Ensure that your Next.js server is listening for incoming POST requests on the /webhook endpoint and processing the messages accordingly.

That's it! With these steps, you've set up a webhook for your Telegram bot using Next.js deployed on Vercel. Make sure to handle messages appropriately in your server-side logic.

Top comments (0)