Skip to content

Commit

Permalink
feat: support for telegraf@4
Browse files Browse the repository at this point in the history
close #1
  • Loading branch information
Tsuk1ko committed Jan 17, 2022
1 parent 71f4cfc commit e745e76
Show file tree
Hide file tree
Showing 14 changed files with 1,987 additions and 70 deletions.
3 changes: 0 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
package-lock.json
yarn.lock

# Logs
logs
*.log
Expand Down
60 changes: 38 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Make [telegraf](https://github.com/telegraf/telegraf) (a telegram bot framework)

You can use [cfworker-telegraf-template](https://github.com/Tsuk1ko/cfworker-telegraf-template) directly.

> v1 only support telegraf v3. If you want to use telegraf v4, please upgrade to v2.
> v2 only support for telegraf@4. If you want to use telegraf@3, please downgrade to v1.
## Installation

Expand All @@ -16,6 +16,15 @@ npm i cfworker-middware-telegraf

## Usage

### 0. Install dependencies

Here we use webpack 5.

```bash
npm i @cfworker/web telegraf cfworker-middware-telegraf
npm i -D webpack webpack-cli node-polyfill-webpack-plugin
```

### 1. Write your code

```js
Expand All @@ -37,46 +46,53 @@ new Application().use(router.middleware).listen();

```js
// webpack.config.js
const path = require('path');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');

module.exports = {
entry: path.resolve(__dirname, 'index.js'),
target: 'webworker',
entry: './index.js',
mode: 'production',
node: {
fs: 'empty',
output: {
filename: 'worker.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.mjs$/,
include: /node_modules/,
type: 'javascript/auto',
},
],
mode: 'production',
resolve: {
fallback: {
fs: false,
},
},
plugins: [new NodePolyfillPlugin()],
performance: {
hints: false,
},
};
```

Just copy and paste built code to cfworker online editor and save.
```bash
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](https://developers.cloudflare.com/workers/tooling/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.
Or you can use [Wrangler](https://developers.cloudflare.com/workers/cli-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.

```js
const Telegraf = require('telegraf');
const { Telegraf } = require('telegraf');
const bot = new Telegraf('BOT_TOKEN');

// set webhook
bot.telegram.setWebhook('https://your.cfworker.domain/SECRET_PATH');
(async () => {
// set webhook
await bot.telegram.setWebhook('https://your.cfworker.domain/SECRET_PATH');

// delete webhook
// bot.telegram.deleteWebhook();
// delete webhook
// await bot.telegram.deleteWebhook();

// get webhook info
// bot.telegram.getWebhookInfo().then(console.log);
// get webhook info
await bot.telegram.getWebhookInfo().then(console.log);
})();
```
7 changes: 0 additions & 7 deletions index.d.ts

This file was deleted.

6 changes: 0 additions & 6 deletions index.js

This file was deleted.

28 changes: 22 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
{
"name": "cfworker-middware-telegraf",
"version": "1.0.1",
"version": "2.0.0",
"description": "Make telegraf (a telegram bot framework) useable in Cloudflare Workers",
"main": "index.js",
"main": "src/index.js",
"exports": {
".": "./src/index.js"
},
"repository": "https://github.com/Tsuk1ko/cfworker-middware-telegraf",
"author": "神代綺凜 <i@loli.best>",
"license": "MIT",
Expand All @@ -15,12 +18,25 @@
"telegram",
"bot"
],
"files": [
"src"
],
"scripts": {
"test": "webpack -c test/webpack.config.js"
},
"devDependencies": {
"@cfworker/web": "^1.3.0",
"telegraf": "^3.38.0"
"@cfworker/web": "^1.12.0",
"dotenv": "^14.1.0",
"node-polyfill-webpack-plugin": "^1.1.4",
"telegraf": "^4.6.0",
"webpack": "^5.66.0",
"webpack-cli": "^4.9.1"
},
"peerDependencies": {
"@cfworker/web": "^1.3.0",
"telegraf": "^3.38.0"
"@cfworker/web": "^1.12.0",
"telegraf": "^4.6.0"
},
"dependencies": {
"abortcontroller-polyfill": "^1.7.3"
}
}
6 changes: 6 additions & 0 deletions src/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Middleware } from '@cfworker/web';
import { Telegraf } from 'telegraf';

declare function telegrafMiddware(bot: Telegraf): Middleware;

export = telegrafMiddware;
13 changes: 13 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
require('abortcontroller-polyfill/dist/polyfill-patch-fetch');
require('./urlPatch');
const telegrafResponseBuilder = require('./telegrafResponseBuilder');

/**
* @param {import('telegraf').Telegraf} bot
*/
module.exports = bot => {
return async ({ req, res }) => {
await bot.handleUpdate(await req.body.json(), telegrafResponseBuilder(res));
res.status = 200;
};
};
10 changes: 0 additions & 10 deletions src/telegrafResponseBuilder.d.ts

This file was deleted.

33 changes: 17 additions & 16 deletions src/telegrafResponseBuilder.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
/**
* @param {import('@cfworker/web').ResponseBuilder} res
*/
module.exports = res => {
return new Proxy(
Object.assign(res, {
set: (...args) => res.headers.set(...args),
header: res.headers,
}),
{
set(obj, prop, value) {
if (prop === 'body' && ['Object', 'Array'].includes(Object.getPrototypeOf(value).constructor.name)) {
obj.body = JSON.stringify(value);
obj.headers.set('content-type', 'application/json');
return true;
}
return Reflect.set(...arguments);
},
}
);
let writableEnded = false;
const modRes = Object.assign(res, {
headersSent: false,
setHeader: (name, value) => res.headers.set(name, value),
end: data => {
if (writableEnded) return;
res.body = data;
writableEnded = true;
},
});
Object.defineProperty(modRes, 'writableEnded', {
get: () => writableEnded,
});
return modRes;
};
1 change: 1 addition & 0 deletions src/urlPatch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
require('url').URL = URL;
13 changes: 13 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const { Telegraf } = require('telegraf');
const { Application, Router } = require('@cfworker/web');
const createTelegrafMiddware = require('../');

const bot = new Telegraf(BOT_TOKEN);
bot.start(ctx => ctx.reply('Welcome'));
bot.help(ctx => ctx.reply('Send me a sticker'));
bot.on('sticker', ctx => ctx.reply('👍'));
bot.hears('hi', ctx => ctx.reply('Hey there'));

const router = new Router();
router.post(`/${SECRET_PATH}`, createTelegrafMiddware(bot));
new Application().use(router.middleware).listen();
14 changes: 14 additions & 0 deletions test/webhook.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
require('dotenv').config();
const { Telegraf } = require('telegraf');
const bot = new Telegraf(process.env.BOT_TOKEN);

(async () => {
// set webhook
await bot.telegram.setWebhook(`${process.env.BOT_WEBHOOK}/${process.env.SECRET_PATH || ''}`);

// delete webhook
// await bot.telegram.deleteWebhook();

// get webhook info
await bot.telegram.getWebhookInfo().then(console.log);
})();
32 changes: 32 additions & 0 deletions test/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
require('dotenv').config();
const path = require('path');
const { DefinePlugin } = require('webpack');
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(),
new DefinePlugin({
BOT_TOKEN: JSON.stringify(process.env.BOT_TOKEN || ''),
SECRET_PATH: JSON.stringify(process.env.SECRET_PATH || ''),
}),
],
optimization: {
minimize: false,
},
performance: {
hints: false,
},
};
Loading

0 comments on commit e745e76

Please sign in to comment.