Skip to content

Commit

Permalink
feat: add bot.start method
Browse files Browse the repository at this point in the history
  • Loading branch information
kravetsone committed Feb 24, 2024
1 parent 3ca83b4 commit fcd110a
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
31 changes: 27 additions & 4 deletions src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
}
}
11 changes: 6 additions & 5 deletions src/updates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<any, any>;
private isStarted = false;
isStarted = false;
private offset = 0;
private composer = Composer.builder<
Context<Bot> & {
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit fcd110a

Please sign in to comment.