Skip to content

Commit

Permalink
feat: Context::persistentChatAction (#1804)
Browse files Browse the repository at this point in the history
  • Loading branch information
orimiles5 authored Feb 23, 2023
1 parent 5137c75 commit 14d5c3f
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import ApiClient from './core/network/client'
import { Guard, Guarded, MaybeArray } from './util'
import Telegram from './telegram'
import { FmtString } from './format'
import d from 'debug'

const debug = d('telegraf:context')

type Tail<T> = T extends [unknown, ...infer U] ? U : never

Expand Down Expand Up @@ -865,6 +868,44 @@ export class Context<U extends Deunionize<tg.Update> = tg.Update> {
})
}

/**
* @see https://core.telegram.org/bots/api#sendchataction
*
* Sends the sendChatAction request repeatedly, with a delay between requests,
* as long as the provided callback function is being processed.
*
* The sendChatAction errors should be ignored, because the goal is the actual long process completing and performing an action.
*
* @param action - chat action type.
* @param callback - a function to run along with the chat action.
* @param extra - extra parameters for sendChatAction.
* @param {number} [extra.intervalDuration=8000] - The duration (in milliseconds) between subsequent sendChatAction requests.
*/
async persistentChatAction(
action: Shorthand<'sendChatAction'>[0],
callback: () => Promise<void>,
{
intervalDuration,
...extra
}: tt.ExtraSendChatAction & { intervalDuration?: number } = {}
) {
await this.sendChatAction(action, { ...extra })

const timer = setInterval(
() =>
this.sendChatAction(action, { ...extra }).catch((err) => {
debug('Ignored error while persisting sendChatAction:', err)
}),
intervalDuration ?? 4000
)

try {
await callback()
} finally {
clearInterval(timer)
}
}

/**
* @deprecated use {@link Context.sendChatAction} instead
* @see https://core.telegram.org/bots/api#sendchataction
Expand Down

0 comments on commit 14d5c3f

Please sign in to comment.