From fcd110aecab0e08bf6f6b1e3d7ce66e68ac752cd Mon Sep 17 00:00:00 2001 From: Kravets <57632712+kravetsone@users.noreply.github.com> Date: Sat, 24 Feb 2024 17:55:44 +0300 Subject: [PATCH] feat: add bot.start method --- package.json | 2 +- src/bot.ts | 31 +++++++++++++++++++++++++++---- src/updates.ts | 11 ++++++----- 3 files changed, 34 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index acf7aff..6f8d519 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "license": "ISC", "devDependencies": { "@biomejs/biome": "1.5.3", - "@gramio/types": "^7.1.3", + "@gramio/types": "^7.1.4", "@types/node": "^20.11.20", "typescript": "^5.3.3" }, diff --git a/src/bot.ts b/src/bot.ts index dbca536..0fcffcd 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -316,13 +316,36 @@ export class Bot< >; } - async start({ webhook }: { webhook?: APIMethodParams<"setWebhook"> }) { + async start({ + webhook, + dropPendingUpdates, + allowedUpdates, + }: { + webhook?: Omit< + APIMethodParams<"setWebhook">, + "drop_pending_updates" | "allowed_updates" + >; + dropPendingUpdates?: boolean; + allowedUpdates?: NonNullable< + APIMethodParams<"getUpdates"> + >["allowed_updates"]; + } = {}) { if (!webhook) { - this.api.deleteWebhook(); + await this.api.deleteWebhook({ + drop_pending_updates: dropPendingUpdates, + }); - return this.updates.startPolling(); + return this.updates.startPolling({ + allowed_updates: allowedUpdates, + }); } - return this.api.setWebhook(webhook); + if (this.updates.isStarted) this.updates.stopPolling(); + + return this.api.setWebhook({ + ...webhook, + drop_pending_updates: dropPendingUpdates, + allowed_updates: allowedUpdates, + }); } } diff --git a/src/updates.ts b/src/updates.ts index 9e4198c..b0531b7 100644 --- a/src/updates.ts +++ b/src/updates.ts @@ -4,14 +4,14 @@ import { UpdateName, contextsMappings, } from "@gramio/contexts"; -import type { TelegramUpdate } from "@gramio/types"; +import type { APIMethodParams, TelegramUpdate } from "@gramio/types"; import { CaughtMiddlewareHandler, Composer, noopNext } from "middleware-io"; import type { Bot } from "./bot"; import { Handler } from "./types"; export class Updates { private readonly bot: Bot; - private isStarted = false; + isStarted = false; private offset = 0; private composer = Composer.builder< Context & { @@ -88,20 +88,21 @@ export class Updates { } } - async startPolling() { + async startPolling(params: APIMethodParams<"getUpdates"> = {}) { if (this.isStarted) throw new Error("[UPDATES] Polling already started!"); this.isStarted = true; - this.startFetchLoop(); + this.startFetchLoop(params); return; } - async startFetchLoop() { + async startFetchLoop(params: APIMethodParams<"getUpdates"> = {}) { while (this.isStarted) { const updates = await this.bot.api.getUpdates({ offset: this.offset, + ...params, }); for await (const update of updates) {