cfworker-middleware-telegraf
v2.0.2
Published
Make telegraf (a telegram bot framework) useable in Cloudflare Workers
Downloads
344
Maintainers
Readme
cfworker-middleware-telegraf
Make telegraf (a telegram bot framework) useable in Cloudflare Workers.
You can use cfworker-telegraf-template directly.
v2 only support for telegraf@4. If you want to use telegraf@3, please downgrade to v1.
Installation
npm i cfworker-middleware-telegraf
Usage
0. Install dependencies
Here we use webpack 5.
npm i @cfworker/web telegraf cfworker-middleware-telegraf
npm i -D webpack webpack-cli node-polyfill-webpack-plugin
1. Write your code
// index.js
const { Telegraf } = require('telegraf');
const { Application, Router } = require('@cfworker/web');
const createTelegrafMiddleware = require('cfworker-middleware-telegraf');
const bot = new Telegraf(self.BOT_TOKEN);
// Your code here, but do not `bot.launch()`
// Do not forget to set environment variables BOT_TOKEN and SECRET_PATH on your worker
const router = new Router();
router.post(`/${self.SECRET_PATH}`, createTelegrafMiddleware(bot));
new Application().use(router.middleware).listen();
2. Webpack your code and upload to cfworker
// webpack.config.js
const path = require('path');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
module.exports = {
entry: path.resolve(__dirname, 'index.js'),
target: 'webworker',
output: {
filename: 'worker.js',
path: path.resolve(__dirname, 'dist'),
},
mode: 'production',
resolve: {
fallback: {
fs: false,
},
},
plugins: [new NodePolyfillPlugin()],
performance: {
hints: false,
},
};
npx webpack -c webpack.config.js
Just copy and paste built code dist/worker.js
to cfworker online editor and save.
Or you can use Wrangler, an official CLI tool, so you don't need to copy and paste code manually anymore. But I don't like it due to its inexplicable bugs on Win10.
3. Set telegram bot webhook
These codes only need to be run once locally.
const { Telegraf } = require('telegraf');
const bot = new Telegraf('YOUR_BOT_TOKEN');
(async () => {
// set webhook
await bot.telegram.setWebhook('https://your.cfworker.domain/YOUR_SECRET_PATH');
// delete webhook
// await bot.telegram.deleteWebhook();
// get webhook info
await bot.telegram.getWebhookInfo().then(console.log);
})();