@codebam/cf-workers-telegram-bot 5.16.0 → 6.1.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 (107) hide show
  1. package/dist/main/src/bot_api.d.ts +3 -3
  2. package/dist/main/src/commands/bored.d.ts +5 -0
  3. package/dist/main/src/commands/bored.js +8 -0
  4. package/dist/main/src/commands/clear.d.ts +5 -0
  5. package/dist/main/src/commands/clear.js +14 -0
  6. package/dist/main/src/commands/code.d.ts +5 -0
  7. package/dist/main/src/commands/code.js +4 -0
  8. package/dist/main/src/commands/commandlist.d.ts +5 -0
  9. package/dist/main/src/commands/commandlist.js +1 -0
  10. package/dist/main/src/commands/dog.d.ts +5 -0
  11. package/dist/main/src/commands/dog.js +7 -0
  12. package/dist/main/src/commands/duckduckgo.d.ts +5 -0
  13. package/dist/main/src/commands/duckduckgo.js +42 -0
  14. package/dist/main/src/commands/epoch.d.ts +5 -0
  15. package/dist/main/src/commands/epoch.js +4 -0
  16. package/dist/main/src/commands/getchatinfo.d.ts +5 -0
  17. package/dist/main/src/commands/getchatinfo.js +2 -0
  18. package/dist/main/src/commands/image.d.ts +5 -0
  19. package/dist/main/src/commands/image.js +19 -0
  20. package/dist/main/src/commands/joke.d.ts +5 -0
  21. package/dist/main/src/commands/joke.js +8 -0
  22. package/dist/main/src/commands/kanye.d.ts +5 -0
  23. package/dist/main/src/commands/kanye.js +8 -0
  24. package/dist/main/src/commands/ping.d.ts +5 -0
  25. package/dist/main/src/commands/ping.js +1 -0
  26. package/dist/main/src/commands/question.d.ts +5 -0
  27. package/dist/main/src/commands/question.js +74 -0
  28. package/dist/main/src/commands/roll.d.ts +5 -0
  29. package/dist/main/src/commands/roll.js +6 -0
  30. package/dist/main/src/commands/sean.d.ts +5 -0
  31. package/dist/main/src/commands/sean.js +76 -0
  32. package/dist/main/src/commands/toss.d.ts +5 -0
  33. package/dist/main/src/commands/toss.js +1 -0
  34. package/dist/main/src/commands/translate.d.ts +5 -0
  35. package/dist/main/src/commands/translate.js +26 -0
  36. package/dist/main/src/handler.d.ts +2 -2
  37. package/dist/main/src/handler.js +5 -7
  38. package/dist/main/src/libs.js +6 -11
  39. package/dist/main/src/main.d.ts +11 -11
  40. package/dist/main/src/main.js +11 -11
  41. package/dist/main/src/telegram_api.d.ts +3 -3
  42. package/dist/main/src/telegram_api.js +20 -27
  43. package/dist/main/src/telegram_bot.d.ts +20 -21
  44. package/dist/main/src/telegram_bot.js +52 -341
  45. package/dist/main/src/telegram_commands.d.ts +1 -1
  46. package/dist/main/src/telegram_commands.js +16 -16
  47. package/dist/main/src/telegram_webhook.d.ts +2 -2
  48. package/dist/main/src/telegram_webhook.js +5 -6
  49. package/dist/main/src/types/Balance.d.ts +6 -0
  50. package/dist/main/src/types/Balance.js +1 -0
  51. package/dist/main/src/types/Bored.d.ts +10 -0
  52. package/dist/main/src/types/Bored.js +1 -0
  53. package/dist/main/src/types/Command.d.ts +5 -0
  54. package/dist/main/src/types/Command.js +1 -0
  55. package/dist/main/src/types/Commands.d.ts +3 -0
  56. package/dist/main/src/types/Commands.js +1 -0
  57. package/dist/main/src/types/Config.d.ts +20 -0
  58. package/dist/main/src/types/Config.js +33 -0
  59. package/dist/main/src/types/DDGQueryResponse.d.ts +12 -0
  60. package/dist/main/src/types/DDGQueryResponse.js +1 -0
  61. package/dist/main/src/types/Joke.d.ts +20 -0
  62. package/dist/main/src/types/Joke.js +1 -0
  63. package/dist/main/src/types/Kv.d.ts +3 -0
  64. package/dist/main/src/types/Kv.js +1 -0
  65. package/dist/main/src/types/PartialTelegramUpdate.d.ts +11 -0
  66. package/dist/main/src/types/PartialTelegramUpdate.js +1 -0
  67. package/dist/main/src/types/TelegramChat.d.ts +21 -0
  68. package/dist/main/src/types/TelegramChat.js +1 -0
  69. package/dist/main/src/types/TelegramCommand.d.ts +5 -0
  70. package/dist/main/src/types/TelegramCommand.js +1 -0
  71. package/dist/main/src/types/TelegramFrom.d.ts +8 -0
  72. package/dist/main/src/types/TelegramFrom.js +1 -0
  73. package/dist/main/src/types/TelegramInlineQuery.d.ts +9 -0
  74. package/dist/main/src/types/TelegramInlineQuery.js +1 -0
  75. package/dist/main/src/types/TelegramInlineQueryResult.d.ts +6 -0
  76. package/dist/main/src/types/TelegramInlineQueryResult.js +8 -0
  77. package/dist/main/src/types/TelegramInlineQueryResultArticle.d.ts +8 -0
  78. package/dist/main/src/types/TelegramInlineQueryResultArticle.js +15 -0
  79. package/dist/main/src/types/TelegramInlineQueryResultPhoto.d.ts +13 -0
  80. package/dist/main/src/types/TelegramInlineQueryResultPhoto.js +19 -0
  81. package/dist/main/src/types/TelegramInlineQueryType.d.ts +2 -0
  82. package/dist/main/src/types/TelegramInlineQueryType.js +1 -0
  83. package/dist/main/src/types/TelegramInputMessageContent.d.ts +5 -0
  84. package/dist/main/src/types/TelegramInputMessageContent.js +1 -0
  85. package/dist/main/src/types/TelegramMessage.d.ts +42 -0
  86. package/dist/main/src/types/TelegramMessage.js +1 -0
  87. package/dist/main/src/types/TelegramMessageEntity.d.ts +10 -0
  88. package/dist/main/src/types/TelegramMessageEntity.js +1 -0
  89. package/dist/main/src/types/TelegramPhotoSize.d.ts +8 -0
  90. package/dist/main/src/types/TelegramPhotoSize.js +1 -0
  91. package/dist/main/src/types/TelegramUpdate.d.ts +13 -0
  92. package/dist/main/src/types/TelegramUpdate.js +36 -0
  93. package/dist/main/src/types/TelegramUser.d.ts +12 -0
  94. package/dist/main/src/types/TelegramUser.js +1 -0
  95. package/dist/main/src/types/Update.d.ts +3 -0
  96. package/dist/main/src/types/Update.js +2 -0
  97. package/dist/main/src/types/WebhookCommands.d.ts +4 -0
  98. package/dist/main/src/types/WebhookCommands.js +2 -0
  99. package/dist/main/src/types/localhost.d.ts +3 -0
  100. package/dist/main/src/types/localhost.js +1 -0
  101. package/dist/main/src/types.d.ts +28 -215
  102. package/dist/main/src/types.js +10 -113
  103. package/dist/main/src/webhook.d.ts +1 -1
  104. package/dist/main/src/webhook.js +3 -4
  105. package/dist/worker/src/worker.d.ts +1 -1
  106. package/dist/worker/src/worker.js +37 -37
  107. package/package.json +4 -7
