@tgify/tgify 0.1.0 → 0.1.4
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.
- package/LICENSE +23 -23
- package/README.md +356 -356
- package/lib/cli.mjs +9 -9
- package/package.json +1 -1
- package/src/button.ts +182 -182
- package/src/composer.ts +1008 -1008
- package/src/context.ts +1661 -1661
- package/src/core/helpers/args.ts +63 -63
- package/src/core/helpers/check.ts +71 -71
- package/src/core/helpers/compact.ts +18 -18
- package/src/core/helpers/deunionize.ts +26 -26
- package/src/core/helpers/formatting.ts +119 -119
- package/src/core/helpers/util.ts +96 -96
- package/src/core/network/client.ts +396 -396
- package/src/core/network/error.ts +29 -29
- package/src/core/network/multipart-stream.ts +45 -45
- package/src/core/network/polling.ts +94 -94
- package/src/core/network/webhook.ts +58 -58
- package/src/core/types/typegram.ts +54 -54
- package/src/filters.ts +109 -109
- package/src/format.ts +110 -110
- package/src/future.ts +213 -213
- package/src/index.ts +17 -17
- package/src/input.ts +59 -59
- package/src/markup.ts +142 -142
- package/src/middleware.ts +24 -24
- package/src/reactions.ts +118 -118
- package/src/router.ts +55 -55
- package/src/scenes/base.ts +52 -52
- package/src/scenes/context.ts +136 -136
- package/src/scenes/index.ts +21 -21
- package/src/scenes/stage.ts +71 -71
- package/src/scenes/wizard/context.ts +58 -58
- package/src/scenes/wizard/index.ts +63 -63
- package/src/scenes.ts +1 -1
- package/src/session.ts +204 -204
- package/src/telegraf.ts +354 -354
- package/src/telegram-types.ts +219 -219
- package/src/telegram.ts +1635 -1635
- package/src/types.ts +2 -2
- package/src/utils.ts +1 -1
- package/typings/telegraf.d.ts.map +1 -1
package/README.md
CHANGED
|
@@ -1,356 +1,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
|
-
<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
|
+
<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
|
+
```
|