@codebam/cf-workers-telegram-bot 7.6.0 → 7.8.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.
Files changed (74) hide show
  1. package/README.md +2 -8
  2. package/dist/api.d.ts +29 -0
  3. package/dist/api.js +37 -0
  4. package/dist/ctx.d.ts +19 -0
  5. package/dist/ctx.js +107 -0
  6. package/dist/main.d.ts +4 -0
  7. package/dist/main.js +4 -0
  8. package/dist/{main/src/telegram_bot.d.ts → telegram_bot.d.ts} +6 -10
  9. package/dist/telegram_bot.js +73 -0
  10. package/dist/types/SerializableData.d.ts +2 -0
  11. package/dist/{main/src/types → types}/TelegramInlineQueryResultPhoto.d.ts +2 -0
  12. package/dist/{main/src/types → types}/TelegramInlineQueryResultPhoto.js +1 -1
  13. package/dist/types/TelegramInlineQueryResultVideo.d.ts +15 -0
  14. package/dist/types/TelegramInlineQueryResultVideo.js +19 -0
  15. package/dist/types/TelegramUser.js +1 -0
  16. package/dist/{main/src/types.d.ts → types.d.ts} +2 -1
  17. package/dist/webhook.d.ts +7 -0
  18. package/dist/webhook.js +17 -0
  19. package/package.json +2 -2
  20. package/LICENSE_MIT +0 -21
  21. package/dist/main/src/main.d.ts +0 -4
  22. package/dist/main/src/main.js +0 -4
  23. package/dist/main/src/telegram_bot.js +0 -116
  24. package/dist/worker/src/worker.d.ts +0 -18
  25. package/dist/worker/src/worker.js +0 -81
  26. /package/dist/{main/src/types → types}/Balance.d.ts +0 -0
  27. /package/dist/{main/src/types → types}/Balance.js +0 -0
  28. /package/dist/{main/src/types → types}/Bored.d.ts +0 -0
  29. /package/dist/{main/src/types → types}/Bored.js +0 -0
  30. /package/dist/{main/src/types → types}/ChatPermissions.d.ts +0 -0
  31. /package/dist/{main/src/types → types}/ChatPermissions.js +0 -0
  32. /package/dist/{main/src/types → types}/DDGQueryResponse.d.ts +0 -0
  33. /package/dist/{main/src/types → types}/DDGQueryResponse.js +0 -0
  34. /package/dist/{main/src/types → types}/Joke.d.ts +0 -0
  35. /package/dist/{main/src/types → types}/Joke.js +0 -0
  36. /package/dist/{main/src/types → types}/Kanye.d.ts +0 -0
  37. /package/dist/{main/src/types → types}/Kanye.js +0 -0
  38. /package/dist/{main/src/types → types}/Kv.d.ts +0 -0
  39. /package/dist/{main/src/types → types}/Kv.js +0 -0
  40. /package/dist/{main/src/types → types}/PartialTelegramUpdate.d.ts +0 -0
  41. /package/dist/{main/src/types → types}/PartialTelegramUpdate.js +0 -0
  42. /package/dist/{main/src/types/TelegramChat.js → types/SerializableData.js} +0 -0
  43. /package/dist/{main/src/types → types}/TelegramChat.d.ts +0 -0
  44. /package/dist/{main/src/types/TelegramCommand.js → types/TelegramChat.js} +0 -0
  45. /package/dist/{main/src/types → types}/TelegramCommand.d.ts +0 -0
  46. /package/dist/{main/src/types/TelegramFrom.js → types/TelegramCommand.js} +0 -0
  47. /package/dist/{main/src/types → types}/TelegramFrom.d.ts +0 -0
  48. /package/dist/{main/src/types/TelegramInlineQuery.js → types/TelegramFrom.js} +0 -0
  49. /package/dist/{main/src/types → types}/TelegramInlineQuery.d.ts +0 -0
  50. /package/dist/{main/src/types/TelegramInlineQueryType.js → types/TelegramInlineQuery.js} +0 -0
  51. /package/dist/{main/src/types → types}/TelegramInlineQueryResult.d.ts +0 -0
  52. /package/dist/{main/src/types → types}/TelegramInlineQueryResult.js +0 -0
  53. /package/dist/{main/src/types → types}/TelegramInlineQueryResultArticle.d.ts +0 -0
  54. /package/dist/{main/src/types → types}/TelegramInlineQueryResultArticle.js +0 -0
  55. /package/dist/{main/src/types → types}/TelegramInlineQueryType.d.ts +0 -0
  56. /package/dist/{main/src/types/TelegramInputMessageContent.js → types/TelegramInlineQueryType.js} +0 -0
  57. /package/dist/{main/src/types → types}/TelegramInputMessageContent.d.ts +0 -0
  58. /package/dist/{main/src/types/TelegramMessage.js → types/TelegramInputMessageContent.js} +0 -0
  59. /package/dist/{main/src/types → types}/TelegramMessage.d.ts +0 -0
  60. /package/dist/{main/src/types/TelegramMessageEntity.js → types/TelegramMessage.js} +0 -0
  61. /package/dist/{main/src/types → types}/TelegramMessageEntity.d.ts +0 -0
  62. /package/dist/{main/src/types/TelegramPhotoSize.js → types/TelegramMessageEntity.js} +0 -0
  63. /package/dist/{main/src/types → types}/TelegramPhotoSize.d.ts +0 -0
  64. /package/dist/{main/src/types/TelegramUser.js → types/TelegramPhotoSize.js} +0 -0
  65. /package/dist/{main/src/types → types}/TelegramUpdate.d.ts +0 -0
  66. /package/dist/{main/src/types → types}/TelegramUpdate.js +0 -0
  67. /package/dist/{main/src/types → types}/TelegramUser.d.ts +0 -0
  68. /package/dist/{main/src/types → types}/Update.d.ts +0 -0
  69. /package/dist/{main/src/types → types}/Update.js +0 -0
  70. /package/dist/{main/src/types → types}/WebhookCommands.d.ts +0 -0
  71. /package/dist/{main/src/types → types}/WebhookCommands.js +0 -0
  72. /package/dist/{main/src/types → types}/localhost.d.ts +0 -0
  73. /package/dist/{main/src/types → types}/localhost.js +0 -0
  74. /package/dist/{main/src/types.js → types.js} +0 -0
