In this guide, you will learn how to use Grammy SDK to create a telegram bot in a Next.js application. You will go through the process of setting up a new Next.js project, configuring Grammy SDK with Next.js, and create an API route to respond to user messages.
Prerequisites
You’ll need the following:
- Node.j 20 or later
Table Of Contents
- Create a new Next.js application
- Integrate Grammy SDK in your Next.js project
- Create a Telegram Webhook API Route
- Deploy to Vercel
- Set the API Route as Telegram Bot Webhook
Create a new Next.js application
Let’s get started by creating a new Next.js project. Open your terminal and run the following command:
npx create-next-app@latest my-appWhen prompted, choose:
Yeswhen prompted to use TypeScript.Nowhen prompted to use ESLint.Yeswhen prompted to use Tailwind CSS.Nowhen prompted to usesrc/directory.Yeswhen prompted to use App Router.Nowhen prompted to customize the default import alias (@/*).
Once that is done, move into the project directory and start the app in development mode by executing the following command:
cd my-appnpm run devThe app should be running on localhost:3000. Now, let’s close the developement server to install Grammy SDK.
Integrate Grammy SDK in your Next.js project
First, run the following command to install the Grammy SDK:
grammy: A package that makes it easy to create Telegram bots.
npm install grammyFurther, perform the following code addition in next.config.mjs file to allow grammy to use Node.js specific features in Next.js App Router:
// File: next.config.mjs // [!code focus]
/** @type {import('next').NextConfig} */const nextConfig = { experimental: { // [!code ++] // [!code focus] serverComponentsExternalPackages: ['grammy'], // [!code ++] // [!code focus] }, // [!code ++] // [!code focus]}
export default nextConfigNow, let’s move on to creating an API route to respond to user messages with the bot.
Create a Telegram Webhook API Route
To create an API route that responds to the POST request by Telegram to respond to user messages interacting with your bot, create a file named route.ts in the app/api/bot directory with the following code:
export const dynamic = 'force-dynamic'
export const fetchCache = 'force-no-store'
import { Bot, webhookCallback } from 'grammy'
const token = process.env.TELEGRAM_BOT_TOKEN
if (!token) throw new Error('TELEGRAM_BOT_TOKEN environment variable not found.')
const bot = new Bot(token)bot.on('message:text', async (ctx) => { await ctx.reply(ctx.message.text)})
export const POST = webhookCallback(bot, 'std/http')The code above does the following:
- Makes sure that each request is processed dynamically and responses are not cached.
- Imports the
BotandwebhookCallbackhelpers from the Grammy SDK. - Initializes a Telegram Bot API compatible bot instance.
- Exports the
webhookCallbackhelper relying on standard HTTP Request and Response mechanism as the handler to incomingPOSTrequests.
With that done, let’s move on to deploying the application.
Deploy to Vercel
The code is now ready to deploy to Vercel. Use the following steps to deploy:
- Start by creating a GitHub repository containing your app’s code.
- Then, navigate to the Vercel Dashboard and create a New Project.
- Link the new project to the GitHub repository you have just created.
- In Settings, update the Environment Variables to match those in your local
.envfile. - Deploy! 🚀
Set the API Route as Telegram Bot Webhook
To configure Telegram to invoke the /api/bot route to respond to user interactions with your bot, run the following command after updating it with your Telegram Bot Token and Vercel Deployment URL.
curl https://api.telegram.org/bot<telegram_bot_token>/setWebhook?url=https://<your-deployment.vercel>.app/api/botConclusion
In this guide, you learned how to integrate Grammy SDK to create your own Telegram Bot in Next.js. Further, you learnt how to point Telegram Bot to your custom deployment URL to respond to user messages with the bot.
If you have any questions or comments, feel free to reach out to me on Twitter.