Run your telegram bot free on cloudflare workers by using the power of Hono and grammY
- Telegram bot in Cloudflare worker
You can create your free account in cloudflare > Register an account
first you need to clone the this project:
git clone https://github.com/dinno7/telegram-bot-cloudflare.git
cd telegram-bot-cloudflare
Open the
wrangler.toml
file and:
-
Set your personal project name instead of
YOUR_APP_NAME_IN_CLOUDFLARE
-
Create a bot from BotFather and get the bot token, put it instead of
YOU_TELEGRAM_BOT_TOKEN
-
Generate hex random bytes(32-bit is enough) and put it instead of
TELEGRAM_SECRET_TOKEN_BYTES
This is for detecting telegram requests and it must be unique and secure, you can use nodejs to generate bytes by this piece of code:
require('crypto').randomBytes(32).toString('hex');
Or do it with Python:
import os;os.urandom(32).hex()
-
You can also add another env variables and use them in your app.
After configuration your app, you must deploy it by below command:
npm run deploy
After deploying your app, you must set the webhook, so:
- Go to your cloudflare account and
Workers & Pages > Overview
section of your dashboard - Select the worker whose name we set in the previous step
- Click on the
View
button on the top right to open the deployed worker address - Click on
WebHook management
link in the opened page - Paste your bot token inside the input and click on Set webhook button
- You should see success message in new open page
Your bot is ready, just go to your bot and send /start
command
- /src/index.ts
- /src/bot/index.ts
- /src/bot/handle-errors.ts
- Hono controllers
injectBotInstructions
function inside the/src/bot/instructions.ts
- Add your envirement variables inside the
wrangle.toml
and also in theEnv
interface inside the/src/types/index.ts
to get autocompletion
For adding new instructions you just need add your instructions in the injectBotInstructions function inside the
/src/bot/instructions.ts
file.
For more detail, read grammY document
You have the below routes as default for managing your telegram webhook:
- Home page: <WORKER_ORIGIN>
- Webhook management page: <WORKER_ORIGIN>/webhook
- Setting webhook route: <WORKER_ORIGIN>/webhook/set/<YOUR_BOT_TOKEN>
- Deleting webhook route: <WORKER_ORIGIN>/webhook/del/<YOUR_BOT_TOKEN>
According to the existing example(the webhook stuff) you can add your new routes easy inside the /src/api
directory:
- Add your controller functions in
/src/api/controllers
- Add your routes in
/src/api/routes
- Finally add declared route in
/src/api/index.ts
If you have any question, you can send me DM in Telegram: