/
webhook.ts
187 lines (181 loc) · 5.84 KB
/
webhook.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// deno-lint-ignore-file no-explicit-any
import { Bot } from "../bot.ts";
import { debug as d, Update } from "../platform.deno.ts";
import { WebhookReplyEnvelope } from "../core/client.ts";
import { Context } from "../context.ts";
const debugErr = d("grammy:error");
/**
* HTTP Web frameworks for which grammY provides compatible callback out of the
* box.
*/
type SupportedFrameworks =
| "express"
| "http"
| "https"
| "koa"
| "oak"
| "fastify"
| "worktop"
| "callback"
| "aws-lambda";
/**
* Abstraction over a request-response cycle, provding access to the update, as
* well as a mechanism for responding to the request and to end it.
*/
interface ReqResHandler {
/**
* The update object sent from Telegram, usually resolves the request's JSON
* body
*/
update: Promise<Update>;
/**
* Ends the request immediately without body, called after every request
* unless a webhook reply was performed
*/
end?: () => void;
/**
* Sends the specified JSON as a payload in the body, used for webhook
* replies
*/
respond: (json: string) => unknown;
}
/**
* Middleware for a web framework. Creates a request-response handler for a
* request. The handler will be used to integrate with the compatible framework.
*/
type FrameworkAdapter = (...args: any[]) => ReqResHandler;
const standard: FrameworkAdapter = (req, res) => ({
update: Promise.resolve(req.body),
end: () => res.end(),
respond: (json) => {
res.set("Content-Type", "application/json");
res.send(json);
},
});
// Integrations with popular frameworks
const frameworkAdapters: Record<SupportedFrameworks, FrameworkAdapter> = {
express: standard,
http: standard,
https: standard,
koa: (ctx) => ({
update: Promise.resolve(ctx.request.body),
end: () => (ctx.body = ""),
respond: (json) => {
ctx.set("Content-Type", "application/json");
ctx.response.body = json;
},
}),
oak: (ctx) => ({
update: ctx.request.body({ type: "json" }).value,
end: () => (ctx.response.status = 200),
respond: (json) => {
ctx.response.type = "json";
ctx.response.body = json;
},
}),
fastify: (req, reply) => ({
update: Promise.resolve(req.body),
end: () => reply.send({}),
respond: (json) => reply.send(json),
}),
worktop: (req, res) => ({
update: Promise.resolve(req.body.json()),
end: () => res.end(),
respond: (json) => res.send(200, json),
}),
callback: (update, callback) => ({
update: update,
respond: callback,
}),
"aws-lambda": (event, _context, callback) => ({
update: JSON.parse(event.body),
end: () => callback(null, { statusCode: 200 }),
respond: (json) =>
callback(null, {
statusCode: 200,
body: json,
}),
}),
// please open a PR if you want to add another
};
/**
* Creates a callback function that you can pass to a web framework (such as
* express) if you want to run your bot via webhooks. Use it like this:
* ```ts
* const app = express() // or whatever you're using
* const bot = new Bot('<token>')
*
* app.use(webhookCallback(bot, 'express'))
* ```
*
* Confer the grammY
* [documentation](https://grammy.dev/guide/deployment-types.html) to read more
* about how to run your bot with webhooks.
*
* @param bot The bot for which to create a callback
* @param framework An optional string identifying the framework (default: 'express')
* @param onTimeout An optional strategy to handle timeouts (default: 'throw')
* @param timeoutMilliseconds An optional number of timeout milliseconds (default: 10_000)
*/
export function webhookCallback<C extends Context = Context>(
bot: Bot<C>,
framework: SupportedFrameworks = "express",
onTimeout: "throw" | "return" | ((...args: any[]) => unknown) = "throw",
timeoutMilliseconds = 10_000,
) {
const server = frameworkAdapters[framework] ?? standard;
let firstUpdate = true;
let initialized = false;
let initCall: Promise<void> | undefined;
return async (...args: any[]) => {
const { update, respond, end } = server(...args);
let usedWebhookReply = false;
const webhookReplyEnvelope: WebhookReplyEnvelope = {
send: async (json) => {
usedWebhookReply = true;
await respond(json);
},
};
if (!initialized) {
if (firstUpdate) {
initCall = bot.init();
firstUpdate = false;
}
await initCall;
initialized = true;
}
await timeoutIfNecessary(
bot.handleUpdate(await update, webhookReplyEnvelope),
typeof onTimeout === "function"
? () => onTimeout(...args)
: onTimeout,
timeoutMilliseconds,
);
if (end !== undefined && !usedWebhookReply) end();
};
}
function timeoutIfNecessary(
task: Promise<void>,
onTimeout: "throw" | "return" | (() => unknown),
timeout: number,
): Promise<void> {
if (timeout === Infinity) return task;
return new Promise((resolve, reject) => {
const handle = setTimeout(() => {
if (onTimeout === "throw") {
reject(new Error(`Request timed out after ${timeout} ms`));
} else {
if (typeof onTimeout === "function") onTimeout();
resolve();
}
const now = Date.now();
task.finally(() => {
const diff = Date.now() - now;
debugErr(`Request completed ${diff} ms after timeout!`);
});
}, timeout);
task.then(resolve)
.catch(reject)
.finally(() => clearTimeout(handle));
});
}