@@ -1,13 +1,11 @@
1
- import BotApi from "./bot_api";
2
- import { addSearchParams, log } from "./libs";
1
+ import BotApi from './bot_api';
2
+ import { addSearchParams, log } from './libs';
3
3
  export default class TelegramApi extends BotApi {
4
4
  constructor(commands, webhook, handler) {
5
5
  super({ commands, webhook, handler });
6
6
  }
7
7
  inlineQueryUpdate = async (update) => this.executeInlineCommand(update);
8
- messageUpdate = async (update) => typeof update.message?.text === "string"
9
- ? this.executeCommand(update).then(async () => this.greetUsers(update))
10
- : this.updates.default;
8
+ messageUpdate = async (update) => typeof update.message?.text === 'string' ? this.executeCommand(update).then(async () => this.greetUsers(update)) : this.updates.default;
11
9
  updates = {
12
10
  inline_query: this.inlineQueryUpdate,
13
11
  message: this.messageUpdate,
@@ -17,7 +15,7 @@ export default class TelegramApi extends BotApi {
17
15
  console.log({ update });
18
16
  if (update) {
19
17
  if (update.inline_query) {
20
- if (update.inline_query.query !== "") {
18
+ if (update.inline_query.query !== '') {
21
19
  return this.updates.inline_query(update);
22
20
  }
23
21
  }
@@ -33,33 +31,28 @@ export default class TelegramApi extends BotApi {
33
31
  greetUsers = async (update) => update.message?.new_chat_members
34
32
  ? this.sendMessage(update.message.chat.id, `Welcome to ${update.message.chat.title}, ${update.message.from.username}`)
35
33
  : this.updates.default;
36
- getCommand = (args) => args[0]?.split("@")[0];
34
+ getCommand = (args) => args[0]?.split('@')[0];
37
35
  // run command passed from executeCommand
38
36
  _executeCommand = async (update, text, args = []) => log({ execute: { text, args } })
39
37
  ? ((text_args) => ((command) => this.commands[command]
40
38
  ? this.commands[command]?.(this, update, [...text_args, ...args])
41
39
  : log({
42
40
  error: `command '${command}' does not exist, using default`,
43
- }) &&
44
- this.commands["default"]?.(this, update, [
45
- ...text_args,
46
- ...args,
47
- ]))(
41
+ }) && this.commands['default']?.(this, update, [...text_args, ...args]))(
48
42
  // run the command
49
43
  this.getCommand(text_args)))(
50
44
  // get the command to run
51
45
  text
52
46
  .trimStart()
53
- .replace(/^([^\s]*\s)\s*/gm, "$1")
54
- .split(" "))
47
+ .replace(/^([^\s]*\s)\s*/gm, '$1')
48
+ .split(' '))
55
49
  : this.updates.default;
56
50
  // execute the inline custom bot commands from bot configurations
57
- executeInlineCommand = async (update) => this._executeCommand(update, update.inline_query?.query ?? "").then(async (command_response) => command_response
58
- ? this._executeCommand(update, "inline", update.inline_query?.query.trimStart().split(" ")).then((_command_response) => _command_response)
51
+ executeInlineCommand = async (update) => this._executeCommand(update, update.inline_query?.query ?? '').then(async (command_response) => command_response
52
+ ? this._executeCommand(update, 'inline', update.inline_query?.query.trimStart().split(' ')).then((_command_response) => _command_response)
59
53
  : this.updates.default);
60
54
  // execute the custom bot commands from bot configurations
61
- executeCommand = async (update) => this._executeCommand(update, update.message?.text ?? "") ??
62
- this.updates.default;
55
+ executeCommand = async (update) => this._executeCommand(update, update.message?.text ?? '') ?? this.updates.default;
63
56
  // trigger answerInlineQuery command of BotAPI
64
57
  answerInlineQuery = async (inline_query_id, results, cache_time = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.origin}${this.webhook.api.pathname}/answerInlineQuery`), {
65
58
  inline_query_id: inline_query_id.toString(),
@@ -73,7 +66,7 @@ export default class TelegramApi extends BotApi {
73
66
  text,
74
67
  }).href));
75
68
  // trigger sendMessage command of BotAPI
76
- 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.origin}${this.webhook.api.pathname}/sendMessage`), {
69
+ 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.origin}${this.webhook.api.pathname}/sendMessage`), {
77
70
  chat_id: chat_id.toString(),
78
71
  text,
79
72
  parse_mode: parse_mode,
@@ -89,21 +82,21 @@ export default class TelegramApi extends BotApi {
89
82
  disable_notification: disable_notification.toString(),
90
83
  }).href));
91
84
  // trigger sendPhoto command of BotAPI
92
- sendPhotoRaw = async (chat_id, photo, caption = "", parse_mode = "", disable_notification = false, reply_to_message_id = 0) => {
85
+ sendPhotoRaw = async (chat_id, photo, caption = '', parse_mode = '', disable_notification = false, reply_to_message_id = 0) => {
93
86
  const formdata = new FormData();
94
- formdata.set("file", photo);
87
+ formdata.set('file', photo);
95
88
  return fetch(log(addSearchParams(new URL(`${this.webhook.api.origin}${this.webhook.api.pathname}/sendPhoto`), {
96
89
  chat_id: chat_id.toString(),
97
90
  caption,
98
91
  parse_mode,
99
92
  disable_notification: disable_notification.toString(),
100
93
  reply_to_message_id: reply_to_message_id.toString(),
101
- }).href), { method: "POST", body: formdata })
94
+ }).href), { method: 'POST', body: formdata })
102
95
  .then((resp) => resp.text())
103
96
  .then(log);
104
97
  };
105
98
  // trigger sendPhoto command of BotAPI
106
- sendPhoto = async (chat_id, photo, caption = "", parse_mode = "", disable_notification = false, reply_to_message_id = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.origin}${this.webhook.api.pathname}/sendPhoto`), {
99
+ sendPhoto = async (chat_id, photo, caption = '', parse_mode = '', disable_notification = false, reply_to_message_id = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.origin}${this.webhook.api.pathname}/sendPhoto`), {
107
100
  chat_id: chat_id.toString(),
108
101
  photo,
109
102
  caption,
@@ -112,7 +105,7 @@ export default class TelegramApi extends BotApi {
112
105
  reply_to_message_id: reply_to_message_id.toString(),
113
106
  }).href));
114
107
  // trigger sendVideo command of BotAPI
115
- 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.origin}${this.webhook.api.pathname}/sendVideo`), {
108
+ 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.origin}${this.webhook.api.pathname}/sendVideo`), {
116
109
  chat_id: chat_id.toString(),
117
110
  video: JSON.stringify(video),
118
111
  duration: duration.toString(),
@@ -126,7 +119,7 @@ export default class TelegramApi extends BotApi {
126
119
  reply_to_message_id: reply_to_message_id.toString(),
127
120
  }).href));
128
121
  // trigger sendAnimation command of BotAPI
129
- 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.origin}${this.webhook.api.pathname}/sendAnimation`), {
122
+ 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.origin}${this.webhook.api.pathname}/sendAnimation`), {
130
123
  chat_id: chat_id.toString(),
131
124
  animation: JSON.stringify(animation),
132
125
  duration: duration.toString(),
@@ -148,7 +141,7 @@ export default class TelegramApi extends BotApi {
148
141
  reply_to_message_id: reply_to_message_id.toString(),
149
142
  }).href));
150
143
  // trigger senPoll command of BotAPI
151
- 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.origin}${this.webhook.api.pathname}/sendPoll`), {
144
+ 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.origin}${this.webhook.api.pathname}/sendPoll`), {
152
145
  chat_id: chat_id.toString(),
153
146
  question,
154
147
  options: options.toString(),
@@ -165,7 +158,7 @@ export default class TelegramApi extends BotApi {
165
158
  reply_to_message_id: reply_to_message_id.toString(),
166
159
  }).href));
167
160
  // trigger senDice command of BotAPI
168
- sendDice = async (chat_id, emoji = "", disable_notification = false, reply_to_message_id = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.origin}${this.webhook.api.pathname}/sendDice`), {
161
+ sendDice = async (chat_id, emoji = '', disable_notification = false, reply_to_message_id = 0) => fetch(log(addSearchParams(new URL(`${this.webhook.api.origin}${this.webhook.api.pathname}/sendDice`), {
169
162
  chat_id: chat_id.toString(),
170
163
  emoji,
171
164
  disable_notification: disable_notification.toString(),
@@ -1,32 +1,31 @@
1
1
  /// <reference types="@cloudflare/workers-types" />
2
- import TelegramApi from "./telegram_api";
3
- import { TelegramUpdate, Config, Kv } from "./types";
2
+ import TelegramApi from './telegram_api';
3
+ import { Config, Kv, TelegramUpdate } from './types';
4
4
  export default class TelegramBot extends TelegramApi {
5
+ translate: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
6
+ clear: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
7
+ image: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
8
+ question: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
9
+ sean: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
10
+ code: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
11
+ duckduckgo: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
12
+ kanye: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
13
+ joke: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
14
+ dog: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
15
+ bored: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
16
+ epoch: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
17
+ roll: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
18
+ commandList: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
19
+ toss: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
20
+ ping: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
21
+ getChatInfo: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
5
22
  url: URL;
6
23
  kv: Kv;
7
24
  get_set: KVNamespace;
8
- ai: any;
25
+ ai: Ai;
9
26
  db: D1Database;
10
27
  r2: R2Bucket;
11
28
  bot_name: string;
12
29
  chat_model: string;
13
30
  constructor(config: Config);
14
- translate: (update: TelegramUpdate, args: string[]) => Promise<Response>;
15
- clear: (update: TelegramUpdate) => Promise<Response>;
16
- image: (update: TelegramUpdate, args: string[]) => Promise<Response>;
17
- question: (update: TelegramUpdate, args: string[]) => Promise<Response>;
18
- sean: (update: TelegramUpdate, args: string[]) => Promise<Response>;
19
- code: (update: TelegramUpdate) => Promise<Response>;
20
- duckduckgo: (update: TelegramUpdate, args: string[]) => Promise<Response>;
21
- kanye: (update: TelegramUpdate) => Promise<Response>;
22
- joke: (update: TelegramUpdate) => Promise<Response>;
23
- dog: (update: TelegramUpdate) => Promise<Response>;
24
- bored: (update: TelegramUpdate) => Promise<Response>;
25
- epoch: (update: TelegramUpdate) => Promise<Response>;
26
- _average: (numbers: number[]) => number;
27
- roll: (update: TelegramUpdate, args: string[]) => Promise<Response>;
28
- commandList: (update: TelegramUpdate) => Promise<Response>;
29
- toss: (update: TelegramUpdate) => Promise<Response>;
30
- ping: (update: TelegramUpdate, args: string[]) => Promise<Response>;
31
- getChatInfo: (update: TelegramUpdate) => Promise<Response>;
32
31
  }
@@ -1,12 +1,42 @@
1
- import { preTagString, prettyJSON, addSearchParams, responseToJSON, } from "./libs";
2
- import TelegramApi from "./telegram_api";
3
- import { TelegramInlineQueryResultArticle, TelegramInlineQueryResultPhoto, } from "./types";
4
- import { Ai } from "@cloudflare/ai";
1
+ import TelegramApi from './telegram_api';
2
+ import translate from './commands/translate';
3
+ import clear from './commands/clear';
4
+ import image from './commands/image';
5
+ import question from './commands/question';
6
+ import sean from './commands/sean';
7
+ import code from './commands/code';
8
+ import duckduckgo from './commands/duckduckgo';
9
+ import kanye from './commands/kanye';
10
+ import joke from './commands/joke';
11
+ import dog from './commands/dog';
12
+ import bored from './commands/bored';
13
+ import epoch from './commands/epoch';
14
+ import roll from './commands/roll';
15
+ import commandlist from './commands/commandlist';
16
+ import toss from './commands/toss';
17
+ import ping from './commands/ping';
18
+ import getchatinfo from './commands/getchatinfo';
5
19
  export default class TelegramBot extends TelegramApi {
20
+ translate;
21
+ clear;
22
+ image;
23
+ question;
24
+ sean;
25
+ code;
26
+ duckduckgo;
27
+ kanye;
28
+ joke;
29
+ dog;
30
+ bored;
31
+ epoch;
32
+ roll;
33
+ commandList;
34
+ toss;
35
+ ping;
36
+ getChatInfo;
6
37
  url;
7
38
  kv;
8
39
  get_set;
9
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
40
  ai;
11
41
  db;
12
42
  r2;
@@ -14,6 +44,23 @@ export default class TelegramBot extends TelegramApi {
14
44
  chat_model;
15
45
  constructor(config) {
16
46
  super(config.commands, config.webhook, config.handler);
47
+ this.translate = translate;
48
+ this.clear = clear;
49
+ this.image = image;
50
+ this.question = question;
51
+ this.sean = sean;
52
+ this.code = code;
53
+ this.duckduckgo = duckduckgo;
54
+ this.kanye = kanye;
55
+ this.joke = joke;
56
+ this.dog = dog;
57
+ this.bored = bored;
58
+ this.epoch = epoch;
59
+ this.roll = roll;
60
+ this.commandList = commandlist;
61
+ this.toss = toss;
62
+ this.ping = ping;
63
+ this.getChatInfo = getchatinfo;
17
64
  this.url = config.url;
18
65
  this.kv = config.kv;
19
66
  this.get_set = config.kv?.get_set;
@@ -23,340 +70,4 @@ export default class TelegramBot extends TelegramApi {
23
70
  this.bot_name = config.bot_name;
24
71
  this.chat_model = config.chat_model;
25
72
  }
26
- // bot command: /translate
27
- translate = async (update, args) => {
28
- if (this.ai === undefined) {
29
- return new Response("ok");
30
- }
31
- const ai = new Ai(this.ai);
32
- let _prompt;
33
- if (args[0][0] === "/") {
34
- _prompt = args.slice(1).join(" ");
35
- }
36
- else {
37
- _prompt = args.join(" ");
38
- }
39
- if (_prompt === "") {
40
- _prompt = "";
41
- }
42
- const langs = ["french", "arabic", "german", "spanish", "russian"];
43
- const inline_articles = await Promise.all(langs.map(async (lang) => {
44
- const response = await ai.run("@cf/meta/m2m100-1.2b", {
45
- text: _prompt,
46
- source_lang: lang,
47
- target_lang: "english",
48
- });
49
- return new TelegramInlineQueryResultArticle(response.translated_text, `${lang}: ${response.translated_text}`);
50
- }));
51
- return this.answerInlineQuery(update.inline_query?.id ?? 0, inline_articles);
52
- };
53
- // bot command: /clear
54
- // reset the llama2 session by deleting messages from d1
55
- clear = async (update) => {
56
- const { success } = await this.db
57
- .prepare("DELETE FROM Messages WHERE userId=?")
58
- .bind(update.inline_query
59
- ? update.inline_query.from.id
60
- : update.message?.from.id)
61
- .run();
62
- if (success) {
63
- if (update.inline_query) {
64
- return this.answerInlineQuery(update.inline_query.id, [
65
- new TelegramInlineQueryResultArticle("_"),
66
- ]);
67
- }
68
- return this.sendMessage(update.message?.chat.id ?? 0, "_");
69
- }
70
- return this.sendMessage(update.message?.chat.id ?? 0, "failed");
71
- };
72
- // bot command: /image
73
- image = async (update, args) => {
74
- const ai = new Ai(this.ai);
75
- let _prompt;
76
- if (args[0][0] === "/") {
77
- _prompt = args.slice(1).join(" ");
78
- }
79
- else {
80
- _prompt = args.join(" ");
81
- }
82
- if (_prompt === "") {
83
- _prompt = "";
84
- }
85
- const inputs = { prompt: _prompt, num_steps: 20 };
86
- await this.sendMessage(update.message?.chat.id ?? 0, "image is processing. please wait...");
87
- const response = await ai.run("@cf/stabilityai/stable-diffusion-xl-base-1.0", inputs);
88
- const id = crypto.randomUUID();
89
- await this.r2.put(id, response);
90
- const url = "https://r2.seanbehan.ca/" + id;
91
- return this.sendPhoto(update.message?.chat.id ?? 0, url);
92
- };
93
- // bot command: /question
94
- question = async (update, args) => {
95
- if (this.ai === undefined) {
96
- return new Response("ok");
97
- }
98
- const ai = new Ai(this.ai);
99
- let _prompt;
100
- if (args[0][0] === "/") {
101
- _prompt = args.slice(1).join(" ");
102
- }
103
- else {
104
- _prompt = args.join(" ");
105
- }
106
- if (_prompt === "") {
107
- _prompt = "";
108
- }
109
- const results = await (async () => {
110
- if (this.db) {
111
- const { results } = await this.db
112
- .prepare("SELECT * FROM Messages WHERE userId=?")
113
- .bind(update.inline_query
114
- ? update.inline_query.from.id
115
- : update.message?.from.id)
116
- .all();
117
- return results;
118
- }
119
- })();
120
- const old_messages = (() => {
121
- if (results) {
122
- return results.map((col) => ({
123
- role: "system",
124
- content: col.content,
125
- }));
126
- }
127
- return [];
128
- })();
129
- const system_prompt = "<s>" +
130
- [
131
- `Your name is ${this.bot_name}.`,
132
- `You are talking to ${update.message?.from.first_name}.`,
133
- `Your source code is at https://github.com/codebam/cf-workers-telegram-bot .`,
134
- `the current date is ${new Date().toString()}`,
135
- ].reduce((acc, cur) => {
136
- return acc + cur + "\n";
137
- }) +
138
- old_messages.reduce((acc, cur) => {
139
- return acc + cur.content + "\n";
140
- }, "") +
141
- "</s>";
142
- const p = system_prompt + "[INST]" + _prompt + "[/INST]";
143
- const prompt = p.slice(p.length - 4096, p.length);
144
- const response = await ai
145
- // @ts-expect-error ModelName doesn't need to be verified at build time
146
- .run(this.chat_model, {
147
- prompt,
148
- max_tokens: 596,
149
- })
150
- .then(({ response }) => response
151
- .replace(/(\[|)(\/|)INST(S|)(s|)(\]|)/, "")
152
- .replace(/<<(\/|)SYS>>/, ""));
153
- if (this.db) {
154
- const { success } = await this.db
155
- .prepare("INSERT INTO Messages (id, userId, content) VALUES (?, ?, ?)")
156
- .bind(crypto.randomUUID(), update.inline_query
157
- ? update.inline_query.from.id
158
- : update.message?.from.id, "[INST] " + _prompt + " [/INST]" + "\n" + response)
159
- .run();
160
- if (!success) {
161
- console.log("failed to insert data into d1");
162
- }
163
- }
164
- if (response === "") {
165
- this.clear(update);
166
- return this.question(update, args);
167
- } // sometimes llama2 doesn't respond when given lots of system prompts
168
- if (update.inline_query) {
169
- return this.answerInlineQuery(update.inline_query.id, [
170
- new TelegramInlineQueryResultArticle(response),
171
- ]);
172
- }
173
- return this.sendMessage(update.message?.chat.id ?? 0, response, "", false, false, update.message?.message_id);
174
- };
175
- // bot command: /sean
176
- sean = async (update, args) => {
177
- if (this.ai === undefined) {
178
- return new Response("ok");
179
- }
180
- const ai = new Ai(this.ai);
181
- let _prompt;
182
- if (args[0][0] === "/") {
183
- _prompt = args.slice(1).join(" ");
184
- }
185
- else {
186
- _prompt = args.join(" ");
187
- }
188
- if (_prompt === "") {
189
- _prompt = "";
190
- }
191
- const results = await (async () => {
192
- if (this.db) {
193
- const { results } = await this.db
194
- .prepare("SELECT * FROM Messages WHERE userId=?")
195
- .bind(update.inline_query
196
- ? update.inline_query.from.id
197
- : update.message?.from.id)
198
- .all();
199
- return results;
200
- }
201
- })();
202
- const old_messages = (() => {
203
- if (results) {
204
- return results.map((col) => ({
205
- role: "system",
206
- content: col.content,
207
- }));
208
- }
209
- return [];
210
- })();
211
- const system_prompt = "<s>" +
212
- [
213
- `Your name is ${this.bot_name}.`,
214
- `You are talking to ${update.message?.from.first_name}.`,
215
- `Your source code is at https://github.com/codebam/cf-workers-telegram-bot .`,
216
- `the current date is ${new Date().toString()}`,
217
- "Sean Behan is a full stack developer who goes by the username codebam.",
218
- "Sean Behan likes programming and video games.",
219
- "Pretend to be Sean Behan but don't make things up.",
220
- ].reduce((acc, cur) => {
221
- return acc + cur + "\n";
222
- }) +
223
- old_messages.reduce((acc, cur) => {
224
- return acc + cur.content + "\n";
225
- }, "") +
226
- "</s>";
227
- const p = system_prompt + "[INST]" + _prompt + "[/INST]";
228
- const prompt = p.slice(p.length - 4096, p.length);
229
- const response = await ai
230
- // @ts-expect-error ModelName doesn't need to be verified at build time
231
- .run(this.chat_model, {
232
- prompt,
233
- max_tokens: 596,
234
- })
235
- .then(({ response }) => response
236
- .replace(/(\[|)(\/|)INST(S|)(s|)(\]|)/, "")
237
- .replace(/<<(\/|)SYS>>/, "")
238
- .replace(/[OUT]/, ""));
239
- if (this.db) {
240
- const { success } = await this.db
241
- .prepare("INSERT INTO Messages (id, userId, content) VALUES (?, ?, ?)")
242
- .bind(crypto.randomUUID(), update.inline_query
243
- ? update.inline_query.from.id
244
- : update.message?.from.id, "[INST] " + _prompt + " [/INST]" + "\n" + response)
245
- .run();
246
- if (!success) {
247
- console.log("failed to insert data into d1");
248
- }
249
- }
250
- if (update.inline_query) {
251
- return this.answerInlineQuery(update.inline_query.id, [
252
- new TelegramInlineQueryResultArticle(response),
253
- ]);
254
- }
255
- return this.sendMessage(update.message?.chat.id ?? 0, response, "", false, false, update.message?.message_id);
256
- };
257
- // bot command: /code
258
- code = async (update) => ((url) => update.inline_query
259
- ? this.answerInlineQuery(update.inline_query.id, [
260
- new TelegramInlineQueryResultArticle(url),
261
- ])
262
- : this.sendMessage(update.message?.chat.id ?? 0, url))("https://github.com/codebam/cf-workers-telegram-bot");
263
- // bot command: /duckduckgo
264
- duckduckgo = async (update, args) => ((query) => ((duckduckgo_url) => update.inline_query && query === ""
265
- ? this.answerInlineQuery(update.inline_query.id, [
266
- new TelegramInlineQueryResultArticle("https://duckduckgo.com"),
267
- ])
268
- : update.inline_query
269
- ? fetch(addSearchParams(new URL("https://api.duckduckgo.com"), {
270
- q: query,
271
- format: "json",
272
- t: "telegram_bot",
273
- no_redirect: "1",
274
- }).href).then((response) => response
275
- .json()
276
- .then((results) => results)
277
- .then((ddg_response) => ((instant_answer_url, thumb_url, default_thumb_url = "https://duckduckgo.com/assets/icons/meta/DDG-icon_256x256.png") => this.answerInlineQuery(update.inline_query?.id ?? 0, instant_answer_url !== ""
278
- ? [
279
- new TelegramInlineQueryResultArticle(`${instant_answer_url}\n\n<a href="${addSearchParams(new URL(duckduckgo_url), {
280
- q: args
281
- .slice(2)
282
- .join(" ")
283
- .replace(/^!\w* /, ""),
284
- }).href}">Results From DuckDuckGo</a>`, instant_answer_url, "HTML", thumb_url),
285
- new TelegramInlineQueryResultArticle(duckduckgo_url, duckduckgo_url, "", default_thumb_url),
286
- ]
287
- : [
288
- new TelegramInlineQueryResultArticle(duckduckgo_url, duckduckgo_url, "", default_thumb_url),
289
- ], 3600 // 1 hour
290
- ))(ddg_response.Redirect ?? ddg_response.AbstractURL, ddg_response.Redirect === ""
291
- ? `https://duckduckgo.com${ddg_response.Image !== "" && ddg_response.Image
292
- ? ddg_response.Image
293
- : ddg_response.RelatedTopics.length !== 0 &&
294
- ddg_response.RelatedTopics[0].Icon.URL !== ""
295
- ? ddg_response.RelatedTopics[0].Icon.URL
296
- : "/i/f96d4798.png"}`
297
- : "")))
298
- : this.sendMessage(update.message?.chat.id ?? 0, duckduckgo_url))(query === ""
299
- ? "https://duckduckgo.com"
300
- : (() => {
301
- if (query[0][0] !== "/") {
302
- return addSearchParams(new URL("https://duckduckgo.com"), {
303
- q: query,
304
- }).href;
305
- }
306
- return addSearchParams(new URL("https://duckduckgo.com"), {
307
- q: query.split(" ").slice(1).join(" "),
308
- }).href;
309
- })()))(args.join(" "));
310
- // bot command: /kanye
311
- kanye = async (update) => fetch("https://api.kanye.rest")
312
- .then((response) => responseToJSON(response))
313
- .then((json) => ((message) => update.inline_query
314
- ? this.answerInlineQuery(update.inline_query.id, [
315
- new TelegramInlineQueryResultArticle(message),
316
- ])
317
- : this.sendMessage(update.message?.chat.id ?? 0, message))(`Kanye says... ${json.quote}`))
318
- .catch(() => new Response("Failed to parse JSON"));
319
- // bot command: /joke
320
- joke = async (update) => fetch("https://v2.jokeapi.dev/joke/Any?safe-mode")
321
- .then((response) => responseToJSON(response))
322
- .then((joke) => joke)
323
- .then((joke_response) => ((message) => update.inline_query
324
- ? this.answerInlineQuery(update.inline_query.id, [
325
- new TelegramInlineQueryResultArticle(message, joke_response.joke ?? joke_response.setup, "HTML"),
326
- ], 0)
327
- : this.sendMessage(update.message?.chat.id ?? 0, message, "HTML"))(joke_response.joke ??
328
- `${joke_response.setup}\n\n<tg-spoiler>${joke_response.delivery}</tg-spoiler>`));
329
- // bot command: /dog
330
- dog = async (update) => fetch("https://shibe.online/api/shibes")
331
- .then((response) => response.json())
332
- .then((json) => json)
333
- .then((shibe_response) => update.inline_query
334
- ? this.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultPhoto(shibe_response[0])], 0)
335
- : this.sendPhoto(update.message?.chat.id ?? 0, shibe_response[0]));
336
- // bot command: /bored
337
- bored = async (update) => fetch("https://boredapi.com/api/activity/")
338
- .then((response) => responseToJSON(response))
339
- .then((json) => json)
340
- .then((bored_response) => update.inline_query
341
- ? this.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultArticle(bored_response.activity)], 0)
342
- : this.sendMessage(update.message?.chat.id ?? 0, bored_response.activity));
343
- // bot command: /epoch
344
- epoch = async (update) => ((seconds) => update.inline_query
345
- ? this.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultArticle(seconds)], 0)
346
- : this.sendMessage(update.message?.chat.id ?? 0, seconds))(Math.floor(Date.now() / 1000).toString());
347
- _average = (numbers) => parseFloat((numbers.reduce((prev, cur) => prev + cur, 0) / numbers.length || 0).toFixed(2));
348
- // bot command: /roll
349
- roll = async (update, args) => ((outcome, message) => update.inline_query
350
- ? this.answerInlineQuery(update.inline_query.id, [
351
- new TelegramInlineQueryResultArticle(message(update.inline_query.from.username, update.inline_query.from.first_name, outcome)),
352
- ])
353
- : this.sendMessage(update.message?.chat.id ?? 0, message(update.message?.from.username ?? "", update.message?.from.first_name ?? "", outcome)))(Math.floor(Math.random() * (parseInt(args[1]) || 6 - 1 + 1) + 1), (username, first_name, outcome) => `${first_name ?? username} rolled a ${parseInt(args[1]) || 6} sided die. it landed on ${outcome}`);
354
- // bot command: /commandList
355
- commandList = async (update) => this.sendMessage(update.message?.chat.id ?? 0, `${Object.keys(this.commands).join("\n")}`, "HTML");
356
- // bot command: /toss
357
- toss = async (update) => this.sendMessage(update.message?.chat.id ?? 0, Math.floor(Math.random() * 2) == 0 ? "heads" : "tails");
358
- // bot command: /ping
359
- ping = async (update, args) => this.sendMessage(update.message?.chat.id ?? 0, args.length === 1 ? "pong" : args.slice(1).join(" "));
360
- // bot command: /chatInfo
361
- getChatInfo = async (update) => this.sendMessage(update.message?.chat.id ?? 0, preTagString(prettyJSON(update.message?.chat ?? 0)), "HTML");
362
73
  }
@@ -1,4 +1,4 @@
1
- import { TelegramCommand } from "./types";
1
+ import { TelegramCommand } from './types';
2
2
  export default class TelegramCommands {
3
3
  static ping: TelegramCommand;
4
4
  static toss: TelegramCommand;
@@ -1,18 +1,18 @@
1
1
  export default class TelegramCommands {
2
- static ping = async (bot, update, args) => bot.ping(update, args);
3
- static toss = async (bot, update) => bot.toss(update);
4
- static epoch = async (bot, update) => bot.epoch(update);
5
- static kanye = async (bot, update) => bot.kanye(update);
6
- static bored = async (bot, update) => bot.bored(update);
7
- static joke = async (bot, update) => bot.joke(update);
8
- static dog = async (bot, update) => bot.dog(update);
9
- static roll = async (bot, update, args) => bot.roll(update, args);
10
- static duckduckgo = async (bot, update, args) => bot.duckduckgo(update, args);
11
- static question = async (bot, update, args) => bot.question(update, args);
12
- static sean = async (bot, update, args) => bot.sean(update, args);
13
- static clear = async (bot, update) => bot.clear(update);
14
- static code = async (bot, update) => bot.code(update);
15
- static commandList = async (bot, update) => bot.commandList(update);
16
- static image = async (bot, update, args) => bot.image(update, args);
17
- static translate = async (bot, update, args) => bot.translate(update, args);
2
+ static ping = async (bot, update, args) => bot.ping(bot, update, args);
3
+ static toss = async (bot, update) => bot.toss(bot, update);
4
+ static epoch = async (bot, update) => bot.epoch(bot, update);
5
+ static kanye = async (bot, update) => bot.kanye(bot, update);
6
+ static bored = async (bot, update) => bot.bored(bot, update);
7
+ static joke = async (bot, update) => bot.joke(bot, update);
8
+ static dog = async (bot, update) => bot.dog(bot, update);
9
+ static roll = async (bot, update, args) => bot.roll(bot, update, args);
10
+ static duckduckgo = async (bot, update, args) => bot.duckduckgo(bot, update, args);
11
+ static question = async (bot, update, args) => bot.question(bot, update, args);
12
+ static sean = async (bot, update, args) => bot.sean(bot, update, args);
13
+ static clear = async (bot, update) => bot.clear(bot, update);
14
+ static code = async (bot, update) => bot.code(bot, update);
15
+ static commandList = async (bot, update) => bot.commandList(bot, update);
16
+ static image = async (bot, update, args) => bot.image(bot, update, args);
17
+ static translate = async (bot, update, args) => bot.translate(bot, update, args);
18
18
  }
@@ -1,6 +1,6 @@
1
1
  /// <reference types="@cloudflare/workers-types" />
2
- import Webhook from "./webhook";
3
- import { WebhookCommands } from "./types";
2
+ import Webhook from './webhook';
3
+ import { WebhookCommands } from './types';
4
4
  export default class TelegramWebhook extends Webhook {
5
5
  constructor(api: URL, token: string, url: URL);
6
6
  set: (drop_pending_updates?: boolean) => Promise<Response>;