Create serverless Telegram bot using Cloudflare Workers and grammY.
- Talk to BotFather and create a bot
- Get the bot token
- Create a new Cloudflare Workers
- Set a custom domain for your worker. This must be done since Telegram bot webhook API is not compatible with the SSL certificate of Cloudflare Workers' default domain (
https://<worker-name>.<your-account>.workers.dev)
- Click
Use this templateto create a new repo from this template - Clone the repo you just created
- Change field
nameinwrangler.toml&package.jsonto your Cloudflare Worker name - Install dependencies:
npm i - Set the bot token as a secret environment variable:
npx wrangler secret put TELEGRAM_BOT_API_TOKEN, then paste the token - Set a secret token for webhook verification:
npx wrangler secret put TELEGRAM_BOT_SECRET_TOKEN, then paste a random string (see Telegram docs for more details) - Upload the worker:
npx wrangler publish
Visit https://api.telegram.org/bot<TELEGRAM_BOT_API_TOKEN>/setWebhook?url=https://<YOUR_CUSTOM_DOMAIN>&secret_token=<TELEGRAM_BOT_SECRET_TOKEN> to set the webhook.
For example, you got TELEGRAM_BOT_API_TOKEN of 000000:AAAAAAAAAAAA, YOUR_CUSTOM_DOMAIN of bot.example.com and TELEGRAM_BOT_SECRET_TOKEN of foo, visit:
https://api.telegram.org/bot000000:AAAAAAAAAAAA/setWebhook?url=https://bot.example.com&secret_token=foo
Send /start to your bot and it should reply Hello, world!.
Change the code in src/bot.ts to write your own bot. See grammY docs for more details.
https://developers.cloudflare.com/workers/wrangler/workers-kv/
- Create a new KV namespace with Wrangler:
npx wrangler kv:namespace create <YOUR_NAMESPACE> - Change fields in
kv_namespacesinwrangler.tomlto the output of the previous command - Declare the KV binding in
src/env.ts - Use Worker KV in your code.
No comments:
Post a Comment