Are you ready to build a Telegram bot without the hassle of managing servers? With Cloudflare Workers, you can deploy your bot in minutes, leveraging a powerful, scalable platform that takes care of all the heavy lifting. In this guide, we'll walk you through the entire process - from setting up your development environment to deploying a fully functional Telegram bot - all using a simple, easy-to-follow template in TypeScript. Let's dive in and get your bot up and running.
🚀 Why Choose Cloudflare Workers for Your Telegram Bot?
Cloudflare Workers is a serverless platform that allows developers to run JavaScript, TypeScript, or Python code at the edge, close to your users, with minimal latency. By leveraging this platform, you can deploy a Telegram bot that is not only lightning-fast but also highly scalable. No need to manage servers, handle scaling, or deal with complex infrastructure - Cloudflare takes care of everything for you.
📚 Step-by-Step Guide to Building Your Bot
Now let's dive into the process.
👷Create a New Worker Project
1- Set Up Your Development Environment
Before we start building, you'll need to install wrangler
, Cloudflare's command-line tool for managing Workers:
npm install wrangler
Tip: If you don't have
npm
installed, you can easily get it by downloading and installing Node.js from nodejs.org.
2- Create a New Worker Using the Telegram Bot Template
Once wrangler
is set up, navigate to the directory where you'd like your worker files to reside. Run the following command to create your worker:
npm create cloudflare@latest MY_WORKER_NAME
Replace MY_WORKER_NAME with your preferred name for the worker. If this is your first time using wrangler it will prompt you to connect to your Cloudflare account and authenticate via a browser window-just follow the instructions.
When prompted for the template, select Template from a GitHub repo and enter:
https://github.com/m-sarabi/cloudflare-telegram-bot
Then select Typescript when asked.
Please give this repository a Star ⭐️.
3- Initialize Git and Skip Deployment
During the setup, you'll be asked if you want to use Git for version control and if you wish to deploy your worker immediately. I suggest selecting No for both, holding off until we've configured everything.
You should see the message: SUCCESS Application created successfully!
🤖 Set Up Your Telegram Bot with @BotFather
1- Use the /newbot command to create your bot.
2- Follow the prompts and take note of the API token provided.
Next, we'll set up environment variables in the wrangler.toml file within your project directory. So add these lines to the file:
[vars]
SECRET = "<SECRET>"
TOKEN = "<API_TOKEN>"
-
SECRET: Replace
<SECRET>
with a random token that ensures requests come from your set webhook. It can be 1–256 characters, includingA-Z
,a-z
,0-9
,_
, and-
. -
API_TOKEN: Replace
<API_TOKEN>
with the API token you got from@BotFather
.
After setting these variables, run this command inside your project directory:
npm run cf-typegen
This command regenerates the worker-configuration.d.ts
file, reflecting your newly set variables.
💻 Writing Your Bot Logic
Now, let's get into the fun part - coding the bot! In this example we will create this:
Scenario: When a user sends the
/start
command, the bot displays a message with a button. Upon pressing the button, the bot removes it and sends a follow-up message.
Handle the /start Command
All update handler functions are in the src/Telegram/handlers
directory.
We'll start by responding to the /start
command with a message and an inline button. Modify src/Telegram/handlers/handleMessage.ts
like so:
import { tg } from '../lib/methods';
export async function handleMessage(message: tgTypes.Message) {
const messageText = message.text;
const chatId = message.chat.id;
if (messageText === '/start') {
await tg.sendMessage({
text: 'Welcome to my bot! Press the button to accept my rules!',
chat_id: chatId,
reply_markup: {
inline_keyboard: [
[{
text: 'I Accept',
callback_data: 'accept_rules'
}]
]
}
});
}
}
This code snippet sends a message with an inline keyboard button using the tg.sendMessage method.
Handle Inline Button Presses
When the user presses the inline button, we want the bot to acknowledge this action. Modify src/Telegram/handlers/handleCallbackQuery.ts
:
import { tg } from '../lib/methods';
export async function handleCallbackQuery(callbackQuery: tgTypes.CallbackQuery) {
const data = callbackQuery.data;
const messageId = callbackQuery.message?.message_id;
const chatId = callbackQuery.message?.chat.id;
if (messageId && chatId) {
if (data === 'accept_rules') {
await tg.editMessageReplyMarkup({
chat_id: chatId,
message_id: messageId,
reply_markup: undefined
});
await tg.sendMessage({
chat_id: chatId,
text: 'Thanks for accepting my rules.'
});
}
}
}
This code listens for accept_rules
data query and on match removes the inline button and sends a follow-up message using the tg.editMessageReplyMarkup method.
🔗 Registering Your Webhook
With your bot logic in place, it's time to deploy your worker and connect it to Telegram via a webhook.
1- Run wrangler deploy
to deploy your worker.
2- Navigate to your Cloudflare dashboard and select Workers & Pages.
3- Next to your project name, click Visit.
4- In the URL bar, append /registerWebhook
(e.g., https://my-project.my-username.workers.dev/registerWebhook
) and hit enter. If you see "Webhook registered" you've done it correctly!
Once deployed and registered, you can interact with your bot on Telegram. Start by clicking Start (or sending /start
), and you should see the welcome message with the inline button.
🧠 Conclusion
Building and deploying Telegram bots has never been easier thanks to Cloudflare Workers. By following this guide, you've harnessed the power of serverless technology to create a bot that's not only scalable and fast but also easy to maintain.
Whether you're building a simple bot for personal use or deploying something more complex for a business, this template provides a solid foundation. Happy coding!
🔗 Resources & Further Reading
- Cloudflare Workers Documentation
- Telegram Bot API
-
GitHub Repository for the Template
m-sarabi / cloudflare-telegram-bot
Telegram bot worker to be used on cloudflare workers
Cloudflare Telegram Bot Template
This repository provides an easy-to-use, fully documented template for building Telegram bots using Cloudflare Workers, written in TypeScript It is designed to balance staying as close as possible to the Telegram Bot API while providing ease of use and effortless deployment of serverless Telegram bots on the Cloudflare platform.
Step by step guide
Create a new worker using this template
- Install
wrangler
by runningnpm install wrangler
Note
If you need to install npm, download and install node.js from nodejs.org
- Go to a directory that you want your worker files to be in and run
npm create cloudflare@latest MY_WORKER_NAME
ReplaceMY_WORKER_NAME
with a name you like for your worker.
Note
If you are running it for the first time, it will open the browser to connect to your Cloudflare account, follow its instructions.
- For "What would you like to start with?" Choose
Template from a
…
- Install
Top comments (0)