package/README.md CHANGED
@@ -1,16 +1,10 @@
1
1
  <h3 align="center">
2
2
  <img src="https://raw.githubusercontent.com/codebam/cf-workers-telegram-bot/master/assets/logo.png" width="100" />
3
3
  <br/>
4
- CF workers telegram bot
4
+ CF Workers Telegram Bot
5
5
  <br/>
6
6
  </h3>
7
7
 
8
- <h6 align="center">
9
- <a href="https://github.com/codebam/cf-workers-telegram-bot/wiki">Wiki</a>
10
- ·
11
- <a href="https://codebam.github.io/cf-workers-telegram-bot-docs/">Docs</a>
12
- </h6>
13
-
14
8
  <p align="center">
15
9
  <a href="https://github.com/codebam/cf-workers-telegram-bot/stargazers"> <img src="https://img.shields.io/github/stars/codebam/cf-workers-telegram-bot?style=for-the-badge&logo=starship&color=111111&logoColor=ffffff&labelColor=000000" alt="GitHub stars"/></a>
16
10
  <a href="https://github.com/codebam/cf-workers-telegram-bot/issues">
@@ -19,7 +13,7 @@ CF workers telegram bot
19
13
  <a href="https://www.npmjs.com/package/@codebam/cf-workers-telegram-bot"> <img src="https://img.shields.io/npm/v/@codebam/cf-workers-telegram-bot?style=for-the-badge&logo=npm&color=111111&logoColor=ffffff&labelColor=000000" alt="npm version" /></a>
20
14
  </p>
21
15
 
