Skip to content

Commit d278ff7

Browse files
committed
chore: add more info about start and stop
1 parent a164833 commit d278ff7

File tree

3 files changed

+157
-3
lines changed

3 files changed

+157
-3
lines changed

docs/ru/updates/overview.md

Lines changed: 80 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,85 @@ head:
1111
content: "телеграм бот, фреймворк, как создать бота, Telegram, Telegram Bot API, GramIO, TypeScript, JavaScript, Node.JS, Nodejs, Deno, Bun, обработка обновлений, context объект, middleware, события бота, Update типы, обработчики событий, next функция, цепочка middleware, message события, callback_query события, фильтрация обновлений, маршрутизация событий, edited_message, channel_post, inline_query, polling, webhook, типы обновлений, регистрация обработчиков"
1212
---
1313

14-
# Контекст
14+
# Обработка обновлений
15+
16+
## Start
17+
18+
Метод `start` запускает процесс получения обновлений от Telegram для вашего бота. В зависимости от переданных параметров, бот может использовать long-polling или webhook для получения событий. Этот метод инициализирует бота, подгружает [lazy плагины](/docs/ru/plugins/lazy-load) и вызывает хук [`onStart`](/docs/ru/plugins/hooks#onstart).
19+
20+
**Сигнатура:**
21+
22+
```ts
23+
start(options?): Promise<BotInfo>
24+
```
25+
26+
**Параметры:**
27+
28+
- `options` — объект с настройками запуска:
29+
- `webhook` — параметры для запуска через webhook (`true`, строка-URL или объект с параметрами).
30+
- `longPolling` — параметры для long-polling (например, таймауты).
31+
- `dropPendingUpdates` — сбрасывать ли неотправленные обновления при запуске.
32+
- `allowedUpdates` — список типов обновлений, которые бот будет получать.
33+
- `deleteWebhook` — как поступать с существующим webhook при запуске long-polling.
34+
35+
> [!IMPORTANT]
36+
>
37+
> **Особенности параметров:**
38+
>
39+
> - Если указать `webhook: true`, GramIO не будет пытаться установить webhook самостоятельно — предполагается, что вы уже настроили его. В этом случае бот просто начнёт принимать обновления через уже существующий webhook.
40+
>
41+
> - Параметр `deleteWebhook` управляет тем, что делать с существующим webhook при запуске long-polling:
42+
> - Если `deleteWebhook: true`, бот всегда удаляет webhook перед запуском long-polling.
43+
> - Если `deleteWebhook: "on-conflict-with-polling"`, webhook будет удалён только если он мешает запуску long-polling (когда Telegram отвечает на запрос `getUpdates` с ошибкой конфликта).
44+
> - Если не указано, используется поведение по умолчанию (`on-conflict-with-polling`).
45+
46+
```ts
47+
import { Bot } from "gramio";
48+
49+
const bot = new Bot(process.env.BOT_TOKEN)
50+
.command("start", (ctx) => ctx.send("Привет!"))
51+
.onStart(console.log);
52+
53+
await bot.start({
54+
longPolling: { timeout: 10 },
55+
dropPendingUpdates: true,
56+
});
57+
```
58+
59+
**Описание работы:**
60+
61+
- Если не указан webhook, запускается long-polling.
62+
- Если указан webhook, настраивается webhook и бот начинает принимать обновления через HTTP.
63+
- Вызывает хук [`onStart`](/docs/ru/plugins/hooks#onstart).
64+
- Можно сбросить старые обновления при запуске.
65+
66+
## Stop
67+
68+
Метод `stop` завершает приём обновлений и корректно останавливает все внутренние процессы бота. Вызываются хуки завершения (`onStop`), очищается очередь обновлений.
69+
70+
**Сигнатура:**
71+
72+
```ts
73+
stop(timeout?): Promise<void>
74+
```
75+
76+
**Параметры:**
77+
78+
- `timeout` — время ожидания завершения обработки очереди обновлений (по умолчанию 3000 мс).
79+
80+
**Пример использования:**
81+
82+
```ts
83+
await bot.stop();
84+
```
85+
86+
**Описание работы:**
87+
88+
- Останавливает long-polling или webhook (если был запущен).
89+
- Дожидается завершения обработки всех текущих обновлений.
90+
- Вызывает хук [`onStop`](/docs/ru/plugins/hooks#onstop).
91+
92+
## Контекст
1593
1694
## Прослушивание всех событий
1795
@@ -143,4 +221,4 @@ const bot = new Bot(process.env.BOT_TOKEN as string)
143221
context.k;
144222
// ^|
145223
});
146-
```
224+
```

docs/tma/init-data.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,6 @@ const app = new Elysia()
189189
.use(authElysia)
190190
.get("/user", ({ user }) => {
191191
user;
192-
// ^?
192+
// ^?
193193
});
194194
```

docs/updates/overview.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,79 @@
1+
# Update handling
2+
3+
## Start
4+
5+
The `start` method launches the process of receiving updates from Telegram for your bot. Depending on the parameters provided, the bot can use long-polling or webhook to receive events. This method initializes the bot, loads [lazy plugins](/plugins/lazy-load), and calls the [`onStart`](/plugins/hooks#onstart) hook.
6+
7+
**Signature:**
8+
9+
```ts
10+
start(options?): Promise<BotInfo>
11+
```
12+
13+
**Parameters:**
14+
15+
- `options` — an object with launch settings:
16+
- `webhook` — parameters for starting via webhook (`true`, a URL string, or an object with parameters).
17+
- `longPolling` — parameters for long-polling (for example, timeouts).
18+
- `dropPendingUpdates` — whether to drop pending updates on start.
19+
- `allowedUpdates` — a list of update types the bot will receive.
20+
- `deleteWebhook` — how to handle an existing webhook when starting long-polling.
21+
22+
> [!IMPORTANT] > **Parameter details:**
23+
>
24+
> - If you set `webhook: true`, GramIO will not attempt to set the webhook itself — it assumes you have already configured it. In this case, the bot will simply start receiving updates via the existing webhook.
25+
>
26+
> - The `deleteWebhook` parameter controls what to do with an existing webhook when starting long-polling:
27+
> - If `deleteWebhook: true`, the bot will always delete the webhook before starting long-polling.
28+
> - If `deleteWebhook: "on-conflict-with-polling"`, the webhook will only be deleted if it interferes with starting long-polling (when Telegram responds to `getUpdates` with a conflict error).
29+
> - If not specified, the default behavior (`on-conflict-with-polling`) is used.
30+
31+
```ts
32+
import { Bot } from "gramio";
33+
34+
const bot = new Bot(process.env.BOT_TOKEN)
35+
.command("start", (ctx) => ctx.send("Hi!"))
36+
.onStart(console.log);
37+
38+
await bot.start({
39+
longPolling: { timeout: 10 },
40+
dropPendingUpdates: true,
41+
});
42+
```
43+
44+
**How it works:**
45+
46+
- If webhook is not specified, long-polling is started.
47+
- If webhook is specified, the webhook is set up and the bot starts receiving updates via HTTP.
48+
- Calls the [`onStart`](/plugins/hooks#onstart) hook.
49+
- You can drop old updates on start.
50+
51+
## Stop
52+
53+
The `stop` method stops receiving updates and gracefully shuts down all internal bot processes. The [`onStop`](/plugins/hooks#onstop) hook is called, and the update queue is cleared.
54+
55+
**Signature:**
56+
57+
```ts
58+
stop(timeout?): Promise<void>
59+
```
60+
61+
**Parameters:**
62+
63+
- `timeout` — the time to wait for the update queue to finish processing (default is 3000 ms).
64+
65+
**Example usage:**
66+
67+
```ts
68+
await bot.stop();
69+
```
70+
71+
**How it works:**
72+
73+
- Stops long-polling or webhook (if it was running).
74+
- Waits for all current updates to finish processing.
75+
- Calls the [`onStop`](/plugins/hooks#onstop) hook.
76+
177
# Context
278
379
## Listen to all events

0 commit comments

Comments
 (0)