@tgify/tgify 0.1.0 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +358 -356
  3. package/lib/cli.mjs +9 -9
  4. package/package.json +1 -1
  5. package/src/button.ts +182 -182
  6. package/src/composer.ts +1008 -1008
  7. package/src/context.ts +1661 -1661
  8. package/src/core/helpers/args.ts +63 -63
  9. package/src/core/helpers/check.ts +71 -71
  10. package/src/core/helpers/compact.ts +18 -18
  11. package/src/core/helpers/deunionize.ts +26 -26
  12. package/src/core/helpers/formatting.ts +119 -119
  13. package/src/core/helpers/util.ts +96 -96
  14. package/src/core/network/client.ts +396 -396
  15. package/src/core/network/error.ts +29 -29
  16. package/src/core/network/multipart-stream.ts +45 -45
  17. package/src/core/network/polling.ts +94 -94
  18. package/src/core/network/webhook.ts +58 -58
  19. package/src/core/types/typegram.ts +54 -54
  20. package/src/filters.ts +109 -109
  21. package/src/format.ts +110 -110
  22. package/src/future.ts +213 -213
  23. package/src/index.ts +17 -17
  24. package/src/input.ts +59 -59
  25. package/src/markup.ts +142 -142
  26. package/src/middleware.ts +24 -24
  27. package/src/reactions.ts +118 -118
  28. package/src/router.ts +55 -55
  29. package/src/scenes/base.ts +52 -52
  30. package/src/scenes/context.ts +136 -136
  31. package/src/scenes/index.ts +21 -21
  32. package/src/scenes/stage.ts +71 -71
  33. package/src/scenes/wizard/context.ts +58 -58
  34. package/src/scenes/wizard/index.ts +63 -63
  35. package/src/scenes.ts +1 -1
  36. package/src/session.ts +204 -204
  37. package/src/telegraf.ts +354 -354
  38. package/src/telegram-types.ts +219 -219
  39. package/src/telegram.ts +1635 -1635
  40. package/src/types.ts +2 -2
  41. package/src/utils.ts +1 -1
  42. package/typings/telegraf.d.ts.map +1 -1