22
- ![screenshot of cf-workers-telegram-bot](/screenshot.png)
16
+ ![screenshot of cf-workers-telegram-bot](https://raw.githubusercontent.com/codebam/cf-workers-telegram-bot/master/assets/screenshot.png)
23
17
 
24
18
  ```sh
25
19
  npm i @codebam/cf-workers-telegram-bot
package/dist/api.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import { SerializableData, TelegramInlineQueryResultArticle, TelegramInlineQueryResultPhoto } from './types';
3
+ import TelegramInlineQueryResultVideo from './types/TelegramInlineQueryResultVideo';
4
+ export default class API {
5
+ static getApiUrl(botApi: string, slug: string, data: Record<string, SerializableData>): Request<unknown, CfProperties<unknown>>;
6
+ static getFile(botApi: string, data: {
7
+ file_id: string;
8
+ }, token: string): Promise<ArrayBuffer>;
9
+ static sendMessage(botApi: string, data: {
10
+ reply_to_message_id: number | string;
11
+ chat_id: number | string;
12
+ text: string;
13
+ }): Promise<Response>;
14
+ static sendVideo(botApi: string, data: {
15
+ reply_to_message_id: number | string;
16
+ chat_id: number | string;
17
+ video: string;
18
+ }): Promise<Response>;
19
+ static sendPhoto(botApi: string, data: {
20
+ reply_to_message_id: number | string;
21
+ chat_id: number | string;
22
+ photo: string;
23
+ caption: string;
24
+ }): Promise<Response>;
25
+ static answerInline(botApi: string, data: {
26
+ inline_query_id: number | string;
27
+ results: TelegramInlineQueryResultArticle[] | TelegramInlineQueryResultPhoto[] | TelegramInlineQueryResultVideo[];
28
+ }): Promise<Response>;
29
+ }
package/dist/api.js ADDED
@@ -0,0 +1,37 @@
1
+ export default class API {
2
+ static getApiUrl(botApi, slug, data) {
3
+ const request = new URL(botApi + (slug.startsWith('/') || botApi.endsWith('/') ? '' : '/') + slug);
4
+ const params = new URLSearchParams();
5
+ for (const i in data) {
6
+ params.append(i, data[i].toString());
7
+ }
8
+ return new Request(`${request}?${params}`);
9
+ }
10
+ static async getFile(botApi, data, token) {
11
+ const url = this.getApiUrl(botApi, 'getFile', data);
12
+ const response = await fetch(url);
13
+ const json = (await response.json());
14
+ const file_path = json.result.file_path;
15
+ const file_response = await fetch(`https://api.telegram.org/file/bot${token}/${file_path}`);
16
+ return await file_response.arrayBuffer();
17
+ }
18
+ static async sendMessage(botApi, data) {
19
+ const url = this.getApiUrl(botApi, 'sendMessage', data);
20
+ return await fetch(url);
21
+ }
22
+ static async sendVideo(botApi, data) {
23
+ const url = this.getApiUrl(botApi, 'sendVideo', data);
24
+ return await fetch(url);
25
+ }
26
+ static async sendPhoto(botApi, data) {
27
+ const url = this.getApiUrl(botApi, 'sendPhoto', data);
28
+ return await fetch(url);
29
+ }
30
+ static async answerInline(botApi, data) {
31
+ const url = this.getApiUrl(botApi, 'answerInlineQuery', {
32
+ inline_query_id: data.inline_query_id,
33
+ results: JSON.stringify(data.results),
34
+ });
35
+ return await fetch(url);
36
+ }
37
+ }
package/dist/ctx.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from './telegram_bot';
3
+ import { SerializableData, TelegramUpdate } from './types';
4
+ export default class TelegramExecutionContext {
5
+ bot: TelegramBot;
6
+ update: TelegramUpdate;
7
+ update_type: string;
8
+ private data;
9
+ constructor(bot: TelegramBot, update: TelegramUpdate);
10
+ getText(): string;
11
+ next(): Response;
12
+ setData(key: string, value: SerializableData): this;
13
+ deleteData(key: string): this;
14
+ getData(key: string): SerializableData;
15
+ replyVideo(video: string): Promise<Response | undefined>;
16
+ getFile(file_id: string): Promise<ArrayBuffer>;
17
+ replyPhoto(photo: string, caption?: string): Promise<Response | undefined>;
18
+ reply(message: string): Promise<Response | undefined>;
19
+ }
package/dist/ctx.js ADDED
@@ -0,0 +1,107 @@
1
+ import API from './api';
2
+ import { TelegramInlineQueryResultArticle, TelegramInlineQueryResultPhoto } from './types';
3
+ import TelegramInlineQueryResultVideo from './types/TelegramInlineQueryResultVideo';
4
+ export default class TelegramExecutionContext {
5
+ bot;
6
+ update;
7
+ update_type = '';
8
+ data = {};
9
+ constructor(bot, update) {
10
+ this.bot = bot;
11
+ this.update = update;
12
+ if (this.update.message?.photo) {
13
+ this.update_type = 'photo';
14
+ }
15
+ else if (this.update.message?.text) {
16
+ this.update_type = 'message';
17
+ }
18
+ else if (this.update.inline_query?.query) {
19
+ this.update_type = 'inline';
20
+ }
21
+ }
22
+ getText() {
23
+ return this.update.message?.text || this.update.inline_query?.query || '';
24
+ }
25
+ next() {
26
+ return new Response('ok');
27
+ }
28
+ setData(key, value) {
29
+ this.data[key] = value;
30
+ return this;
31
+ }
32
+ deleteData(key) {
33
+ delete this.data[key];
34
+ return this;
35
+ }
36
+ getData(key) {
37
+ return this.data[key];
38
+ }
39
+ async replyVideo(video) {
40
+ switch (this.update_type) {
41
+ case 'message':
42
+ return await API.sendVideo(this.bot.api.toString(), {
43
+ chat_id: this.update.message?.chat.id.toString() ?? '',
44
+ reply_to_message_id: this.update.message?.message_id.toString() ?? '',
45
+ video,
46
+ });
47
+ case 'inline':
48
+ return await API.answerInline(this.bot.api.toString(), {
49
+ inline_query_id: this.update.inline_query?.id.toString() ?? '',
50
+ results: [new TelegramInlineQueryResultVideo(video)],
51
+ });
52
+ default:
53
+ break;
54
+ }
55
+ }
56
+ async getFile(file_id) {
57
+ return await API.getFile(this.bot.api.toString(), { file_id }, this.bot.token);
58
+ }
59
+ async replyPhoto(photo, caption = '') {
60
+ switch (this.update_type) {
61
+ case 'photo':
62
+ return await API.sendPhoto(this.bot.api.toString(), {
63
+ chat_id: this.update.message?.chat.id.toString() ?? '',
64
+ reply_to_message_id: this.update.message?.message_id.toString() ?? '',
65
+ photo,
66
+ caption,
67
+ });
68
+ case 'message':
69
+ return await API.sendPhoto(this.bot.api.toString(), {
70
+ chat_id: this.update.message?.chat.id.toString() ?? '',
71
+ reply_to_message_id: this.update.message?.message_id.toString() ?? '',
72
+ photo,
73
+ caption,
74
+ });
75
+ case 'inline':
76
+ return await API.answerInline(this.bot.api.toString(), {
77
+ inline_query_id: this.update.inline_query?.id.toString() ?? '',
78
+ results: [new TelegramInlineQueryResultPhoto(photo)],
79
+ });
80
+ default:
81
+ break;
82
+ }
83
+ }
84
+ async reply(message) {
85
+ switch (this.update_type) {
86
+ case 'message':
87
+ return await API.sendMessage(this.bot.api.toString(), {
88
+ chat_id: this.update.message?.chat.id.toString() ?? '',
89
+ reply_to_message_id: this.update.message?.message_id.toString() ?? '',
90
+ text: message,
91
+ });
92
+ case 'photo':
93
+ return await API.sendMessage(this.bot.api.toString(), {
94
+ chat_id: this.update.message?.chat.id.toString() ?? '',
95
+ reply_to_message_id: this.update.message?.message_id.toString() ?? '',
96
+ text: message,
97
+ });
98
+ case 'inline':
99
+ return await API.answerInline(this.bot.api.toString(), {
100
+ inline_query_id: this.update.inline_query?.id.toString() ?? '',
101
+ results: [new TelegramInlineQueryResultArticle(message)],
102
+ });
103
+ default:
104
+ break;
105
+ }
106
+ }
107
+ }
package/dist/main.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import ExecutionContext from './ctx';
2
+ import TelegramBot from './telegram_bot';
3
+ import * as Types from './types';
4
+ export { TelegramBot, Types, ExecutionContext };
package/dist/main.js ADDED
@@ -0,0 +1,4 @@
1
+ import ExecutionContext from './ctx';
2
+ import TelegramBot from './telegram_bot';
3
+ import * as Types from './types';
4
+ export { TelegramBot, Types, ExecutionContext };
@@ -1,20 +1,16 @@
1
1
  /// <reference types="@cloudflare/workers-types" />
