@codebam/cf-workers-telegram-bot 3.40.0
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 +176 -0
- package/LICENSE_MIT +21 -0
- package/README.md +51 -0
- package/dist/main/src/bot_api.d.ts +10 -0
- package/dist/main/src/bot_api.js +11 -0
- package/dist/main/src/handler.d.ts +12 -0
- package/dist/main/src/handler.js +51 -0
- package/dist/main/src/libs.d.ts +10 -0
- package/dist/main/src/libs.js +30 -0
- package/dist/main/src/main.d.ts +11 -0
- package/dist/main/src/main.js +11 -0
- package/dist/main/src/telegram_api.d.ts +30 -0
- package/dist/main/src/telegram_api.js +153 -0
- package/dist/main/src/telegram_bot.d.ts +26 -0
- package/dist/main/src/telegram_bot.js +152 -0
- package/dist/main/src/telegram_commands.d.ts +19 -0
- package/dist/main/src/telegram_commands.js +16 -0
- package/dist/main/src/telegram_webhook.d.ts +10 -0
- package/dist/main/src/telegram_webhook.js +21 -0
- package/dist/main/src/types.d.ts +220 -0
- package/dist/main/src/types.js +100 -0
- package/dist/main/src/webhook.d.ts +10 -0
- package/dist/main/src/webhook.js +17 -0
- package/dist/worker/src/worker.d.ts +12 -0
- package/dist/worker/src/worker.js +64 -0
- package/package.json +42 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
package/LICENSE_MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2020 Nikhil John
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# cf-workers-telegram-bot
|
|
2
|
+
|
|
3
|
+
serverless telegram bot on cf workers
|
|
4
|
+
|
|
5
|
+
The original `worker.js` is the content of Nikhil John's
|
|
6
|
+
https://github.com/nikhiljohn10/telegram-bot-worker which is licensed with MIT.
|
|
7
|
+
My modifications are licensed under the Apache license.
|
|
8
|
+
|
|
9
|
+
[](https://deploy.workers.cloudflare.com/?url=https://github.com/codebam/cf-workers-telegram-bot)
|
|
10
|
+
|
|
11
|
+
To use the deploy button:
|
|
12
|
+
|
|
13
|
+
- Click the deploy button
|
|
14
|
+
- Navigate to your new **GitHub repository > Settings > Secrets** and add the following secrets:
|
|
15
|
+
|
|
16
|
+
```yaml
|
|
17
|
+
- Name: CF_API_TOKEN (should be added automatically)
|
|
18
|
+
- Name: CF_ACCOUNT_ID (should be added automatically)
|
|
19
|
+
|
|
20
|
+
- Name: SECRET_TELEGRAM_API_TOKEN
|
|
21
|
+
- Value: your-telegram-bot-token
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
- Push to `master` to trigger a deploy
|
|
25
|
+
|
|
26
|
+
To fork this repo and use wrangler:
|
|
27
|
+
|
|
28
|
+
- Click fork
|
|
29
|
+
- `wrangler secret put SECRET_TELEGRAM_API_TOKEN` and set it to your telegram
|
|
30
|
+
bot token
|
|
31
|
+
- `wrangler publish`
|
|
32
|
+
- Done!
|
|
33
|
+
|
|
34
|
+
## Getting started with cf-workers-telegram-bot
|
|
35
|
+
|
|
36
|
+
Once you've deployed the bot you can get your Webhook command URL by doing any
|
|
37
|
+
of the following.
|
|
38
|
+
|
|
39
|
+
- sha256sum(YourTelegramSecretKey) is the path to your webhook commands and
|
|
40
|
+
should be put at the end of your worker URL to access commands such as
|
|
41
|
+
setting your webhook
|
|
42
|
+
- Use `sha256sum <<< "your secret key"` to get the path
|
|
43
|
+
- Open the Cloudflare Worker Logs under **Workers > cf-workers-telegram-bot
|
|
44
|
+
> Logs > Begin log stream** and make a GET request (open it in your browser)
|
|
45
|
+
to your Worker URL and look at the logs to see your Access URL
|
|
46
|
+
- Run `wrangler tail --format pretty` from inside your git repository and make
|
|
47
|
+
a GET request to your Worker URL
|
|
48
|
+
|
|
49
|
+
Example URL for setting the Webhook and dropping pending updates:
|
|
50
|
+
|
|
51
|
+
`https://cf-workers-telegram-bot.codebam.workers.dev/a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447?command=set`
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
import Handler from "./handler";
|
|
3
|
+
import { Commands, Config, Update, Webhook } from "./types";
|
|
4
|
+
export default class BotApi {
|
|
5
|
+
commands: Commands;
|
|
6
|
+
webhook: Config["webhook"];
|
|
7
|
+
handler: Handler;
|
|
8
|
+
update: (update: Update) => Promise<Response>;
|
|
9
|
+
constructor(commands: Commands, webhook: Webhook, handler: Handler);
|
|
10
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
import BotApi from "./bot_api";
|
|
3
|
+
import { PartialConfig } from "./types";
|
|
4
|
+
export default class Handler {
|
|
5
|
+
configs: PartialConfig[];
|
|
6
|
+
constructor(configs: PartialConfig[]);
|
|
7
|
+
getResponse: (_request?: Request, _bot?: BotApi) => Promise<Response>;
|
|
8
|
+
postResponse: (_request?: Request, _bot?: BotApi) => Promise<Response>;
|
|
9
|
+
responses: Record<string, (_request?: Request, _bot?: BotApi) => Promise<Response>>;
|
|
10
|
+
getAccessKeys: (configs: PartialConfig[]) => Promise<Record<string, any> | Record<string, never>>;
|
|
11
|
+
handle: (request: Request) => Promise<Response>;
|
|
12
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import BotApi from "./bot_api";
|
|
2
|
+
import { sha256, log } from "./libs";
|
|
3
|
+
import { Config, Webhook, localhost, } from "./types";
|
|
4
|
+
export default class Handler {
|
|
5
|
+
configs;
|
|
6
|
+
constructor(configs) {
|
|
7
|
+
this.configs = configs;
|
|
8
|
+
}
|
|
9
|
+
getResponse = async (_request, _bot) => {
|
|
10
|
+
this.getAccessKeys(this.configs).then((access_keys) => Object.keys(access_keys).forEach((key) => log(`${access_keys[key].bot_name} ${new URL(_request?.url ?? localhost).origin}/${key}`)));
|
|
11
|
+
if (_bot?.webhook.token) {
|
|
12
|
+
return _bot.webhook.process(new URL(_request?.url ?? localhost));
|
|
13
|
+
}
|
|
14
|
+
return this.responses.default();
|
|
15
|
+
};
|
|
16
|
+
postResponse = async (_request, _bot) => {
|
|
17
|
+
const bot = _bot ??
|
|
18
|
+
new BotApi({}, new Webhook(localhost, "", localhost), new Handler([new Config()]));
|
|
19
|
+
if (bot.webhook.token) {
|
|
20
|
+
const request = _request ?? new Request("");
|
|
21
|
+
return (request
|
|
22
|
+
.json()
|
|
23
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
24
|
+
.then((update) => bot.update(update)));
|
|
25
|
+
}
|
|
26
|
+
return this.responses.default();
|
|
27
|
+
};
|
|
28
|
+
responses = {
|
|
29
|
+
GET: this.getResponse,
|
|
30
|
+
POST: this.postResponse,
|
|
31
|
+
default: () => new Promise(() => new Response()),
|
|
32
|
+
};
|
|
33
|
+
getAccessKeys = async (configs
|
|
34
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
35
|
+
) => Promise.all(configs.map((bot_config) => sha256(bot_config.webhook?.token ?? "").then((hash) => [
|
|
36
|
+
hash,
|
|
37
|
+
bot_config,
|
|
38
|
+
]))).then((result) => Object.fromEntries(result));
|
|
39
|
+
// handles the request
|
|
40
|
+
handle = async (request) => this.getAccessKeys(this.configs).then((access_keys) => {
|
|
41
|
+
if (Object.keys(this.responses).includes(request.method)) {
|
|
42
|
+
return this.responses[request.method](request, new access_keys[new URL(request.url).pathname.substring(1)].api({
|
|
43
|
+
...new Config(),
|
|
44
|
+
url: new URL(new URL(request.url).origin),
|
|
45
|
+
handler: this,
|
|
46
|
+
...access_keys[new URL(request.url).pathname.substring(1)],
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
return this.responses.default();
|
|
50
|
+
});
|
|
51
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
export declare const sha256: (text: string) => Promise<string>;
|
|
3
|
+
export declare const prettyJSON: (obj: unknown) => string;
|
|
4
|
+
export declare const JSONResponse: (obj: unknown, status?: number) => Response;
|
|
5
|
+
export declare const log: (obj: any) => any;
|
|
6
|
+
export declare const preTagString: (str: string) => string;
|
|
7
|
+
export declare const addSearchParams: (url: URL, params?: Record<string, string>) => URL;
|
|
8
|
+
export declare const responseToJSON: (response: Response) => Promise<Record<string, unknown>>;
|
|
9
|
+
export declare const undefinedEmpty: <T>(obj: T) => T[];
|
|
10
|
+
export declare const fetch_json: (url: URL) => Promise<Response>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export const sha256 = async (text) => crypto.subtle
|
|
2
|
+
.digest("SHA-256", new TextEncoder().encode(text))
|
|
3
|
+
.then((array_buffer) => Array.from(new Uint8Array(array_buffer))
|
|
4
|
+
.map((b) => b.toString(16).padStart(2, "0"))
|
|
5
|
+
.join(""));
|
|
6
|
+
// format json with line indents and newlines
|
|
7
|
+
export const prettyJSON = (obj) => JSON.stringify(obj, null, 2);
|
|
8
|
+
// Generate JSON response
|
|
9
|
+
export const JSONResponse = (obj, status = 200) => new Response(prettyJSON(obj), {
|
|
10
|
+
status: status,
|
|
11
|
+
headers: {
|
|
12
|
+
"content-type": "application/json",
|
|
13
|
+
},
|
|
14
|
+
});
|
|
15
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
16
|
+
export const log = (obj) => console.log(obj) === undefined && obj;
|
|
17
|
+
export const preTagString = (str) => `<pre>${str}</pre>`;
|
|
18
|
+
export const addSearchParams = (url, params = {}) => new URL(`${url.origin}${url.pathname}?${new URLSearchParams(Object.entries(Object.fromEntries([
|
|
19
|
+
...Array.from(url.searchParams.entries()),
|
|
20
|
+
...Object.entries(params),
|
|
21
|
+
]))).toString()}`);
|
|
22
|
+
export const responseToJSON = async (response) => response
|
|
23
|
+
.clone()
|
|
24
|
+
.text()
|
|
25
|
+
.then((text) => JSON.parse(text))
|
|
26
|
+
.catch(() => log({ error: "Failed to parse JSON of response" }));
|
|
27
|
+
export const undefinedEmpty = (obj) => (obj === undefined && []) || [obj];
|
|
28
|
+
export const fetch_json = async (url) => fetch(url.href)
|
|
29
|
+
.then((response) => responseToJSON(response))
|
|
30
|
+
.then((json) => JSONResponse(json));
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import BotApi from "./bot_api";
|
|
2
|
+
import Handler from "./handler";
|
|
3
|
+
import * as Libs from "./libs";
|
|
4
|
+
import TelegramApi from "./telegram_api";
|
|
5
|
+
import TelegramBot from "./telegram_bot";
|
|
6
|
+
import TelegramCommands from "./telegram_commands";
|
|
7
|
+
import TelegramWebhook from "./telegram_webhook";
|
|
8
|
+
import * as Types from "./types";
|
|
9
|
+
import Webhook from "./webhook";
|
|
10
|
+
import worker from "../../worker/src/worker";
|
|
11
|
+
export { BotApi, Handler, Libs, TelegramApi, TelegramBot, TelegramCommands, TelegramWebhook, Types, Webhook, worker, };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import BotApi from "./bot_api";
|
|
2
|
+
import Handler from "./handler";
|
|
3
|
+
import * as Libs from "./libs";
|
|
4
|
+
import TelegramApi from "./telegram_api";
|
|
5
|
+
import TelegramBot from "./telegram_bot";
|
|
6
|
+
import TelegramCommands from "./telegram_commands";
|
|
7
|
+
import TelegramWebhook from "./telegram_webhook";
|
|
8
|
+
import * as Types from "./types";
|
|
9
|
+
import Webhook from "./webhook";
|
|
10
|
+
import worker from "../../worker/src/worker";
|
|
11
|
+
export { BotApi, Handler, Libs, TelegramApi, TelegramBot, TelegramCommands, TelegramWebhook, Types, Webhook, worker, };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
import BotApi from "./bot_api";
|
|
3
|
+
import { Commands, TelegramInlineQueryResult, TelegramUpdate, Webhook, Update } from "./types";
|
|
4
|
+
import Handler from "./handler";
|
|
5
|
+
export default class TelegramApi extends BotApi {
|
|
6
|
+
constructor(commands: Commands, webhook: Webhook, handler: Handler);
|
|
7
|
+
inlineQueryUpdate: (update: TelegramUpdate) => Promise<Response>;
|
|
8
|
+
messageUpdate: (update: TelegramUpdate) => Promise<Response>;
|
|
9
|
+
updates: {
|
|
10
|
+
inline_query: (update: TelegramUpdate) => Promise<Response>;
|
|
11
|
+
message: (update: TelegramUpdate) => Promise<Response>;
|
|
12
|
+
default: Response;
|
|
13
|
+
};
|
|
14
|
+
update: (update: Update) => Promise<Response>;
|
|
15
|
+
greetUsers: (update: TelegramUpdate) => Promise<Response>;
|
|
16
|
+
getCommand: (args: string[]) => string;
|
|
17
|
+
_executeCommand: (update: TelegramUpdate, text: string, args?: string[]) => Promise<any>;
|
|
18
|
+
executeInlineCommand: (update: TelegramUpdate) => Promise<Response>;
|
|
19
|
+
executeCommand: (update: TelegramUpdate) => Promise<Response>;
|
|
20
|
+
answerInlineQuery: (inline_query_id: number, results: TelegramInlineQueryResult[], cache_time?: number) => Promise<Response>;
|
|
21
|
+
sendMessage: (chat_id: number, text: string, parse_mode?: string, disable_web_page_preview?: boolean, disable_notification?: boolean, reply_to_message_id?: number) => Promise<Response>;
|
|
22
|
+
forwardMessage: (chat_id: number, from_chat_id: number, disable_notification: boolean | undefined, message_id: number) => Promise<Response>;
|
|
23
|
+
sendPhoto: (chat_id: number, photo: string, caption?: string, parse_mode?: string, disable_notification?: boolean, reply_to_message_id?: number) => Promise<Response>;
|
|
24
|
+
sendVideo: (chat_id: number, video: Blob, duration?: number, width?: number, height?: number, thumb?: string, caption?: string, parse_mode?: string, supports_streaming?: boolean, disable_notification?: boolean, reply_to_message_id?: number) => Promise<Response>;
|
|
25
|
+
sendAnimation: (chat_id: number, animation: Blob, duration?: number, width?: number, height?: number, thumb?: string, caption?: string, parse_mode?: string, disable_notification?: boolean, reply_to_message_id?: number) => Promise<Response>;
|
|
26
|
+
sendLocation: (chat_id: number, latitude: number, longitude: number, live_period?: number, disable_notification?: boolean, reply_to_message_id?: number) => Promise<Response>;
|
|
27
|
+
sendPoll: (chat_id: number, question: string, options: string[], is_anonymous?: boolean, type?: string, allows_multiple_answers?: boolean, correct_option_id?: number, explanation?: string, explanation_parse_mode?: string, open_period?: number, close_date?: number, is_closed?: boolean, disable_notification?: boolean, reply_to_message_id?: number) => Promise<Response>;
|
|
28
|
+
sendDice: (chat_id: number, emoji?: string, disable_notification?: boolean, reply_to_message_id?: number) => Promise<Response>;
|
|
29
|
+
getUserProfilePhotos: (user_id: number, offset?: number, limit?: number) => Promise<Response>;
|
|
30
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import BotApi from "./bot_api";
|
|
2
|
+
import { addSearchParams, log, responseToJSON } from "./libs";
|
|
3
|
+
export default class TelegramApi extends BotApi {
|
|
4
|
+
constructor(commands, webhook, handler) {
|
|
5
|
+
super(commands, webhook, handler);
|
|
6
|
+
}
|
|
7
|
+
inlineQueryUpdate = async (update) => this.executeInlineCommand(update).then(async (response) => (await responseToJSON(response)) && response);
|
|
8
|
+
messageUpdate = async (update) => {
|
|
9
|
+
if (typeof (update.message?.text ?? false) === "string") {
|
|
10
|
+
return await this.executeCommand(update).then(async () => await this.greetUsers(update));
|
|
11
|
+
}
|
|
12
|
+
return this.updates.default;
|
|
13
|
+
};
|
|
14
|
+
updates = {
|
|
15
|
+
inline_query: this.inlineQueryUpdate,
|
|
16
|
+
message: this.messageUpdate,
|
|
17
|
+
default: new Response(),
|
|
18
|
+
};
|
|
19
|
+
update = async (update) => (log({ update }) &&
|
|
20
|
+
update.message !== undefined &&
|
|
21
|
+
(await this.updates.message(update))) ||
|
|
22
|
+
(update.inline_query !== undefined &&
|
|
23
|
+
update.inline_query.query !== "" &&
|
|
24
|
+
(await this.updates.inline_query(update))) ||
|
|
25
|
+
this.updates.default;
|
|
26
|
+
// greet new users who join
|
|
27
|
+
greetUsers = async (update) => {
|
|
28
|
+
if (update.message?.new_chat_members !== undefined) {
|
|
29
|
+
return this.sendMessage(update.message.chat.id, `Welcome to ${update.message.chat.title}, ${update.message.from.username}`);
|
|
30
|
+
}
|
|
31
|
+
return this.updates.default;
|
|
32
|
+
};
|
|
33
|
+
getCommand = (args) => args[0]?.split("@")[0];
|
|
34
|
+
// run command passed from executeCommand
|
|
35
|
+
_executeCommand = async (update, text, args = []) => (log({ execute: { text, args } }) &&
|
|
36
|
+
(async (text_args) => ((command) => ((this.commands[command] ||
|
|
37
|
+
log({
|
|
38
|
+
error: `command '${command}' does not exist`,
|
|
39
|
+
})) &&
|
|
40
|
+
this.commands[command]?.(this, update, [...text_args, ...args])) ||
|
|
41
|
+
// run the command
|
|
42
|
+
this.updates.default)(this.getCommand(text_args)))(
|
|
43
|
+
// get the command to run
|
|
44
|
+
text
|
|
45
|
+
.trimStart()
|
|
46
|
+
.replace(/^([^\s]*\s)\s*/gm, "$1")
|
|
47
|
+
.split(" "))) ??
|
|
48
|
+
this.updates.default;
|
|
49
|
+
// execute the inline custom bot commands from bot configurations
|
|
50
|
+
executeInlineCommand = async (update) => ((await this._executeCommand(update, update.inline_query?.query ?? "")) &&
|
|
51
|
+
(await this._executeCommand(update, "inline", update.inline_query?.query.trimStart().split(" ")))) ??
|
|
52
|
+
this.updates.default;
|
|
53
|
+
// execute the custom bot commands from bot configurations
|
|
54
|
+
executeCommand = async (update) => this._executeCommand(update, update.message?.text ?? "") ||
|
|
55
|
+
this.updates.default;
|
|
56
|
+
// trigger answerInlineQuery command of BotAPI
|
|
57
|
+
answerInlineQuery = async (inline_query_id, results, cache_time = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.href}/answerInlineQuery`), {
|
|
58
|
+
inline_query_id: inline_query_id.toString(),
|
|
59
|
+
results: JSON.stringify(results),
|
|
60
|
+
cache_time: cache_time.toString(),
|
|
61
|
+
}).href));
|
|
62
|
+
// trigger sendMessage command of BotAPI
|
|
63
|
+
sendMessage = async (chat_id, text, parse_mode = "", disable_web_page_preview = false, disable_notification = false, reply_to_message_id = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.href}/sendMessage`), {
|
|
64
|
+
chat_id: chat_id.toString(),
|
|
65
|
+
text,
|
|
66
|
+
parse_mode: parse_mode,
|
|
67
|
+
disable_web_page_preview: disable_web_page_preview.toString(),
|
|
68
|
+
disable_notification: disable_notification.toString(),
|
|
69
|
+
reply_to_message_id: reply_to_message_id.toString(),
|
|
70
|
+
}).href));
|
|
71
|
+
// trigger forwardMessage command of BotAPI
|
|
72
|
+
forwardMessage = async (chat_id, from_chat_id, disable_notification = false, message_id) => fetch(log(addSearchParams(new URL(`${this.webhook.api.href}/sendMessage`), {
|
|
73
|
+
chat_id: chat_id.toString(),
|
|
74
|
+
from_chat_id: from_chat_id.toString(),
|
|
75
|
+
message_id: message_id.toString(),
|
|
76
|
+
disable_notification: disable_notification.toString(),
|
|
77
|
+
}).href));
|
|
78
|
+
// trigger sendPhoto command of BotAPI
|
|
79
|
+
sendPhoto = async (chat_id, photo, caption = "", parse_mode = "", disable_notification = false, reply_to_message_id = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.href}/sendPhoto`), {
|
|
80
|
+
chat_id: chat_id.toString(),
|
|
81
|
+
photo,
|
|
82
|
+
caption,
|
|
83
|
+
parse_mode,
|
|
84
|
+
disable_notification: disable_notification.toString(),
|
|
85
|
+
reply_to_message_id: reply_to_message_id.toString(),
|
|
86
|
+
}).href));
|
|
87
|
+
// trigger sendVideo command of BotAPI
|
|
88
|
+
sendVideo = async (chat_id, video, duration = 0, width = 0, height = 0, thumb = "", caption = "", parse_mode = "", supports_streaming = false, disable_notification = false, reply_to_message_id = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.href}/sendVideo`), {
|
|
89
|
+
chat_id: chat_id.toString(),
|
|
90
|
+
video: JSON.stringify(video),
|
|
91
|
+
duration: duration.toString(),
|
|
92
|
+
width: width.toString(),
|
|
93
|
+
height: height.toString(),
|
|
94
|
+
thumb: thumb,
|
|
95
|
+
caption: caption,
|
|
96
|
+
parse_mode: parse_mode,
|
|
97
|
+
supports_streaming: supports_streaming.toString(),
|
|
98
|
+
disable_notification: disable_notification.toString(),
|
|
99
|
+
reply_to_message_id: reply_to_message_id.toString(),
|
|
100
|
+
}).href));
|
|
101
|
+
// trigger sendAnimation command of BotAPI
|
|
102
|
+
sendAnimation = async (chat_id, animation, duration = 0, width = 0, height = 0, thumb = "", caption = "", parse_mode = "", disable_notification = false, reply_to_message_id = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.href}/sendAnimation`), {
|
|
103
|
+
chat_id: chat_id.toString(),
|
|
104
|
+
animation: JSON.stringify(animation),
|
|
105
|
+
duration: duration.toString(),
|
|
106
|
+
width: width.toString(),
|
|
107
|
+
height: height.toString(),
|
|
108
|
+
thumb,
|
|
109
|
+
caption,
|
|
110
|
+
parse_mode,
|
|
111
|
+
disable_notification: disable_notification.toString(),
|
|
112
|
+
reply_to_message_id: reply_to_message_id.toString(),
|
|
113
|
+
}).href));
|
|
114
|
+
// trigger sendLocation command of BotAPI
|
|
115
|
+
sendLocation = async (chat_id, latitude, longitude, live_period = 0, disable_notification = false, reply_to_message_id = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.href}/sendLocation`), {
|
|
116
|
+
chat_id: chat_id.toString(),
|
|
117
|
+
latitude: latitude.toString(),
|
|
118
|
+
longitude: longitude.toString(),
|
|
119
|
+
live_period: live_period.toString(),
|
|
120
|
+
disable_notification: disable_notification.toString(),
|
|
121
|
+
reply_to_message_id: reply_to_message_id.toString(),
|
|
122
|
+
}).href));
|
|
123
|
+
// trigger senPoll command of BotAPI
|
|
124
|
+
sendPoll = async (chat_id, question, options, is_anonymous = false, type = "", allows_multiple_answers = false, correct_option_id = 0, explanation = "", explanation_parse_mode = "", open_period = 0, close_date = 0, is_closed = false, disable_notification = false, reply_to_message_id = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.href}/sendPoll`), {
|
|
125
|
+
chat_id: chat_id.toString(),
|
|
126
|
+
question,
|
|
127
|
+
options: options.toString(),
|
|
128
|
+
is_anonymous: is_anonymous.toString(),
|
|
129
|
+
type,
|
|
130
|
+
allows_multiple_answers: allows_multiple_answers.toString(),
|
|
131
|
+
correct_option_id: correct_option_id.toString(),
|
|
132
|
+
explanation: explanation,
|
|
133
|
+
explanation_parse_mode: explanation_parse_mode,
|
|
134
|
+
open_period: open_period.toString(),
|
|
135
|
+
close_date: close_date.toString(),
|
|
136
|
+
is_closed: is_closed.toString(),
|
|
137
|
+
disable_notification: disable_notification.toString(),
|
|
138
|
+
reply_to_message_id: reply_to_message_id.toString(),
|
|
139
|
+
}).href));
|
|
140
|
+
// trigger senDice command of BotAPI
|
|
141
|
+
sendDice = async (chat_id, emoji = "", disable_notification = false, reply_to_message_id = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.href}/sendDice`), {
|
|
142
|
+
chat_id: chat_id.toString(),
|
|
143
|
+
emoji,
|
|
144
|
+
disable_notification: disable_notification.toString(),
|
|
145
|
+
reply_to_message_id: reply_to_message_id.toString(),
|
|
146
|
+
}).href));
|
|
147
|
+
// bot api command to get user profile photos
|
|
148
|
+
getUserProfilePhotos = async (user_id, offset = 0, limit = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.href}/getUserProfilePhotos`), {
|
|
149
|
+
user_id: user_id.toString(),
|
|
150
|
+
offset: offset.toString(),
|
|
151
|
+
limit: limit.toString(),
|
|
152
|
+
}).href));
|
|
153
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
import TelegramApi from "./telegram_api";
|
|
3
|
+
import { TelegramUpdate, Config, Kv } from "./types";
|
|
4
|
+
export default class TelegramBot extends TelegramApi {
|
|
5
|
+
url: URL;
|
|
6
|
+
kv: Kv;
|
|
7
|
+
get_set: KVNamespace;
|
|
8
|
+
constructor(config: Config);
|
|
9
|
+
code: (update: TelegramUpdate) => Promise<Response>;
|
|
10
|
+
duckduckgo: (update: TelegramUpdate, args: string[]) => Promise<Response>;
|
|
11
|
+
kanye: (update: TelegramUpdate) => Promise<Response>;
|
|
12
|
+
joke: (update: TelegramUpdate) => Promise<Response>;
|
|
13
|
+
dog: (update: TelegramUpdate) => Promise<Response>;
|
|
14
|
+
cat: (update: TelegramUpdate) => Promise<Response>;
|
|
15
|
+
bored: (update: TelegramUpdate) => Promise<Response>;
|
|
16
|
+
epoch: (update: TelegramUpdate) => Promise<Response>;
|
|
17
|
+
_get: (update: TelegramUpdate, args: string[]) => Promise<Response>;
|
|
18
|
+
_set: (update: TelegramUpdate, args: string[]) => Promise<Response>;
|
|
19
|
+
_average: (numbers: number[]) => number;
|
|
20
|
+
recursion: (update: TelegramUpdate) => Promise<Response>;
|
|
21
|
+
roll: (update: TelegramUpdate, args: string[]) => Promise<Response>;
|
|
22
|
+
commandList: (update: TelegramUpdate) => Promise<Response>;
|
|
23
|
+
toss: (update: TelegramUpdate) => Promise<Response>;
|
|
24
|
+
ping: (update: TelegramUpdate, args: string[]) => Promise<Response>;
|
|
25
|
+
getChatInfo: (update: TelegramUpdate) => Promise<Response>;
|
|
26
|
+
}
|