grammy-tools 1.36.2
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 +21 -0
- package/README.md +339 -0
- package/out/bot.d.ts +314 -0
- package/out/bot.js +669 -0
- package/out/composer.d.ts +764 -0
- package/out/composer.js +704 -0
- package/out/context.d.ts +1618 -0
- package/out/context.js +1976 -0
- package/out/convenience/constants.d.ts +98 -0
- package/out/convenience/constants.js +37 -0
- package/out/convenience/frameworks.d.ts +216 -0
- package/out/convenience/frameworks.js +370 -0
- package/out/convenience/inline_query.d.ts +401 -0
- package/out/convenience/inline_query.js +461 -0
- package/out/convenience/input_media.d.ts +72 -0
- package/out/convenience/input_media.js +82 -0
- package/out/convenience/keyboard.d.ts +763 -0
- package/out/convenience/keyboard.js +935 -0
- package/out/convenience/session.d.ts +345 -0
- package/out/convenience/session.js +455 -0
- package/out/convenience/webhook.d.ts +59 -0
- package/out/convenience/webhook.js +80 -0
- package/out/core/api.d.ts +1628 -0
- package/out/core/api.js +1907 -0
- package/out/core/client.d.ts +180 -0
- package/out/core/client.js +226 -0
- package/out/core/error.d.ts +53 -0
- package/out/core/error.js +87 -0
- package/out/core/payload.d.ts +39 -0
- package/out/core/payload.js +199 -0
- package/out/filter.d.ts +959 -0
- package/out/filter.js +378 -0
- package/out/mod.d.ts +14 -0
- package/out/mod.js +43 -0
- package/out/platform.node.d.ts +16 -0
- package/out/platform.node.js +43 -0
- package/out/shim.node.d.ts +2 -0
- package/out/shim.node.js +7 -0
- package/out/types.d.ts +1 -0
- package/out/types.js +17 -0
- package/out/types.node.d.ts +78 -0
- package/out/types.node.js +107 -0
- package/out/web.d.ts +1 -0
- package/out/web.mjs +5172 -0
- package/package.json +71 -0
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MemorySessionStorage = void 0;
|
|
4
|
+
exports.session = session;
|
|
5
|
+
exports.lazySession = lazySession;
|
|
6
|
+
exports.enhanceStorage = enhanceStorage;
|
|
7
|
+
const platform_node_js_1 = require("../platform.node.js");
|
|
8
|
+
const debug = (0, platform_node_js_1.debug)("grammy:session");
|
|
9
|
+
/**
|
|
10
|
+
* Session middleware provides a persistent data storage for your bot. You can
|
|
11
|
+
* use it to let your bot remember any data you want, for example the messages
|
|
12
|
+
* it sent or received in the past. This is done by attaching _session data_ to
|
|
13
|
+
* every chat. The stored data is then provided on the context object under
|
|
14
|
+
* `ctx.session`.
|
|
15
|
+
*
|
|
16
|
+
* > **What is a session?** Simply put, the session of a chat is a little
|
|
17
|
+
* > persistent storage that is attached to it. As an example, your bot can send
|
|
18
|
+
* > a message to a chat and store the identifier of that message in the
|
|
19
|
+
* > corresponding session. The next time your bot receives an update from that
|
|
20
|
+
* > chat, the session will still contain that ID.
|
|
21
|
+
* >
|
|
22
|
+
* > Session data can be stored in a database, in a file, or simply in memory.
|
|
23
|
+
* > grammY only supports memory sessions out of the box, but you can use
|
|
24
|
+
* > third-party session middleware to connect to other storage solutions. Note
|
|
25
|
+
* > that memory sessions will be lost when you stop your bot and the process
|
|
26
|
+
* > exits, so they are usually not useful in production.
|
|
27
|
+
*
|
|
28
|
+
* Whenever your bot receives an update, the first thing the session middleware
|
|
29
|
+
* will do is to load the correct session from your storage solution. This
|
|
30
|
+
* object is then provided on `ctx.session` while your other middleware is
|
|
31
|
+
* running. As soon as your bot is done handling the update, the middleware
|
|
32
|
+
* takes over again and writes back the session object to your storage. This
|
|
33
|
+
* allows you to modify the session object arbitrarily in your middleware, and
|
|
34
|
+
* to stop worrying about the database.
|
|
35
|
+
*
|
|
36
|
+
* ```ts
|
|
37
|
+
* bot.use(session())
|
|
38
|
+
*
|
|
39
|
+
* bot.on('message', ctx => {
|
|
40
|
+
* // The session object is persisted across updates!
|
|
41
|
+
* const session = ctx.session
|
|
42
|
+
* })
|
|
43
|
+
* ```
|
|
44
|
+
*
|
|
45
|
+
* It is recommended to make use of the `initial` option in the configuration
|
|
46
|
+
* object, which correctly initializes session objects for new chats.
|
|
47
|
+
*
|
|
48
|
+
* You can delete the session data by setting `ctx.session` to `null` or
|
|
49
|
+
* `undefined`.
|
|
50
|
+
*
|
|
51
|
+
* Check out the [documentation](https://grammy.dev/plugins/session) on the
|
|
52
|
+
* website to know more about how sessions work in grammY.
|
|
53
|
+
*
|
|
54
|
+
* @param options Optional configuration to pass to the session middleware
|
|
55
|
+
*/
|
|
56
|
+
function session(options = {}) {
|
|
57
|
+
return options.type === "multi"
|
|
58
|
+
? strictMultiSession(options)
|
|
59
|
+
: strictSingleSession(options);
|
|
60
|
+
}
|
|
61
|
+
function strictSingleSession(options) {
|
|
62
|
+
const { initial, storage, getSessionKey, custom } = fillDefaults(options);
|
|
63
|
+
return async (ctx, next) => {
|
|
64
|
+
const propSession = new PropertySession(storage, ctx, "session", initial);
|
|
65
|
+
const key = await getSessionKey(ctx);
|
|
66
|
+
await propSession.init(key, { custom, lazy: false });
|
|
67
|
+
await next(); // no catch: do not write back if middleware throws
|
|
68
|
+
await propSession.finish();
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
function strictMultiSession(options) {
|
|
72
|
+
const props = Object.keys(options).filter((k) => k !== "type");
|
|
73
|
+
const defaults = Object.fromEntries(props.map((prop) => [prop, fillDefaults(options[prop])]));
|
|
74
|
+
return async (ctx, next) => {
|
|
75
|
+
ctx.session = {};
|
|
76
|
+
const propSessions = await Promise.all(props.map(async (prop) => {
|
|
77
|
+
const { initial, storage, getSessionKey, custom } = defaults[prop];
|
|
78
|
+
const s = new PropertySession(
|
|
79
|
+
// @ts-expect-error cannot express that the storage works for a concrete prop
|
|
80
|
+
storage, ctx.session, prop, initial);
|
|
81
|
+
const key = await getSessionKey(ctx);
|
|
82
|
+
await s.init(key, { custom, lazy: false });
|
|
83
|
+
return s;
|
|
84
|
+
}));
|
|
85
|
+
await next(); // no catch: do not write back if middleware throws
|
|
86
|
+
if (ctx.session == null)
|
|
87
|
+
propSessions.forEach((s) => s.delete());
|
|
88
|
+
await Promise.all(propSessions.map((s) => s.finish()));
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* > This is an advanced function of grammY.
|
|
93
|
+
*
|
|
94
|
+
* Generally speaking, lazy sessions work just like normal sessions—just they
|
|
95
|
+
* are loaded on demand. Except for a few `async`s and `await`s here and there,
|
|
96
|
+
* their usage looks 100 % identical.
|
|
97
|
+
*
|
|
98
|
+
* Instead of directly querying the storage every time an update arrives, lazy
|
|
99
|
+
* sessions quickly do this _once you access_ `ctx.session`. This can
|
|
100
|
+
* significantly reduce the database traffic (especially when your bot is added
|
|
101
|
+
* to group chats), because it skips a read and a wrote operation for all
|
|
102
|
+
* updates that the bot does not react to.
|
|
103
|
+
*
|
|
104
|
+
* ```ts
|
|
105
|
+
* // The options are identical
|
|
106
|
+
* bot.use(lazySession({ storage: ... }))
|
|
107
|
+
*
|
|
108
|
+
* bot.on('message', async ctx => {
|
|
109
|
+
* // The session object is persisted across updates!
|
|
110
|
+
* const session = await ctx.session
|
|
111
|
+
* // ^
|
|
112
|
+
* // |
|
|
113
|
+
* // This plain property access (no function call) will trigger the database query!
|
|
114
|
+
* })
|
|
115
|
+
* ```
|
|
116
|
+
*
|
|
117
|
+
* Check out the
|
|
118
|
+
* [documentation](https://grammy.dev/plugins/session#lazy-sessions) on the
|
|
119
|
+
* website to know more about how lazy sessions work in grammY.
|
|
120
|
+
*
|
|
121
|
+
* @param options Optional configuration to pass to the session middleware
|
|
122
|
+
*/
|
|
123
|
+
function lazySession(options = {}) {
|
|
124
|
+
if (options.type !== undefined && options.type !== "single") {
|
|
125
|
+
throw new Error("Cannot use lazy multi sessions!");
|
|
126
|
+
}
|
|
127
|
+
const { initial, storage, getSessionKey, custom } = fillDefaults(options);
|
|
128
|
+
return async (ctx, next) => {
|
|
129
|
+
const propSession = new PropertySession(
|
|
130
|
+
// @ts-expect-error suppress promise nature of values
|
|
131
|
+
storage, ctx, "session", initial);
|
|
132
|
+
const key = await getSessionKey(ctx);
|
|
133
|
+
await propSession.init(key, { custom, lazy: true });
|
|
134
|
+
await next(); // no catch: do not write back if middleware throws
|
|
135
|
+
await propSession.finish();
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Internal class that manages a single property on the session. Can be used
|
|
140
|
+
* both in a strict and a lazy way. Works by using `Object.defineProperty` to
|
|
141
|
+
* install `O[P]`.
|
|
142
|
+
*/
|
|
143
|
+
// deno-lint-ignore ban-types
|
|
144
|
+
class PropertySession {
|
|
145
|
+
constructor(storage, obj, prop, initial) {
|
|
146
|
+
this.storage = storage;
|
|
147
|
+
this.obj = obj;
|
|
148
|
+
this.prop = prop;
|
|
149
|
+
this.initial = initial;
|
|
150
|
+
this.fetching = false;
|
|
151
|
+
this.read = false;
|
|
152
|
+
this.wrote = false;
|
|
153
|
+
}
|
|
154
|
+
/** Performs a read op and stores the result in `this.value` */
|
|
155
|
+
load() {
|
|
156
|
+
if (this.key === undefined) {
|
|
157
|
+
// No session key provided, cannot load
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (this.wrote) {
|
|
161
|
+
// Value was set, no need to load
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
// Perform read op if not cached
|
|
165
|
+
if (this.promise === undefined) {
|
|
166
|
+
this.fetching = true;
|
|
167
|
+
this.promise = Promise.resolve(this.storage.read(this.key))
|
|
168
|
+
.then((val) => {
|
|
169
|
+
var _a;
|
|
170
|
+
this.fetching = false;
|
|
171
|
+
// Check for write op in the meantime
|
|
172
|
+
if (this.wrote) {
|
|
173
|
+
// Discard read op
|
|
174
|
+
return this.value;
|
|
175
|
+
}
|
|
176
|
+
// Store received value in `this.value`
|
|
177
|
+
if (val !== undefined) {
|
|
178
|
+
this.value = val;
|
|
179
|
+
return val;
|
|
180
|
+
}
|
|
181
|
+
// No value, need to initialize
|
|
182
|
+
val = (_a = this.initial) === null || _a === void 0 ? void 0 : _a.call(this);
|
|
183
|
+
if (val !== undefined) {
|
|
184
|
+
// Wrote initial value
|
|
185
|
+
this.wrote = true;
|
|
186
|
+
this.value = val;
|
|
187
|
+
}
|
|
188
|
+
return val;
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
return this.promise;
|
|
192
|
+
}
|
|
193
|
+
async init(key, opts) {
|
|
194
|
+
this.key = key;
|
|
195
|
+
if (!opts.lazy)
|
|
196
|
+
await this.load();
|
|
197
|
+
Object.defineProperty(this.obj, this.prop, {
|
|
198
|
+
enumerable: true,
|
|
199
|
+
get: () => {
|
|
200
|
+
if (key === undefined) {
|
|
201
|
+
const msg = undef("access", opts);
|
|
202
|
+
throw new Error(msg);
|
|
203
|
+
}
|
|
204
|
+
this.read = true;
|
|
205
|
+
if (!opts.lazy || this.wrote)
|
|
206
|
+
return this.value;
|
|
207
|
+
this.load();
|
|
208
|
+
return this.fetching ? this.promise : this.value;
|
|
209
|
+
},
|
|
210
|
+
set: (v) => {
|
|
211
|
+
if (key === undefined) {
|
|
212
|
+
const msg = undef("assign", opts);
|
|
213
|
+
throw new Error(msg);
|
|
214
|
+
}
|
|
215
|
+
this.wrote = true;
|
|
216
|
+
this.fetching = false;
|
|
217
|
+
this.value = v;
|
|
218
|
+
},
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
delete() {
|
|
222
|
+
Object.assign(this.obj, { [this.prop]: undefined });
|
|
223
|
+
}
|
|
224
|
+
async finish() {
|
|
225
|
+
if (this.key !== undefined) {
|
|
226
|
+
if (this.read)
|
|
227
|
+
await this.load();
|
|
228
|
+
if (this.read || this.wrote) {
|
|
229
|
+
const value = await this.value;
|
|
230
|
+
if (value == null)
|
|
231
|
+
await this.storage.delete(this.key);
|
|
232
|
+
else
|
|
233
|
+
await this.storage.write(this.key, value);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
function fillDefaults(opts = {}) {
|
|
239
|
+
let { prefix = "", getSessionKey = defaultGetSessionKey, initial, storage, } = opts;
|
|
240
|
+
if (storage == null) {
|
|
241
|
+
debug("Storing session data in memory, all data will be lost when the bot restarts.");
|
|
242
|
+
storage = new MemorySessionStorage();
|
|
243
|
+
}
|
|
244
|
+
const custom = getSessionKey !== defaultGetSessionKey;
|
|
245
|
+
return {
|
|
246
|
+
initial,
|
|
247
|
+
storage,
|
|
248
|
+
getSessionKey: async (ctx) => {
|
|
249
|
+
const key = await getSessionKey(ctx);
|
|
250
|
+
return key === undefined ? undefined : prefix + key;
|
|
251
|
+
},
|
|
252
|
+
custom,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
/** Stores session data per chat by default */
|
|
256
|
+
function defaultGetSessionKey(ctx) {
|
|
257
|
+
var _a;
|
|
258
|
+
return (_a = ctx.chatId) === null || _a === void 0 ? void 0 : _a.toString();
|
|
259
|
+
}
|
|
260
|
+
/** Returns a useful error message for when the session key is undefined */
|
|
261
|
+
function undef(op, opts) {
|
|
262
|
+
const { lazy = false, custom } = opts;
|
|
263
|
+
const reason = custom
|
|
264
|
+
? "the custom `getSessionKey` function returned undefined for this update"
|
|
265
|
+
: "this update does not belong to a chat, so the session key is undefined";
|
|
266
|
+
return `Cannot ${op} ${lazy ? "lazy " : ""}session data because ${reason}!`;
|
|
267
|
+
}
|
|
268
|
+
function isEnhance(value) {
|
|
269
|
+
return value === undefined ||
|
|
270
|
+
typeof value === "object" && value !== null && "__d" in value;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* You can use this function to transform an existing storage adapter, and add
|
|
274
|
+
* more features to it. Currently, you can add session migrations and expiry
|
|
275
|
+
* dates.
|
|
276
|
+
*
|
|
277
|
+
* You can use this function like so:
|
|
278
|
+
* ```ts
|
|
279
|
+
* const storage = ... // define your storage adapter
|
|
280
|
+
* const enhanced = enhanceStorage({ storage, millisecondsToLive: 500 })
|
|
281
|
+
* bot.use(session({ storage: enhanced }))
|
|
282
|
+
* ```
|
|
283
|
+
*
|
|
284
|
+
* @param options Session enhancing options
|
|
285
|
+
* @returns The enhanced storage adapter
|
|
286
|
+
*/
|
|
287
|
+
function enhanceStorage(options) {
|
|
288
|
+
let { storage, millisecondsToLive, migrations } = options;
|
|
289
|
+
storage = compatStorage(storage);
|
|
290
|
+
if (millisecondsToLive !== undefined) {
|
|
291
|
+
storage = timeoutStorage(storage, millisecondsToLive);
|
|
292
|
+
}
|
|
293
|
+
if (migrations !== undefined) {
|
|
294
|
+
storage = migrationStorage(storage, migrations);
|
|
295
|
+
}
|
|
296
|
+
return wrapStorage(storage);
|
|
297
|
+
}
|
|
298
|
+
function compatStorage(storage) {
|
|
299
|
+
return {
|
|
300
|
+
read: async (k) => {
|
|
301
|
+
const v = await storage.read(k);
|
|
302
|
+
return isEnhance(v) ? v : { __d: v };
|
|
303
|
+
},
|
|
304
|
+
write: (k, v) => storage.write(k, v),
|
|
305
|
+
delete: (k) => storage.delete(k),
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
function timeoutStorage(storage, millisecondsToLive) {
|
|
309
|
+
const ttlStorage = {
|
|
310
|
+
read: async (k) => {
|
|
311
|
+
const value = await storage.read(k);
|
|
312
|
+
if (value === undefined)
|
|
313
|
+
return undefined;
|
|
314
|
+
if (value.e === undefined) {
|
|
315
|
+
await ttlStorage.write(k, value);
|
|
316
|
+
return value;
|
|
317
|
+
}
|
|
318
|
+
if (value.e < Date.now()) {
|
|
319
|
+
await ttlStorage.delete(k);
|
|
320
|
+
return undefined;
|
|
321
|
+
}
|
|
322
|
+
return value;
|
|
323
|
+
},
|
|
324
|
+
write: async (k, v) => {
|
|
325
|
+
v.e = addExpiryDate(v, millisecondsToLive).expires;
|
|
326
|
+
await storage.write(k, v);
|
|
327
|
+
},
|
|
328
|
+
delete: (k) => storage.delete(k),
|
|
329
|
+
};
|
|
330
|
+
return ttlStorage;
|
|
331
|
+
}
|
|
332
|
+
function migrationStorage(storage, migrations) {
|
|
333
|
+
const versions = Object.keys(migrations)
|
|
334
|
+
.map((v) => parseInt(v))
|
|
335
|
+
.sort((a, b) => a - b);
|
|
336
|
+
const count = versions.length;
|
|
337
|
+
if (count === 0)
|
|
338
|
+
throw new Error("No migrations given!");
|
|
339
|
+
const earliest = versions[0];
|
|
340
|
+
const last = count - 1;
|
|
341
|
+
const latest = versions[last];
|
|
342
|
+
const index = new Map();
|
|
343
|
+
versions.forEach((v, i) => index.set(v, i)); // inverse array lookup
|
|
344
|
+
function nextAfter(current) {
|
|
345
|
+
// TODO: use `findLastIndex` with Node 18
|
|
346
|
+
let i = last;
|
|
347
|
+
while (current <= versions[i])
|
|
348
|
+
i--;
|
|
349
|
+
return i;
|
|
350
|
+
// return versions.findLastIndex((v) => v < current)
|
|
351
|
+
}
|
|
352
|
+
return {
|
|
353
|
+
read: async (k) => {
|
|
354
|
+
var _a;
|
|
355
|
+
const val = await storage.read(k);
|
|
356
|
+
if (val === undefined)
|
|
357
|
+
return val;
|
|
358
|
+
let { __d: value, v: current = earliest - 1 } = val;
|
|
359
|
+
let i = 1 + ((_a = index.get(current)) !== null && _a !== void 0 ? _a : nextAfter(current));
|
|
360
|
+
for (; i < count; i++)
|
|
361
|
+
value = migrations[versions[i]](value);
|
|
362
|
+
return { ...val, v: latest, __d: value };
|
|
363
|
+
},
|
|
364
|
+
write: (k, v) => storage.write(k, { v: latest, ...v }),
|
|
365
|
+
delete: (k) => storage.delete(k),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function wrapStorage(storage) {
|
|
369
|
+
return {
|
|
370
|
+
read: (k) => Promise.resolve(storage.read(k)).then((v) => v === null || v === void 0 ? void 0 : v.__d),
|
|
371
|
+
write: (k, v) => storage.write(k, { __d: v }),
|
|
372
|
+
delete: (k) => storage.delete(k),
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
// === Memory storage adapter
|
|
376
|
+
/**
|
|
377
|
+
* The memory session storage is a built-in storage adapter that saves your
|
|
378
|
+
* session data in RAM using a regular JavaScript `Map` object. If you use this
|
|
379
|
+
* storage adapter, all sessions will be lost when your process terminates or
|
|
380
|
+
* restarts. Hence, you should only use it for short-lived data that is not
|
|
381
|
+
* important to persist.
|
|
382
|
+
*
|
|
383
|
+
* This class is used as default if you do not provide a storage adapter, e.g.
|
|
384
|
+
* to your database.
|
|
385
|
+
*
|
|
386
|
+
* This storage adapter features expiring sessions. When instantiating this
|
|
387
|
+
* class yourself, you can pass a time to live in milliseconds that will be used
|
|
388
|
+
* for each session object. If a session for a user expired, the session data
|
|
389
|
+
* will be discarded on its first read, and a fresh session object as returned
|
|
390
|
+
* by the `initial` option (or undefined) will be put into place.
|
|
391
|
+
*/
|
|
392
|
+
class MemorySessionStorage {
|
|
393
|
+
/**
|
|
394
|
+
* Constructs a new memory session storage with the given time to live. Note
|
|
395
|
+
* that this storage adapter will not store your data permanently.
|
|
396
|
+
*
|
|
397
|
+
* @param timeToLive TTL in milliseconds, default is `Infinity`
|
|
398
|
+
*/
|
|
399
|
+
constructor(timeToLive) {
|
|
400
|
+
this.timeToLive = timeToLive;
|
|
401
|
+
/**
|
|
402
|
+
* Internally used `Map` instance that stores the session data
|
|
403
|
+
*/
|
|
404
|
+
this.storage = new Map();
|
|
405
|
+
}
|
|
406
|
+
read(key) {
|
|
407
|
+
const value = this.storage.get(key);
|
|
408
|
+
if (value === undefined)
|
|
409
|
+
return undefined;
|
|
410
|
+
if (value.expires !== undefined && value.expires < Date.now()) {
|
|
411
|
+
this.delete(key);
|
|
412
|
+
return undefined;
|
|
413
|
+
}
|
|
414
|
+
return value.session;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* @deprecated Use {@link readAllValues} instead
|
|
418
|
+
*/
|
|
419
|
+
readAll() {
|
|
420
|
+
return this.readAllValues();
|
|
421
|
+
}
|
|
422
|
+
readAllKeys() {
|
|
423
|
+
return Array.from(this.storage.keys());
|
|
424
|
+
}
|
|
425
|
+
readAllValues() {
|
|
426
|
+
return Array
|
|
427
|
+
.from(this.storage.keys())
|
|
428
|
+
.map((key) => this.read(key))
|
|
429
|
+
.filter((value) => value !== undefined);
|
|
430
|
+
}
|
|
431
|
+
readAllEntries() {
|
|
432
|
+
return Array.from(this.storage.keys())
|
|
433
|
+
.map((key) => [key, this.read(key)])
|
|
434
|
+
.filter((pair) => pair[1] !== undefined);
|
|
435
|
+
}
|
|
436
|
+
has(key) {
|
|
437
|
+
return this.storage.has(key);
|
|
438
|
+
}
|
|
439
|
+
write(key, value) {
|
|
440
|
+
this.storage.set(key, addExpiryDate(value, this.timeToLive));
|
|
441
|
+
}
|
|
442
|
+
delete(key) {
|
|
443
|
+
this.storage.delete(key);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
exports.MemorySessionStorage = MemorySessionStorage;
|
|
447
|
+
function addExpiryDate(value, ttl) {
|
|
448
|
+
if (ttl !== undefined && ttl < Infinity) {
|
|
449
|
+
const now = Date.now();
|
|
450
|
+
return { session: value, expires: now + ttl };
|
|
451
|
+
}
|
|
452
|
+
else {
|
|
453
|
+
return { session: value };
|
|
454
|
+
}
|
|
455
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { type Bot } from "../bot.js";
|
|
2
|
+
import { type Context } from "../context.js";
|
|
3
|
+
import { type FrameworkAdapter } from "./frameworks.js";
|
|
4
|
+
declare const adapters: {
|
|
5
|
+
callback: FrameworkAdapter;
|
|
6
|
+
"aws-lambda": import("./frameworks.js").LambdaAdapter;
|
|
7
|
+
"aws-lambda-async": import("./frameworks.js").LambdaAsyncAdapter;
|
|
8
|
+
azure: import("./frameworks.js").AzureAdapter;
|
|
9
|
+
"azure-v4": import("./frameworks.js").AzureAdapterV4;
|
|
10
|
+
bun: import("./frameworks.js").BunAdapter;
|
|
11
|
+
cloudflare: import("./frameworks.js").CloudflareAdapter;
|
|
12
|
+
"cloudflare-mod": import("./frameworks.js").CloudflareModuleAdapter;
|
|
13
|
+
elysia: import("./frameworks.js").ElysiaAdapter;
|
|
14
|
+
express: import("./frameworks.js").ExpressAdapter;
|
|
15
|
+
fastify: import("./frameworks.js").FastifyAdapter;
|
|
16
|
+
hono: import("./frameworks.js").HonoAdapter;
|
|
17
|
+
http: import("./frameworks.js").HttpAdapter;
|
|
18
|
+
https: import("./frameworks.js").HttpAdapter;
|
|
19
|
+
koa: import("./frameworks.js").KoaAdapter;
|
|
20
|
+
"next-js": import("./frameworks.js").NextAdapter;
|
|
21
|
+
nhttp: import("./frameworks.js").NHttpAdapter;
|
|
22
|
+
oak: import("./frameworks.js").OakAdapter;
|
|
23
|
+
serveHttp: import("./frameworks.js").ServeHttpAdapter;
|
|
24
|
+
"std/http": import("./frameworks.js").StdHttpAdapter;
|
|
25
|
+
sveltekit: import("./frameworks.js").SveltekitAdapter;
|
|
26
|
+
worktop: import("./frameworks.js").WorktopAdapter;
|
|
27
|
+
};
|
|
28
|
+
export interface WebhookOptions {
|
|
29
|
+
/** An optional strategy to handle timeouts (default: 'throw') */
|
|
30
|
+
onTimeout?: "throw" | "return" | ((...args: any[]) => unknown);
|
|
31
|
+
/** An optional number of timeout milliseconds (default: 10_000) */
|
|
32
|
+
timeoutMilliseconds?: number;
|
|
33
|
+
/** An optional string to compare to X-Telegram-Bot-Api-Secret-Token */
|
|
34
|
+
secretToken?: string;
|
|
35
|
+
}
|
|
36
|
+
type Adapters = typeof adapters;
|
|
37
|
+
type AdapterNames = keyof Adapters;
|
|
38
|
+
type ResolveName<A extends FrameworkAdapter | AdapterNames> = A extends AdapterNames ? Adapters[A] : A;
|
|
39
|
+
/**
|
|
40
|
+
* Creates a callback function that you can pass to a web framework (such as
|
|
41
|
+
* express) if you want to run your bot via webhooks. Use it like this:
|
|
42
|
+
* ```ts
|
|
43
|
+
* const app = express() // or whatever you're using
|
|
44
|
+
* const bot = new Bot('<token>')
|
|
45
|
+
*
|
|
46
|
+
* app.use(webhookCallback(bot, 'express'))
|
|
47
|
+
* ```
|
|
48
|
+
*
|
|
49
|
+
* Confer the grammY
|
|
50
|
+
* [documentation](https://grammy.dev/guide/deployment-types) to read more
|
|
51
|
+
* about how to run your bot with webhooks.
|
|
52
|
+
*
|
|
53
|
+
* @param bot The bot for which to create a callback
|
|
54
|
+
* @param adapter An optional string identifying the framework (default: 'express')
|
|
55
|
+
* @param webhookOptions Further options for the webhook setup
|
|
56
|
+
*/
|
|
57
|
+
export declare function webhookCallback<C extends Context = Context, A extends FrameworkAdapter | AdapterNames = FrameworkAdapter | AdapterNames>(bot: Bot<C>, adapter: A, webhookOptions?: WebhookOptions): (...args: Parameters<ResolveName<A>>) => ReturnType<ResolveName<A>>["handlerReturn"] extends undefined ? Promise<void> : NonNullable<ReturnType<ResolveName<A>>["handlerReturn"]>;
|
|
58
|
+
export declare function webhookCallback<C extends Context = Context, A extends FrameworkAdapter | AdapterNames = FrameworkAdapter | AdapterNames>(bot: Bot<C>, adapter: A, onTimeout?: WebhookOptions["onTimeout"], timeoutMilliseconds?: WebhookOptions["timeoutMilliseconds"], secretToken?: WebhookOptions["secretToken"]): (...args: Parameters<ResolveName<A>>) => ReturnType<ResolveName<A>>["handlerReturn"] extends undefined ? Promise<void> : NonNullable<ReturnType<ResolveName<A>>["handlerReturn"]>;
|
|
59
|
+
export {};
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.webhookCallback = webhookCallback;
|
|
4
|
+
const platform_node_js_1 = require("../platform.node.js");
|
|
5
|
+
const frameworks_js_1 = require("./frameworks.js");
|
|
6
|
+
const debugErr = (0, platform_node_js_1.debug)("grammy:error");
|
|
7
|
+
const callbackAdapter = (update, callback, header, unauthorized = () => callback('"unauthorized"')) => ({
|
|
8
|
+
update: Promise.resolve(update),
|
|
9
|
+
respond: callback,
|
|
10
|
+
header,
|
|
11
|
+
unauthorized,
|
|
12
|
+
});
|
|
13
|
+
const adapters = { ...frameworks_js_1.adapters, callback: callbackAdapter };
|
|
14
|
+
function webhookCallback(bot, adapter = platform_node_js_1.defaultAdapter, onTimeout, timeoutMilliseconds, secretToken) {
|
|
15
|
+
if (bot.isRunning()) {
|
|
16
|
+
throw new Error("Bot is already running via long polling, the webhook setup won't receive any updates!");
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
bot.start = () => {
|
|
20
|
+
throw new Error("You already started the bot via webhooks, calling `bot.start()` starts the bot with long polling and this will prevent your webhook setup from receiving any updates!");
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
const { onTimeout: timeout = "throw", timeoutMilliseconds: ms = 10000, secretToken: token, } = typeof onTimeout === "object"
|
|
24
|
+
? onTimeout
|
|
25
|
+
: { onTimeout, timeoutMilliseconds, secretToken };
|
|
26
|
+
let initialized = false;
|
|
27
|
+
const server = typeof adapter === "string"
|
|
28
|
+
? adapters[adapter]
|
|
29
|
+
: adapter;
|
|
30
|
+
return async (...args) => {
|
|
31
|
+
const { update, respond, unauthorized, end, handlerReturn, header } = server(...args);
|
|
32
|
+
if (!initialized) {
|
|
33
|
+
// Will dedupe concurrently incoming calls from several updates
|
|
34
|
+
await bot.init();
|
|
35
|
+
initialized = true;
|
|
36
|
+
}
|
|
37
|
+
if (header !== token) {
|
|
38
|
+
await unauthorized();
|
|
39
|
+
// TODO: investigate deno bug that happens when this console logging is removed
|
|
40
|
+
console.log(handlerReturn);
|
|
41
|
+
return handlerReturn;
|
|
42
|
+
}
|
|
43
|
+
let usedWebhookReply = false;
|
|
44
|
+
const webhookReplyEnvelope = {
|
|
45
|
+
async send(json) {
|
|
46
|
+
usedWebhookReply = true;
|
|
47
|
+
await respond(json);
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
await timeoutIfNecessary(bot.handleUpdate(await update, webhookReplyEnvelope), typeof timeout === "function" ? () => timeout(...args) : timeout, ms);
|
|
51
|
+
if (!usedWebhookReply)
|
|
52
|
+
end === null || end === void 0 ? void 0 : end();
|
|
53
|
+
return handlerReturn;
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function timeoutIfNecessary(task, onTimeout, timeout) {
|
|
57
|
+
if (timeout === Infinity)
|
|
58
|
+
return task;
|
|
59
|
+
return new Promise((resolve, reject) => {
|
|
60
|
+
const handle = setTimeout(() => {
|
|
61
|
+
debugErr(`Request timed out after ${timeout} ms`);
|
|
62
|
+
if (onTimeout === "throw") {
|
|
63
|
+
reject(new Error(`Request timed out after ${timeout} ms`));
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
if (typeof onTimeout === "function")
|
|
67
|
+
onTimeout();
|
|
68
|
+
resolve();
|
|
69
|
+
}
|
|
70
|
+
const now = Date.now();
|
|
71
|
+
task.finally(() => {
|
|
72
|
+
const diff = Date.now() - now;
|
|
73
|
+
debugErr(`Request completed ${diff} ms after timeout!`);
|
|
74
|
+
});
|
|
75
|
+
}, timeout);
|
|
76
|
+
task.then(resolve)
|
|
77
|
+
.catch(reject)
|
|
78
|
+
.finally(() => clearTimeout(handle));
|
|
79
|
+
});
|
|
80
|
+
}
|