2
2
  import { TelegramUpdate } from './types';
3
+ import TelegramExecutionContext from './ctx';
4
+ import Webhook from './webhook';
3
5
  export default class TelegramBot {
4
6
  token: string;
5
7
  webhook: Webhook;
6
- update: TelegramUpdate;
7
8
  api: URL;
9
+ update: TelegramUpdate;
8
10
  update_type: string;
11
+ commands: Record<string, (ctx: TelegramExecutionContext) => Promise<Response>>;
12
+ currentContext: TelegramExecutionContext;
9
13
  constructor(token: string);
10
- on(event: string, callback: () => Promise<Response>): this;
14
+ on(event: string, callback: (ctx: TelegramExecutionContext) => Promise<Response>): this;
11
15
  handle(request: Request): Promise<Response>;
12
- reply(message: string): Promise<void>;
13
- }
14
- declare class Webhook {
15
- api: URL;
16
- webhook: URL;
17
- constructor(token: string, request: Request);
18
- set(): Promise<Response>;
19
16
  }
20
- export {};
@@ -0,0 +1,73 @@
1
+ import { TelegramUpdate } from './types';
2
+ import TelegramExecutionContext from './ctx';
3
+ import Webhook from './webhook';
4
+ export default class TelegramBot {
5
+ token;
6
+ webhook;
7
+ api;
8
+ update;
9
+ update_type;
10
+ commands = {};
11
+ currentContext;
12
+ constructor(token) {
13
+ this.token = token;
14
+ this.webhook = new Webhook('', new Request('http://127.0.0.1'));
15
+ this.api = new URL('https://api.telegram.org/bot' + token);
16
+ this.update = new TelegramUpdate({});
17
+ this.update_type = '';
18
+ }
19
+ on(event, callback) {
20
+ if (event !== 'on') {
21
+ this.commands[event] = callback;
22
+ }
23
+ return this;
24
+ }
25
+ async handle(request) {
26
+ this.webhook = new Webhook(this.token, request);
27
+ if (request.method === 'POST') {
28
+ this.update = await request.json();
29
+ }
30
+ else {
31
+ this.update = new TelegramUpdate({});
32
+ }
33
+ const url = new URL(request.url);
34
+ if (`/${this.token}` === url.pathname) {
35
+ switch (url.searchParams.get('command')) {
36
+ case 'set':
37
+ return this.webhook.set();
38
+ default:
39
+ break;
40
+ }
41
+ console.log(this.update);
42
+ let command = 'default';
43
+ let args = [];
44
+ const ctx = new TelegramExecutionContext(this, this.update);
45
+ this.currentContext = ctx;
46
+ switch (ctx.update_type) {
47
+ case 'message': {
48
+ args = this.update.message?.text?.split(' ') ?? [];
49
+ break;
50
+ }
51
+ case 'inline': {
52
+ args = this.update.inline_query?.query.split(' ') ?? [];
53
+ break;
54
+ }
55
+ case 'photo': {
56
+ command = ':photo';
57
+ break;
58
+ }
59
+ default:
60
+ break;
61
+ }
62
+ if (args.at(0)?.startsWith('/')) {
63
+ command = args.at(0)?.slice(1) ?? 'default';
64
+ }
65
+ this.commands['any']?.(ctx);
66
+ if (!this.commands[command]) {
67
+ command = 'default';
68
+ }
69
+ return await this.commands[command]?.(ctx);
70
+ }
71
+ return new Response('ok');
72
+ }
73
+ }
@@ -0,0 +1,2 @@
1
+ type SerializableData = number | string | boolean;
2
+ export default SerializableData;
@@ -1,4 +1,5 @@
1
1
  import TelegramInlineQueryResult from './TelegramInlineQueryResult';
