Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Middleware in message handlers #893

Closed
Mohanbarman opened this issue Jul 17, 2021 · 1 comment
Closed

[Feature] Middleware in message handlers #893

Mohanbarman opened this issue Jul 17, 2021 · 1 comment

Comments

@Mohanbarman
Copy link

There is a feature in telegraf library which lets you specify middleware for your message listeners.
I did a small hack and created a function for the same

// types
type TBotMiddlewareFun = (msg: Message, meta: any, sendMessage: TSendMessage, next?: TBotNextFun) => any;
type TBotNextFun = () => any;
type TSendMessage = (message: string) => Promise<Message>;

// middleware creator
export const applyBotMiddleware = (...fns: Array<TBotMiddlewareFun>) => <T>(msg: Message, meta: T) => {
    const callNext = (fn: TBotMiddlewareFun, fnIndex: number) => {
      // exit when there is no next middleware
      if (fnIndex > fns.length - 1) return;

      fn(
         msg, meta,
         // A small helper to reply to current user  
         (message: string) =>  telegramApi.api.sendMessage(msg.chat.id, message),
         // this calls the next middleware
         async () => { callNext(fns[++fnIndex], fnIndex) }
      );
    };
    // calling first middleware
    callNext(fns[0], 0);
  };

// You can now use this function in on handlers like this
api.onText(/\/start (.+)/, applyBotMiddleware(isBlocked, skipAuthorizedUsers, startController)); 

// function signature of middleware
function middleware(ctx: Message, match: RegExpMatchArray, reply: TSendMessage, next: TBotNextFun);

Feel free to improve the solution

@kamikazechaser
Copy link
Collaborator

I'll close and pin this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants