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.
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.
Now let's dive into the process.
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.
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.
Make sure to go to this repository and give it a Star ⭐️ please.
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!
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>"
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.
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.
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.
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.
With your bot logic in place, it's time to deploy your worker and connect it to Telegram via a webhook.
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.
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!
The above is the detailed content of Deploying Your Telegram Bots on Cloudflare Workers: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!