2
+ import TelegramInputMessageContent from './TelegramInputMessageContent';
2
3
  export default class TelegramInlineQueryResultPhoto extends TelegramInlineQueryResult {
3
4
  photo_url: string;
4
5
  thumb_url: string;
@@ -9,5 +10,6 @@ export default class TelegramInlineQueryResultPhoto extends TelegramInlineQueryR
9
10
  caption?: string;
10
11
  parse_mode?: string;
11
12
  caption_entities?: string;
13
+ input_message_content?: TelegramInputMessageContent;
12
14
  constructor(photo: string);
13
15
  }
@@ -10,7 +10,7 @@ export default class TelegramInlineQueryResultPhoto extends TelegramInlineQueryR
10
10
  parse_mode;
11
11
  caption_entities;
12
12
  // reply_markup?: TelegramInlineKeyboardMarkup;
13
- // input_message_content?: TelegramInputMessageContent;
13
+ input_message_content;
14
14
  constructor(photo) {
15
15
  super('photo');
16
16
  this.photo_url = photo;
@@ -0,0 +1,15 @@
1
+ import TelegramInlineQueryResult from './TelegramInlineQueryResult';
2
+ import TelegramInputMessageContent from './TelegramInputMessageContent';
3
+ export default class TelegramInlineQueryResultVideo extends TelegramInlineQueryResult {
4
+ video_url: string;
5
+ thumb_url: string;
6
+ photo_width?: number;
7
+ photo_height?: number;
8
+ title?: string;
9
+ description?: string;
10
+ caption?: string;
11
+ parse_mode?: string;
12
+ caption_entities?: string;
13
+ input_message_content?: TelegramInputMessageContent;
14
+ constructor(video: string);
15
+ }
@@ -0,0 +1,19 @@
1
+ import TelegramInlineQueryResult from './TelegramInlineQueryResult';
2
+ export default class TelegramInlineQueryResultVideo extends TelegramInlineQueryResult {
3
+ video_url;
4
+ thumb_url;
5
+ photo_width;
6
+ photo_height;
7
+ title;
8
+ description;
9
+ caption;
10
+ parse_mode;
11
+ caption_entities;
12
+ // reply_markup?: TelegramInlineKeyboardMarkup;
13
+ input_message_content;
14
+ constructor(video) {
15
+ super('video');
16
+ this.video_url = video;
17
+ this.thumb_url = video;
18
+ }
19
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -23,4 +23,5 @@ import TelegramInlineQueryResultArticle from './types/TelegramInlineQueryResultA
23
23
  import DDGQueryResponse from './types/DDGQueryResponse';
24
24
  import ChatPermissions from './types/ChatPermissions';
25
25
  import Kanye from './types/Kanye';
26
- export { TelegramCommand, Kv, localhost, WebhookCommands, Joke, Bored, Balance, TelegramFrom, TelegramChat, TelegramUser, TelegramMessageEntity, TelegramPhotoSize, TelegramMessage, TelegramInputMessageContent, TelegramInlineQuery, Update, TelegramUpdate, PartialTelegramUpdate, TelegramInlineQueryType, TelegramInlineQueryResult, TelegramInlineQueryResultPhoto, TelegramInlineQueryResultArticle, DDGQueryResponse, ChatPermissions, Kanye, };
26
+ import SerializableData from './types/SerializableData';
27
+ export { TelegramCommand, Kv, localhost, WebhookCommands, Joke, Bored, Balance, TelegramFrom, TelegramChat, TelegramUser, TelegramMessageEntity, TelegramPhotoSize, TelegramMessage, TelegramInputMessageContent, TelegramInlineQuery, Update, TelegramUpdate, PartialTelegramUpdate, TelegramInlineQueryType, TelegramInlineQueryResult, TelegramInlineQueryResultPhoto, TelegramInlineQueryResultArticle, DDGQueryResponse, ChatPermissions, Kanye, SerializableData, };
@@ -0,0 +1,7 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ export default class Webhook {
3
+ api: URL;
4
+ webhook: URL;
5
+ constructor(token: string, request: Request);
6
+ set(): Promise<Response>;
7
+ }
@@ -0,0 +1,17 @@
1
+ export default class Webhook {
2
+ api;
3
+ webhook;
4
+ constructor(token, request) {
5
+ this.api = new URL('https://api.telegram.org/bot' + token);
6
+ this.webhook = new URL(new URL(request.url).origin + `/${token}`);
7
+ }
8
+ async set() {
9
+ const url = new URL(`${this.api.origin}${this.api.pathname}/setWebhook`);
10
+ const params = url.searchParams;
11
+ params.append('url', this.webhook.toString());
12
+ params.append('max_connections', '100');
13
+ params.append('allowed_updates', JSON.stringify(['message', 'inline_query']));
14
+ params.append('drop_pending_updates', 'true');
15
+ return await fetch(`${url}?${params}`);
16
+ }
17
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codebam/cf-workers-telegram-bot",
3
- "version": "7.6.0",
3
+ "version": "7.8.0",
4
4
  "description": "serverless telegram bot on cf workers",
5
5
  "main": "./dist/main/src/main.js",
6
6
  "module": "./dist/main/src/main.js",
@@ -43,5 +43,5 @@
43
43
  "typescript-eslint": "^7.8.0",
44
44
  "vitest": "^1.6.0"
45
45
  },
46
- "gitHead": "d2c50965ef1d04fb62c9683f4418a7f4931ded93"
46
+ "gitHead": "f70461a7e08ddedf437e1ee761c0c40c6184f3f2"
47
47
  }
package/LICENSE_MIT DELETED
@@ -1,21 +0,0 @@
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.
@@ -1,4 +0,0 @@
1
- import TelegramBot from './telegram_bot';
2
- import * as Types from './types';
3
- import worker from '../../worker/src/worker';
4
- export { TelegramBot, Types, worker };
@@ -1,4 +0,0 @@
1
- import TelegramBot from './telegram_bot';
2
- import * as Types from './types';
3
- import worker from '../../worker/src/worker';
4
- export { TelegramBot, Types, worker };
@@ -1,116 +0,0 @@
1
- import { TelegramInlineQueryResultArticle, TelegramUpdate } from './types';
2
- export default class TelegramBot {
3
- token;
4
- webhook;
5
- update;
6
- api;
7
- update_type;
8
- constructor(token) {
9
- this.token = token;
10
- this.webhook = new Webhook('', new Request('http://127.0.0.1'));
11
- this.update = new TelegramUpdate({});
12
- this.api = new URL('https://api.telegram.org/bot' + token);
13
- this.update_type = '';
14
- }
15
- on(event, callback) {
16
- if (event !== 'on') {
17
- // eslint-disable-next-line
18
- // @ts-ignore TS7053
19
- this[event] = callback;
20
- }
21
- return this;
22
- }
23
- async handle(request) {
24
- this.webhook = new Webhook(this.token, request);
25
- if (request.method === 'POST') {
26
- this.update = await request.json();
27
- }
28
- const url = new URL(request.url);
29
- if (`/${this.token}` === url.pathname) {
30
- switch (url.searchParams.get('command')) {
31
- case 'set':
32
- return this.webhook.set();
33
- default:
34
- break;
35
- }
36
- console.log(this.update);
37
- if (this.update.message?.text) {
38
- this.update_type = 'message';
39
- }
40
- else if (this.update.inline_query?.query) {
41
- this.update_type = 'inline';
42
- }
43
- let command = 'default';
44
- let args = [];
45
- switch (this.update_type) {
46
- case 'message': {
47
- // @ts-expect-error already checked above
48
- args = this.update.message.text.split(' ');
49
- break;
50
- }
51
- case 'inline': {
52
- // @ts-expect-error already checked above
53
- args = this.update.inline_query.query.split(' ');
54
- break;
55
- }
56
- default:
57
- break;
58
- }
59
- if (args.at(0)?.startsWith('/')) {
60
- // @ts-expect-error already checked above
61
- command = args.at(0).slice(1);
62
- }
63
- // eslint-disable-next-line
64
- // @ts-ignore
65
- if (!this[command] || command === 'on') {
66
- command = 'default';
67
- }
68
- // eslint-disable-next-line
69
- // @ts-ignore
70
- return this[command]?.();
71
- }
72
- return new Response('ok');
73
- }
74
- async reply(message) {
75
- switch (this.update_type) {
76
- case 'message': {
77
- const request = new URL(this.api + '/sendMessage');
78
- const params = new URLSearchParams();
79
- params.append('chat_id', this.update.message?.chat.id.toString() ?? '');
80
- params.append('reply_to_message_id', this.update.message?.message_id.toString() ?? '');
81
- params.append('text', message);
82
- console.log(`${request}?${params}`);
83
- await fetch(`${request}?${params}`);
84
- break;
85
- }
86
- case 'inline': {
87
- const inline_request = new URL(this.api + '/answerInlineQuery');
88
- const inline_params = new URLSearchParams();
89
- inline_params.append('inline_query_id', this.update.inline_query?.id.toString() ?? '');
90
- inline_params.append('results', JSON.stringify([new TelegramInlineQueryResultArticle(message)]));
91
- console.log(`${inline_request}?${inline_params}`);
92
- await fetch(`${inline_request}?${inline_params}`);
93
- break;
94
- }
95
- default:
96
- break;
97
- }
98
- }
99
- }
100
- class Webhook {
101
- api;
102
- webhook;
103
- constructor(token, request) {
104
- this.api = new URL('https://api.telegram.org/bot' + token);
105
- this.webhook = new URL(new URL(request.url).origin + `/${token}`);
106
- }
107
- async set() {
108
- const url = new URL(`${this.api.origin}${this.api.pathname}/setWebhook`);
109
- const params = url.searchParams;
110
- params.append('url', this.webhook.toString());
111
- params.append('max_connections', '100');
112
- params.append('allowed_updates', JSON.stringify(['message', 'inline_query']));
113
- params.append('drop_pending_updates', 'true');
114
- return await fetch(`${url}?${params}`);
115
- }
116
- }
@@ -1,18 +0,0 @@
1
- /// <reference types="@cloudflare/workers-types" />
2
- export interface Environment {
3
- SECRET_TELEGRAM_API_TOKEN: string;
4
- KV_GET_SET: KVNamespace;
5
- KV_UID_DATA: KVNamespace;
6
- SECRET_TELEGRAM_API_TOKEN2: string;
7
- SECRET_TELEGRAM_API_TOKEN3: string;
8
- SECRET_TELEGRAM_API_TOKEN4: string;
9
- SECRET_TELEGRAM_API_TOKEN5: string;
10
- AI: Ai;
11
- DB: D1Database;
12
- R2: R2Bucket;
13
- CHAT_MODEL: string;
14
- }
15
- declare const _default: {
16
- fetch: (request: Request, env: Environment, ctx: ExecutionContext) => Promise<Response>;
17
- };
18
- export default _default;
@@ -1,81 +0,0 @@
1
- import TelegramBot from '../../main/src/telegram_bot';
2
- export default {
3
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
4
- fetch: async (request, env, ctx) => {
5
- const bot = new TelegramBot(env.SECRET_TELEGRAM_API_TOKEN);
6
- await bot
7
- .on('default', async function () {
8
- switch (bot.update_type) {
9
- case 'message': {
10
- const messages = [
11
- { role: 'system', content: 'You are a friendly assistant' },
12
- {
13
- role: 'user',
14
- content: bot.update.message?.text?.toString() ?? '',
15
- },
16
- ];
17
- const response = await env.AI.run('@cf/meta/llama-3-8b-instruct', { messages });
18
- if ('response' in response) {
19
- await bot.reply(response.response ?? '');
20
- }
21
- break;
22
- }
23
- case 'inline': {
24
- const inline_messages = [
25
- { role: 'system', content: 'You are a friendly assistant' },
26
- {
27
- role: 'user',
28
- content: bot.update.inline_query?.query.toString() ?? '',
29
- },
30
- ];
31
- const inline_response = await env.AI.run('@cf/meta/llama-3-8b-instruct', { messages: inline_messages, max_tokens: 50 });
32
- if ('response' in inline_response) {
33
- await bot.reply(inline_response.response ?? '');
34
- }
35
- break;
36
- }
37
- default:
38
- break;
39
- }
40
- return new Response('ok');
41
- })
42
- .handle(request.clone());
43
- const bot2 = new TelegramBot(env.SECRET_TELEGRAM_API_TOKEN2);
44
- await bot2
45
- .on('default', async function () {
46
- switch (bot2.update_type) {
47
- case 'message': {
48
- await bot2.reply('https://duckduckgo.com/?q=' + encodeURIComponent(bot.update.message?.text?.toString() ?? ''));
49
- break;
50
- }
51
- case 'inline': {
52
- await bot2.reply('https://duckduckgo.com/?q=' + encodeURIComponent(bot.update.inline_query?.query ?? ''));
53
- break;
54
- }
55
- default:
56
- break;
57
- }
58
- return new Response('ok');
59
- })
60
- .handle(request.clone());
61
- const bot3 = new TelegramBot(env.SECRET_TELEGRAM_API_TOKEN3);
62
- await bot3
63
- .on('default', async function () {
64
- switch (bot3.update_type) {
65
- case 'inline': {
66
- const translated_text = await fetch('https://clients5.google.com/translate_a/t?client=at&sl=auto&tl=en&q=' +
67
- encodeURIComponent(bot3.update.inline_query?.query.toString() ?? ''))
68
- .then((r) => r.json())
69
- .then((json) => json[0].slice(0, -1).join(' '));
70
- await bot3.reply(translated_text ?? '');
71
- break;
72
- }
73
- default:
74
- break;
75
- }
76
- return new Response('ok');
77
- })
78
- .handle(request.clone());
79
- return new Response('ok');
80
- },
81
- };
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes