npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

telegraf-throttler

v0.6.0

Published

A middleware for Telegraf, that throttles inbound and outbound requests from Telegram

Downloads

3,181

Readme

Telegraf Throttler

Known Vulnerabilities

Throttling middleware for Telegraf bot framework, written in Typescript and built with Bottleneck.

Installation

yarn install telegraf-throttler

About

This throttler aims to throttle incoming updates from Telegram, and outgoing calls to the Telegram API. The incoming throttler aims to protect the bot from abuses (e.g. user forwarding tons of messages to the bot to flood it), while the outgoing throttler aims to limit and queue outgoing Telegram API calls to conform to the official Telegram API rate limits.

Configuration

The throttler accepts a single optional argument of the following form:

type ThrottlerOptions = {
  group?: Bottleneck.ConstructorOptions,      // For throttling outgoing group messages
  in?: Bottleneck.ConstructorOptions,         // For throttling incoming messages
  out?: Bottleneck.ConstructorOptions,        // For throttling outgoing private messages
  inKey?: 'from' | 'chat',                    // Throttle inbound by from.id (default) or chat.id
  inThrottlerError?: InThrottlerErrorHandler, // For custom inThrottler error handling
}

The full list of object properties available for Bottleneck.ConstructorOptions can be found at Bottleneck.

If no argument is passed, the throttler created will use the default configuration settings which should be appropriate for most use cases. The default configuration are as follows:

// Outgoing Group Throttler
const groupConfig = {
  maxConcurrent: 1,                // Only 1 job at a time
  minTime: 333,                    // Wait this many milliseconds to be ready, after a job
  reservoir: 20,                   // Number of new jobs that throttler will accept at start
  reservoirRefreshAmount: 20,      // Number of jobs that throttler will accept after refresh
  reservoirRefreshInterval: 60000, // Interval in milliseconds where reservoir will refresh
};

// Incoming Throttler
const inConfig = {
  highWater: 3,                       // Trigger strategy if throttler is not ready for a new job
  maxConcurrent: 1,                   // Only 1 job at a time
  minTime: 333,                       // Wait this many milliseconds to be ready, after a job
  strategy: Bottleneck.strategy.LEAK, // Drop jobs if throttler is not ready
}

// Outgoing Private Throttler
const outConfig = {
  minTime: 25,                    // Wait this many milliseconds to be ready, after a job
  reservoir: 30,                  // Number of new jobs that throttler will accept at start
  reservoirRefreshAmount: 30,     // Number of jobs that throttler will accept after refresh
  reservoirRefreshInterval: 1000, // Interval in milliseconds where reservoir will refresh
};

// Default Error Handler
const defaultErrorHandler = async (ctx, next, error) => {
  return console.warn(`Inbound ${ctx.from?.id || ctx.chat?.id} | ${error.message}`)
};

Example

// Simple use case (Typescript)
import { Telegraf } from 'telegraf';
import { telegrafThrottler } from 'telegraf-throttler';

const bot = new Telegraf(process.env.BOT_TOKEN);

const throttler = telegrafThrottler();
bot.use(throttler);

bot.command('/example', ctx => ctx.reply('I am throttled'));
bot.launch();
// Simple use case (Javascript)
const { Telegraf } = require('telegraf');
const { telegrafThrottler } = require('telegraf-throttler');

const bot = new Telegraf(process.env.BOT_TOKEN);

const throttler = telegrafThrottler();
bot.use(throttler);

bot.command('/example', ctx => ctx.reply('I am throttled'));
bot.launch();
// Custom use case (Typescript)
import { Composer, Context, Middleware, Telegraf } from 'telegraf';
import { telegrafThrottler } from 'telegraf-throttler';

const bot = new Telegraf(process.env.BOT_TOKEN);

const privateThrottler = telegrafThrottler();
const groupThrottler = telegrafThrottler({
  in: { // Aggresively drop inbound messages
    highWater: 0,                       // Trigger strategy if throttler is not ready for a new job
    maxConcurrent: 1,                   // Only 1 job at a time
    minTime: 30000,                      // Wait this many milliseconds to be ready, after a job
  },
  inKey: 'chat', // Throttle inbound messages by chat.id instead
});

const partitioningMiddleware: Middleware<Context> = (ctx, next) => {
  const chatId = Number(ctx.chat?.id);
  return Composer.optional(() => chatId < 0, groupThrottler, privateThrottler)(ctx, next);
};
bot.use(partitioningMiddleware);

bot.command('/example', ctx => ctx.reply('I am seriously throttled!'));
bot.launch();