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

PHPz
發布: 2024-08-19 18:32:03
原創
811 人瀏覽過

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
登入後複製

Tip:If you don't have npm installed, you can easily get it by downloading and installingNode.jsfrom 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
登入後複製

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, selectTemplate from a GitHub repoand enter:

https://github.com/m-sarabi/cloudflare-telegram-bot
登入後複製

Then selectTypescriptwhen 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 selectingNofor 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 = "" TOKEN = ""
登入後複製
  • 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
登入後複製

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 selectWorkers & Pages.
  3. Next to your project name, clickVisit.
  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 clickingStart(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

以上是Deploying Your Telegram Bots on Cloudflare Workers: A Step-by-Step Guide的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!