package/README.md CHANGED
@@ -1,356 +1,358 @@
1
- <header>
2
-
3
- <div align="center">
4
- <h1 align="center">tgify</h1>
5
-
6
- <p>Modern Telegram Bot API framework for Node.js</p>
7
-
8
- <a href="https://core.telegram.org/bots/api">
9
- <img src="https://img.shields.io/badge/Bot%20API-v7.1-f36caf.svg?style=flat-square" alt="Bot API Version" />
10
- </a>
11
- <a href="https://packagephobia.com/result?p=tgify,node-telegram-bot-api">
12
- <img src="https://flat.badgen.net/packagephobia/install/tgify" alt="install size" />
13
- </a>
14
- <a href="https://github.com/IATNAOD/tgify">
15
- <img src="https://img.shields.io/github/languages/top/IATNAOD/tgify?style=flat-square&logo=github" alt="GitHub top language" />
16
- </a>
17
- </div>
18
-
19
- </header>
20
-
21
- ## Introduction
22
-
23
- Bots are special [Telegram](https://telegram.org) accounts designed to handle messages automatically.
24
- Users can interact with bots by sending them command messages in private or group chats.
25
- These accounts serve as an interface for code running somewhere on your server.
26
-
27
- Tgify is a library that makes it simple for you to develop your own Telegram bots using JavaScript or [TypeScript](https://www.typescriptlang.org/).
28
-
29
- ### Features
30
-
31
- - Full [Telegram Bot API 7.1](https://core.telegram.org/bots/api) support
32
- - [Excellent TypeScript typings](https://github.com/IATNAOD/tgify/releases/tag/v4.0.0)
33
- - [Lightweight](https://packagephobia.com/result?p=tgify,node-telegram-bot-api)
34
- - [AWS **λ**](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html)
35
- / [Firebase](https://firebase.google.com/products/functions/)
36
- / [Glitch](https://glitch.com/edit/#!/dashing-light)
37
- / [Fly.io](https://fly.io/docs/languages-and-frameworks/node)
38
- / Whatever ready
39
- - `http/https/fastify/Connect.js/express.js` compatible webhooks
40
- - Extensible
41
-
42
- ### Example
43
-
44
- ```js
45
- const { Telegraf } = require('telegraf')
46
- const { message } = require('telegraf/filters')
47
-
48
- const bot = new Telegraf(process.env.BOT_TOKEN)
49
- bot.start((ctx) => ctx.reply('Welcome'))
50
- bot.help((ctx) => ctx.reply('Send me a sticker'))
51
- bot.on(message('sticker'), (ctx) => ctx.reply('👍'))
52
- bot.hears('hi', (ctx) => ctx.reply('Hey there'))
53
- bot.launch()
54
-
55
- // Enable graceful stop
56
- process.once('SIGINT', () => bot.stop('SIGINT'))
57
- process.once('SIGTERM', () => bot.stop('SIGTERM'))
58
- ```
59
-
60
- ```js
61
- const { Telegraf } = require('telegraf')
62
-
63
- const bot = new Telegraf(process.env.BOT_TOKEN)
64
- bot.command('oldschool', (ctx) => ctx.reply('Hello'))
65
- bot.command('hipster', Telegraf.reply('λ'))
66
- bot.launch()
67
-
68
- // Enable graceful stop
69
- process.once('SIGINT', () => bot.stop('SIGINT'))
70
- process.once('SIGTERM', () => bot.stop('SIGTERM'))
71
- ```
72
-
73
- For additional bot examples see the new [`docs repo`](https://github.com/feathers-studio/telegraf-docs/).
74
-
75
- ### Resources
76
-
77
- - [Getting started](#getting-started)
78
- - [GitHub Discussions](https://github.com/IATNAOD/tgify/discussions)
79
- - [Dependent repositories](https://libraries.io/npm/tgify/dependent_repositories)
80
-
81
- ## Getting started
82
-
83
- ### Telegram token
84
-
85
- To use the [Telegram Bot API](https://core.telegram.org/bots/api),
86
- you first have to [get a bot account](https://core.telegram.org/bots)
87
- by [chatting with BotFather](https://core.telegram.org/bots#6-botfather).
88
-
89
- BotFather will give you a _token_, something like `123456789:AbCdefGhIJKlmNoPQRsTUVwxyZ`.
90
-
91
- ### Installation
92
-
93
- ```shellscript
94
- $ npm install tgify
95
- ```
96
-
97
- or
98
-
99
- ```shellscript
100
- $ yarn add tgify
101
- ```
102
-
103
- or
104
-
105
- ```shellscript
106
- $ pnpm add tgify
107
- ```
108
-
109
- ### `Telegraf` class
110
-
111
- [`Telegraf`] instance represents your bot. It's responsible for obtaining updates and passing them to your handlers.
112
-
113
- Start by [listening to commands](https://telegraf.js.org/classes/Telegraf-1.html#command) and [launching](https://telegraf.js.org/classes/Telegraf-1.html#launch) your bot.
114
-
115
- ### `Context` class
116
-
117
- `ctx` you can see in every example is a [`Context`] instance.
118
- [`Telegraf`] creates one for each incoming update and passes it to your middleware.
119
- It contains the `update`, `botInfo`, and `telegram` for making arbitrary Bot API requests,
120
- as well as shorthand methods and getters.
121
-
122
- This is probably the class you'll be using the most.
123
-
124
- #### Shorthand methods
125
-
126
- ```js
127
- import { Telegraf } from 'telegraf'
128
- import { message } from 'telegraf/filters'
129
-
130
- const bot = new Telegraf(process.env.BOT_TOKEN)
131
-
132
- bot.command('quit', async (ctx) => {
133
- // Explicit usage
134
- await ctx.telegram.leaveChat(ctx.message.chat.id)
135
-
136
- // Using context shortcut
137
- await ctx.leaveChat()
138
- })
139
-
140
- bot.on(message('text'), async (ctx) => {
141
- // Explicit usage
142
- await ctx.telegram.sendMessage(ctx.message.chat.id, `Hello ${ctx.state.role}`)
143
-
144
- // Using context shortcut
145
- await ctx.reply(`Hello ${ctx.state.role}`)
146
- })
147
-
148
- bot.on('callback_query', async (ctx) => {
149
- // Explicit usage
150
- await ctx.telegram.answerCbQuery(ctx.callbackQuery.id)
151
-
152
- // Using context shortcut
153
- await ctx.answerCbQuery()
154
- })
155
-
156
- bot.on('inline_query', async (ctx) => {
157
- const result = []
158
- // Explicit usage
159
- await ctx.telegram.answerInlineQuery(ctx.inlineQuery.id, result)
160
-
161
- // Using context shortcut
162
- await ctx.answerInlineQuery(result)
163
- })
164
-
165
- bot.launch()
166
-
167
- // Enable graceful stop
168
- process.once('SIGINT', () => bot.stop('SIGINT'))
169
- process.once('SIGTERM', () => bot.stop('SIGTERM'))
170
- ```
171
-
172
- ## Production
173
-
174
- ### Webhooks
175
-
176
- ```TS
177
- import { Telegraf } from "telegraf";
178
- import { message } from 'telegraf/filters';
179
-
180
- const bot = new Telegraf(token);
181
-
182
- bot.on(message("text"), ctx => ctx.reply("Hello"));
183
-
184
- // Start webhook via launch method (preferred)
185
- bot.launch({
186
- webhook: {
187
- // Public domain for webhook; e.g.: example.com
188
- domain: webhookDomain,
189
-
190
- // Port to listen on; e.g.: 8080
191
- port: port,
192
-
193
- // Optional path to listen for.
194
- // `bot.secretPathComponent()` will be used by default
195
- path: webhookPath,
196
-
197
- // Optional secret to be sent back in a header for security.
198
- // e.g.: `crypto.randomBytes(64).toString("hex")`
199
- secretToken: randomAlphaNumericString,
200
- },
201
- });
202
- ```
203
-
204
- Use `createWebhook()` if you want to attach Telegraf to an existing http server.
205
-
206
- <!-- global bot, tlsOptions -->
207
-
208
- ```TS
209
- import { createServer } from "http";
210
-
211
- createServer(await bot.createWebhook({ domain: "example.com" })).listen(3000);
212
- ```
213
-
214
- ```TS
215
- import { createServer } from "https";
216
-
217
- createServer(tlsOptions, await bot.createWebhook({ domain: "example.com" })).listen(8443);
218
- ```
219
-
220
- - [AWS Lambda example integration](https://github.com/feathers-studio/telegraf-docs/tree/master/examples/functions/aws-lambda)
221
- - [Google Cloud Functions example integration](https://github.com/feathers-studio/telegraf-docs/blob/master/examples/functions/google-cloud-function.ts)
222
- - [`express` example integration](https://github.com/feathers-studio/telegraf-docs/blob/master/examples/webhook/express.ts)
223
- - [`fastify` example integration](https://github.com/feathers-studio/telegraf-docs/blob/master/examples/webhook/fastify.ts)
224
- - [`koa` example integration](https://github.com/feathers-studio/telegraf-docs/blob/master/examples/webhook/koa.ts)
225
- - [Cloudflare Workers integration module](https://github.com/Tsuk1ko/cfworker-middware-telegraf)
226
- - Use [`bot.handleUpdate`](https://telegraf.js.org/classes/Telegraf-1.html#handleupdate) to write new integrations
227
-
228
- ### Error handling
229
-
230
- If middleware throws an error or times out, Telegraf calls `bot.handleError`. If it rethrows, update source closes, and then the error is printed to console and process terminates. If it does not rethrow, the error is swallowed.
231
-
232
- Default `bot.handleError` always rethrows. You can overwrite it using `bot.catch` if you need to.
233
-
234
- ⚠️ Swallowing unknown errors might leave the process in invalid state!
235
-
236
- ℹ️ In production, `systemd` or [`pm2`](https://www.npmjs.com/package/pm2) can restart your bot if it exits for any reason.
237
-
238
- ## Advanced topics
239
-
240
- ### Working with files
241
-
242
- Supported file sources:
243
-
244
- - `Existing file_id`
245
- - `File path`
246
- - `Url`
247
- - `Buffer`
248
- - `ReadStream`
249
-
250
- Also, you can provide an optional name of a file as `filename` when you send the file.
251
-
252
- <!-- global bot, fs -->
253
-
254
- ```js
255
- bot.on('message', async (ctx) => {
256
- // resend existing file by file_id
257
- await ctx.replyWithSticker('123123jkbhj6b')
258
-
259
- // send file
260
- await ctx.replyWithVideo(Input.fromLocalFile('/path/to/video.mp4'))
261
-
262
- // send stream
263
- await ctx.replyWithVideo(
264
- Input.fromReadableStream(fs.createReadStream('/path/to/video.mp4'))
265
- )
266
-
267
- // send buffer
268
- await ctx.replyWithVoice(Input.fromBuffer(Buffer.alloc()))
269
-
270
- // send url via Telegram server
271
- await ctx.replyWithPhoto(Input.fromURL('https://picsum.photos/200/300/'))
272
-
273
- // pipe url content
274
- await ctx.replyWithPhoto(
275
- Input.fromURLStream('https://picsum.photos/200/300/?random', 'kitten.jpg')
276
- )
277
- })
278
- ```
279
-
280
- ### Middleware
281
-
282
- In addition to `ctx: Context`, each middleware receives `next: () => Promise<void>`.
283
-
284
- As in Koa and some other middleware-based libraries,
285
- `await next()` will call next middleware and wait for it to finish:
286
-
287
- ```TS
288
- import { Telegraf } from 'telegraf';
289
- import { message } from 'telegraf/filters';
290
-
291
- const bot = new Telegraf(process.env.BOT_TOKEN);
292
-
293
- bot.use(async (ctx, next) => {
294
- console.time(`Processing update ${ctx.update.update_id}`);
295
- await next() // runs next middleware
296
- // runs after next middleware finishes
297
- console.timeEnd(`Processing update ${ctx.update.update_id}`);
298
- })
299
-
300
- bot.on(message('text'), (ctx) => ctx.reply('Hello World'));
301
- bot.launch();
302
-
303
- // Enable graceful stop
304
- process.once('SIGINT', () => bot.stop('SIGINT'));
305
- process.once('SIGTERM', () => bot.stop('SIGTERM'));
306
- ```
307
-
308
- With this simple ability, you can:
309
-
310
- - extract information from updates and then `await next()` to avoid disrupting other middleware,
311
- - like [`Composer`] and [`Router`], `await next()` for updates you don't wish to handle,
312
- - like [`session`] and [`Scenes`], [extend the context](#extending-context) by mutating `ctx` before `await next()`,
313
- - [intercept API calls](https://github.com/telegraf/telegraf/discussions/1267#discussioncomment-254525),
314
- - reuse [other people's code](https://www.npmjs.com/search?q=telegraf-),
315
- - do whatever **you** come up with!
316
-
317
- [`Telegraf`]: https://telegraf.js.org/classes/Telegraf-1.html
318
- [`Composer`]: https://telegraf.js.org/classes/Composer.html
319
- [`Context`]: https://telegraf.js.org/classes/Context.html
320
- [`Router`]: https://telegraf.js.org/classes/Router.html
321
- [`session`]: https://telegraf.js.org/modules.html#session
322
- [`Scenes`]: https://telegraf.js.org/modules/Scenes.html
323
-
324
- ### Usage with TypeScript
325
-
326
- Tgify is written in TypeScript and therefore ships with declaration files for the entire library.
327
- Moreover, it includes types for the complete Telegram API via the [`typegram`](https://github.com/KnorpelSenf/typegram) package.
328
- While most types of Tgify's API surface are self-explanatory, there's some notable things to keep in mind.
329
-
330
- #### Extending `Context`
331
-
332
- The exact shape of `ctx` can vary based on the installed middleware.
333
- Some custom middleware might register properties on the context object that Telegraf is not aware of.
334
- Consequently, you can change the type of `ctx` to fit your needs in order for you to have proper TypeScript types for your data.
335
- This is done through Generics:
336
-
337
- ```ts
338
- import { Context, Telegraf } from 'telegraf'
339
-
340
- // Define your own context type
341
- interface MyContext extends Context {
342
- myProp?: string
343
- myOtherProp?: number
344
- }
345
-
346
- // Create your bot and tell it about your context type
347
- const bot = new Telegraf<MyContext>('SECRET TOKEN')
348
-
349
- // Register middleware and launch your bot as usual
350
- bot.use((ctx, next) => {
351
- // Yay, `myProp` is now available here as `string | undefined`!
352
- ctx.myProp = ctx.chat?.first_name?.toUpperCase()
353
- return next()
354
- })
355
- // ...
356
- ```
1
+ <header>
2
+
3
+ <div align="center">
4
+ <h1 align="center">tgify</h1>
5
+
6
+ <p>Modern Telegram Bot API framework for Node.js</p>
7
+
8
+ <i>This is a fork of the Telegraf library and its continuation as I envision it. I will do my best to maintain full compatibility so that anyone who lacks certain functionality can migrate to this solution quickly and without friction.</i>
9
+
10
+ <a href="https://core.telegram.org/bots/api">
11
+ <img src="https://img.shields.io/badge/Bot%20API-v7.1-f36caf.svg?style=flat-square" alt="Bot API Version" />
12
+ </a>
13
+ <a href="https://packagephobia.com/result?p=@tgify/tgify,node-telegram-bot-api">
14
+ <img src="https://flat.badgen.net/packagephobia/install/@tgify/tgify" alt="install size" />
15
+ </a>
16
+ <a href="https://github.com/IATNAOD/tgify">
17
+ <img src="https://img.shields.io/github/languages/top/IATNAOD/tgify?style=flat-square&logo=github" alt="GitHub top language" />
18
+ </a>
19
+ </div>
20
+
21
+ </header>
22
+
23
+ ## Introduction
24
+
25
+ Bots are special [Telegram](https://telegram.org) accounts designed to handle messages automatically.
26
+ Users can interact with bots by sending them command messages in private or group chats.
27
+ These accounts serve as an interface for code running somewhere on your server.
28
+
29
+ Tgify is a library that makes it simple for you to develop your own Telegram bots using JavaScript or [TypeScript](https://www.typescriptlang.org/).
30
+
31
+ ### Features
32
+
33
+ - Full [Telegram Bot API 7.1](https://core.telegram.org/bots/api) support
34
+ - [Excellent TypeScript typings](https://github.com/IATNAOD/tgify/releases/tag/v4.0.0)
35
+ - [Lightweight](https://packagephobia.com/result?p=@tgify/tgify,node-telegram-bot-api)
36
+ - [AWS **λ**](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html)
37
+ / [Firebase](https://firebase.google.com/products/functions/)
38
+ / [Glitch](https://glitch.com/edit/#!/dashing-light)
39
+ / [Fly.io](https://fly.io/docs/languages-and-frameworks/node)
40
+ / Whatever ready
41
+ - `http/https/fastify/Connect.js/express.js` compatible webhooks
42
+ - Extensible
43
+
44
+ ### Example
45
+
46
+ ```js
47
+ const { Telegraf } = require('@tgify/tgify')
48
+ const { message } = require('@tgify/tgify/filters')
49
+
50
+ const bot = new Telegraf(process.env.BOT_TOKEN)
51
+ bot.start((ctx) => ctx.reply('Welcome'))
52
+ bot.help((ctx) => ctx.reply('Send me a sticker'))
53
+ bot.on(message('sticker'), (ctx) => ctx.reply('👍'))
54
+ bot.hears('hi', (ctx) => ctx.reply('Hey there'))
55
+ bot.launch()
56
+
57
+ // Enable graceful stop
58
+ process.once('SIGINT', () => bot.stop('SIGINT'))
59
+ process.once('SIGTERM', () => bot.stop('SIGTERM'))
60
+ ```
61
+
62
+ ```js
63
+ const { Telegraf } = require('@tgify/tgify')
64
+
65
+ const bot = new Telegraf(process.env.BOT_TOKEN)
66
+ bot.command('oldschool', (ctx) => ctx.reply('Hello'))
67
+ bot.command('hipster', Telegraf.reply('λ'))
68
+ bot.launch()
69
+
70
+ // Enable graceful stop
71
+ process.once('SIGINT', () => bot.stop('SIGINT'))
72
+ process.once('SIGTERM', () => bot.stop('SIGTERM'))
73
+ ```
74
+
75
+ For additional bot examples see the new [`docs repo`](https://github.com/feathers-studio/telegraf-docs/).
76
+
77
+ ### Resources
78
+
79
+ - [Getting started](#getting-started)
80
+ - [GitHub Discussions](https://github.com/IATNAOD/tgify/discussions)
81
+ - [Dependent repositories](https://libraries.io/npm/@tgify/tgify/dependent_repositories)
82
+
83
+ ## Getting started
84
+
85
+ ### Telegram token
86
+
87
+ To use the [Telegram Bot API](https://core.telegram.org/bots/api),
88
+ you first have to [get a bot account](https://core.telegram.org/bots)
89
+ by [chatting with BotFather](https://core.telegram.org/bots#6-botfather).
90
+
91
+ BotFather will give you a _token_, something like `123456789:AbCdefGhIJKlmNoPQRsTUVwxyZ`.
92
+
93
+ ### Installation
94
+
95
+ ```shellscript
96
+ $ npm install @tgify/tgify
97
+ ```
98
+
99
+ or
100
+
101
+ ```shellscript
102
+ $ yarn add @tgify/tgify
103
+ ```
104
+
105
+ or
106
+
107
+ ```shellscript
108
+ $ pnpm add @tgify/tgify
109
+ ```
110
+
111
+ ### `Telegraf` class
112
+
113
+ [`Telegraf`] instance represents your bot. It's responsible for obtaining updates and passing them to your handlers.
114
+
115
+ Start by [listening to commands](https://telegraf.js.org/classes/Telegraf-1.html#command) and [launching](https://telegraf.js.org/classes/Telegraf-1.html#launch) your bot.
116
+
117
+ ### `Context` class
118
+
119
+ `ctx` you can see in every example is a [`Context`] instance.
120
+ [`Telegraf`] creates one for each incoming update and passes it to your middleware.
121
+ It contains the `update`, `botInfo`, and `telegram` for making arbitrary Bot API requests,
122
+ as well as shorthand methods and getters.
123
+
124
+ This is probably the class you'll be using the most.
125
+
126
+ #### Shorthand methods
127
+
128
+ ```js
129
+ import { Telegraf } from '@tgify/tgify'
130
+ import { message } from '@tgify/tgify/filters'
131
+
132
+ const bot = new Telegraf(process.env.BOT_TOKEN)
133
+
134
+ bot.command('quit', async (ctx) => {
135
+ // Explicit usage
136
+ await ctx.telegram.leaveChat(ctx.message.chat.id)
137
+
138
+ // Using context shortcut
139
+ await ctx.leaveChat()
140
+ })
141
+
142
+ bot.on(message('text'), async (ctx) => {
143
+ // Explicit usage
144
+ await ctx.telegram.sendMessage(ctx.message.chat.id, `Hello ${ctx.state.role}`)
145
+
146
+ // Using context shortcut
147
+ await ctx.reply(`Hello ${ctx.state.role}`)
148
+ })
149
+
150
+ bot.on('callback_query', async (ctx) => {
151
+ // Explicit usage
152
+ await ctx.telegram.answerCbQuery(ctx.callbackQuery.id)
153
+
154
+ // Using context shortcut
155
+ await ctx.answerCbQuery()
156
+ })
157
+
158
+ bot.on('inline_query', async (ctx) => {
159
+ const result = []
160
+ // Explicit usage
161
+ await ctx.telegram.answerInlineQuery(ctx.inlineQuery.id, result)
162
+
163
+ // Using context shortcut
164
+ await ctx.answerInlineQuery(result)
165
+ })
166
+
167
+ bot.launch()
168
+
169
+ // Enable graceful stop
170
+ process.once('SIGINT', () => bot.stop('SIGINT'))
171
+ process.once('SIGTERM', () => bot.stop('SIGTERM'))
172
+ ```
173
+
174
+ ## Production
175
+
176
+ ### Webhooks
177
+
178
+ ```TS
179
+ import { Telegraf } from "@tgify/tgify";
180
+ import { message } from '@tgify/tgify/filters';
181
+
182
+ const bot = new Telegraf(token);
183
+
184
+ bot.on(message("text"), ctx => ctx.reply("Hello"));
185
+
186
+ // Start webhook via launch method (preferred)
187
+ bot.launch({
188
+ webhook: {
189
+ // Public domain for webhook; e.g.: example.com
190
+ domain: webhookDomain,
191
+
192
+ // Port to listen on; e.g.: 8080
193
+ port: port,
194
+
195
+ // Optional path to listen for.
196
+ // `bot.secretPathComponent()` will be used by default
197
+ path: webhookPath,
198
+
199
+ // Optional secret to be sent back in a header for security.
200
+ // e.g.: `crypto.randomBytes(64).toString("hex")`
201
+ secretToken: randomAlphaNumericString,
202
+ },
203
+ });
204
+ ```
205
+
206
+ Use `createWebhook()` if you want to attach Telegraf to an existing http server.
207
+
208
+ <!-- global bot, tlsOptions -->
209
+
210
+ ```TS
211
+ import { createServer } from "http";
212
+
213
+ createServer(await bot.createWebhook({ domain: "example.com" })).listen(3000);
214
+ ```
215
+
216
+ ```TS
217
+ import { createServer } from "https";
218
+
219
+ createServer(tlsOptions, await bot.createWebhook({ domain: "example.com" })).listen(8443);
220
+ ```
221
+
222
+ - [AWS Lambda example integration](https://github.com/feathers-studio/telegraf-docs/tree/master/examples/functions/aws-lambda)
223
+ - [Google Cloud Functions example integration](https://github.com/feathers-studio/telegraf-docs/blob/master/examples/functions/google-cloud-function.ts)
224
+ - [`express` example integration](https://github.com/feathers-studio/telegraf-docs/blob/master/examples/webhook/express.ts)
225
+ - [`fastify` example integration](https://github.com/feathers-studio/telegraf-docs/blob/master/examples/webhook/fastify.ts)
226
+ - [`koa` example integration](https://github.com/feathers-studio/telegraf-docs/blob/master/examples/webhook/koa.ts)
227
+ - [Cloudflare Workers integration module](https://github.com/Tsuk1ko/cfworker-middware-telegraf)
228
+ - Use [`bot.handleUpdate`](https://telegraf.js.org/classes/Telegraf-1.html#handleupdate) to write new integrations
229
+
230
+ ### Error handling
231
+
232
+ If middleware throws an error or times out, Telegraf calls `bot.handleError`. If it rethrows, update source closes, and then the error is printed to console and process terminates. If it does not rethrow, the error is swallowed.
233
+
234
+ Default `bot.handleError` always rethrows. You can overwrite it using `bot.catch` if you need to.
235
+
236
+ ⚠️ Swallowing unknown errors might leave the process in invalid state!
237
+
238
+ ℹ️ In production, `systemd` or [`pm2`](https://www.npmjs.com/package/pm2) can restart your bot if it exits for any reason.
239
+
240
+ ## Advanced topics
241
+
242
+ ### Working with files
243
+
244
+ Supported file sources:
245
+
246
+ - `Existing file_id`
247
+ - `File path`
248
+ - `Url`
249
+ - `Buffer`
250
+ - `ReadStream`
251
+
252
+ Also, you can provide an optional name of a file as `filename` when you send the file.
253
+
254
+ <!-- global bot, fs -->
255
+
256
+ ```js
257
+ bot.on('message', async (ctx) => {
258
+ // resend existing file by file_id
259
+ await ctx.replyWithSticker('123123jkbhj6b')
260
+
261
+ // send file
262
+ await ctx.replyWithVideo(Input.fromLocalFile('/path/to/video.mp4'))
263
+
264
+ // send stream
265
+ await ctx.replyWithVideo(
266
+ Input.fromReadableStream(fs.createReadStream('/path/to/video.mp4'))
267
+ )
268
+
269
+ // send buffer
270
+ await ctx.replyWithVoice(Input.fromBuffer(Buffer.alloc()))
271
+
272
+ // send url via Telegram server
273
+ await ctx.replyWithPhoto(Input.fromURL('https://picsum.photos/200/300/'))
274
+
275
+ // pipe url content
276
+ await ctx.replyWithPhoto(
277
+ Input.fromURLStream('https://picsum.photos/200/300/?random', 'kitten.jpg')
278
+ )
279
+ })
280
+ ```
281
+
282
+ ### Middleware
283
+
284
+ In addition to `ctx: Context`, each middleware receives `next: () => Promise<void>`.
285
+
286
+ As in Koa and some other middleware-based libraries,
287
+ `await next()` will call next middleware and wait for it to finish:
288
+
289
+ ```TS
290
+ import { Telegraf } from '@tgify/tgify';
291
+ import { message } from '@tgify/tgify/filters';
292
+
293
+ const bot = new Telegraf(process.env.BOT_TOKEN);
294
+
295
+ bot.use(async (ctx, next) => {
296
+ console.time(`Processing update ${ctx.update.update_id}`);
297
+ await next() // runs next middleware
298
+ // runs after next middleware finishes
299
+ console.timeEnd(`Processing update ${ctx.update.update_id}`);
300
+ })
301
+
302
+ bot.on(message('text'), (ctx) => ctx.reply('Hello World'));
303
+ bot.launch();
304
+
305
+ // Enable graceful stop
306
+ process.once('SIGINT', () => bot.stop('SIGINT'));
307
+ process.once('SIGTERM', () => bot.stop('SIGTERM'));
308
+ ```
309
+
310
+ With this simple ability, you can:
311
+
312
+ - extract information from updates and then `await next()` to avoid disrupting other middleware,
313
+ - like [`Composer`] and [`Router`], `await next()` for updates you don't wish to handle,
314
+ - like [`session`] and [`Scenes`], [extend the context](#extending-context) by mutating `ctx` before `await next()`,
315
+ - [intercept API calls](https://github.com/telegraf/telegraf/discussions/1267#discussioncomment-254525),
316
+ - reuse [other people's code](https://www.npmjs.com/search?q=telegraf-),
317
+ - do whatever **you** come up with!
318
+
319
+ [`Telegraf`]: https://telegraf.js.org/classes/Telegraf-1.html
320
+ [`Composer`]: https://telegraf.js.org/classes/Composer.html
321
+ [`Context`]: https://telegraf.js.org/classes/Context.html
322
+ [`Router`]: https://telegraf.js.org/classes/Router.html
323
+ [`session`]: https://telegraf.js.org/modules.html#session
324
+ [`Scenes`]: https://telegraf.js.org/modules/Scenes.html
325
+
326
+ ### Usage with TypeScript
327
+
328
+ Tgify is written in TypeScript and therefore ships with declaration files for the entire library.
329
+ Moreover, it includes types for the complete Telegram API via the [`typegram`](https://github.com/KnorpelSenf/typegram) package.
330
+ While most types of Tgify's API surface are self-explanatory, there's some notable things to keep in mind.
331
+
332
+ #### Extending `Context`
333
+
334
+ The exact shape of `ctx` can vary based on the installed middleware.
335
+ Some custom middleware might register properties on the context object that Telegraf is not aware of.
336
+ Consequently, you can change the type of `ctx` to fit your needs in order for you to have proper TypeScript types for your data.
337
+ This is done through Generics:
338
+
339
+ ```ts
340
+ import { Context, Telegraf } from '@tgify/tgify'
341
+
342
+ // Define your own context type
343
+ interface MyContext extends Context {
344
+ myProp?: string
345
+ myOtherProp?: number
346
+ }
347
+
348
+ // Create your bot and tell it about your context type
349
+ const bot = new Telegraf<MyContext>('SECRET TOKEN')
350
+
351
+ // Register middleware and launch your bot as usual
352
+ bot.use((ctx, next) => {
353
+ // Yay, `myProp` is now available here as `string | undefined`!
354
+ ctx.myProp = ctx.chat?.first_name?.toUpperCase()
355
+ return next()
356
+ })
357
+ // ...
358
+ ```