Home > Web Front-end > JS Tutorial > body text

Deploying Your Telegram Bots on Cloudflare Workers: A Step-by-Step Guide

PHPz
Release: 2024-08-19 18:32:03
Original
1018 people have browsed it

Deploying Your Telegram Bots on Cloudflare Workers: A Step-by-Step Guide

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
Copy after login

Tip: If you don't have npm installed, you can easily get it by downloading and installing Node.js from nodejs.org.

  1. 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
Copy after login

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
Copy after login

Then select Typescript when asked.

Make sure to go to this repository and give it a Star ⭐️ please.

  1. 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>"
Copy after login
  • SECRET: Replace with a random token that ensures requests come from your set webhook. It can be 1–256 characters, including A-Z, a-z, 0-9, _, and -.
  • API_TOKEN: Replace with the API token you got from @BotFather.

After setting these variables, run this command inside your project directory:

npm run cf-typegen
Copy after login

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'
                    }]
                ]
            }
        });
    }
}
Copy after login

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.'
            });
        }
    }
}
Copy after login

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

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!