Coder Social home page Coder Social logo

tsuk1ko / cfworker-middleware-telegraf Goto Github PK

View Code? Open in Web Editor NEW
58.0 3.0 14.0 52 KB

Make telegraf (a telegram bot framework) useable in Cloudflare Workers

Home Page: https://www.npmjs.com/package/cfworker-middleware-telegraf

License: MIT License

JavaScript 100.00%
telegraf cloudflare-workers cfworker telegram-bot telegram cloudflare

cfworker-middleware-telegraf's Introduction

cfworker-middleware-telegraf

Version

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);
})();

cfworker-middleware-telegraf's People

Contributors

tsuk1ko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cfworker-middleware-telegraf's Issues

Error: globalThis.XMLHttpRequest is not a constructor

Trying to use with wrangler v2

const { Telegraf } = require('telegraf');
const { Application, Router } = require('@cfworker/web');
const createTelegrafMiddleware = require('cfworker-middleware-telegraf');

const bot = new Telegraf("MY_TOKEN");
const router = new Router();
router.post(`/SECRET`, createTelegrafMiddleware(bot));
new Application().use(router.middleware).listen();

running wrangler dev results in Error: globalThis.XMLHttpRequest is not a constructor

The "chunk" argument must be one of type string or Buffer. Received type object

The caption command fails below in CFWorker with error:

  (error) TypeError: The "chunk" argument must be one of type string or Buffer. Received type object
    at new n2 (worker.js:16656:23)
    at worker.js:17181:95
    at A.write (worker.js:17182:10)
    at A.end (worker.js:17216:144)
    at s.addPart (worker.js:20412:73)
    at S (worker.js:20325:21)
    at async worker.js:20313:22
    at async Promise.all (index 2)
    at async _ (worker.js:20318:16)
    at async s.callApi (worker.js:20362:30)

Borrowed from https://github.com/telegraf/telegraf/blob/302a46d144993be7a95c5864c87a8d7b79230d1e/docs/examples/keyboard-bot.js#L83

import { Telegraf, Markup } from 'telegraf';
import { Application, Router } from '@cfworker/web';
import createTelegrafMiddware from 'cfworker-middware-telegraf';
import { DEFAULT_CORS_HEADERS } from './utils';

const bot = new Telegraf(TELEGRAM_API_TOKEN);

//... other commands here

bot.command('caption', (ctx) => {
  return ctx.replyWithPhoto({ url: 'https://picsum.photos/200/300/?random' },
    {
      caption: 'Caption',
      parse_mode: 'Markdown',
      ...Markup.inlineKeyboard([
        Markup.button.callback('Plain', 'plain'),
        Markup.button.callback('Italic', 'italic')
      ])
    }
  )
});

const router = new Router();

// Simple CORS middleware.
const cors = async ({ res }, next) => {
  for (const HEADER_KEY in DEFAULT_CORS_HEADERS) {
    res.headers.set(HEADER_KEY, DEFAULT_CORS_HEADERS[HEADER_KEY]);
  }
  await next();
};

router.post(`/${TELEGRAM_SECRET_PATH}`, createTelegrafMiddware(bot));
new Application().use(cors).use(router.middleware).listen();

Any suggestions?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.