@codebam/cf-workers-telegram-bot 5.14.0 → 5.15.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.
@@ -24,10 +24,10 @@ export default class Handler {
24
24
  POST: this.postResponse,
25
25
  default: () => new Promise(() => new Response()),
26
26
  };
27
- getAccessKeys = async (configs) => Promise.all(configs.map((bot_config) => sha256(bot_config.webhook?.token ?? "").then((hash) => [
28
- hash,
29
- bot_config,
30
- ]))).then((result) => Object.fromEntries(result));
27
+ getAccessKeys = async (configs) => Promise.all(configs.map((bot_config) => sha256(bot_config.webhook?.token ?? "").then((hash) => {
28
+ console.log(hash);
29
+ return [hash, bot_config];
30
+ }))).then((result) => Object.fromEntries(result));
31
31
  // handles the request
32
32
  handle = async (request) => this.getAccessKeys(this.configs).then((access_keys) => Object.keys(this.responses).includes(request.method)
33
33
  ? this.responses[request.method](request, ((key) => {
@@ -13,14 +13,22 @@ export default class TelegramApi extends BotApi {
13
13
  message: this.messageUpdate,
14
14
  default: new Response(),
15
15
  };
16
- update = async (update) => ((log({ update }) &&
17
- update.message &&
18
- this.updates.message(update)) ||
19
- (update.inline_query &&
20
- update.inline_query.query === "" &&
21
- undefined) ||
22
- this.updates.inline_query(update)) ??
23
- this.updates.default;
16
+ update = async (update) => {
17
+ console.log({ update });
18
+ if (update) {
19
+ if (update.inline_query) {
20
+ if (update.inline_query.query !== "") {
21
+ return this.updates.inline_query(update);
22
+ }
23
+ }
24
+ else {
25
+ if (update.message) {
26
+ return this.updates.message(update);
27
+ }
28
+ }
29
+ }
30
+ return this.updates.default;
31
+ };
24
32
  // greet new users who join
25
33
  greetUsers = async (update) => update.message?.new_chat_members
26
34
  ? this.sendMessage(update.message.chat.id, `Welcome to ${update.message.chat.title}, ${update.message.from.username}`)
@@ -10,6 +10,7 @@ export default class TelegramBot extends TelegramApi {
10
10
  r2: R2Bucket;
11
11
  bot_name: string;
12
12
  constructor(config: Config);
13
+ translate: (update: TelegramUpdate, args: string[]) => Promise<Response>;
13
14
  clear: (update: TelegramUpdate) => Promise<Response>;
14
15
  image: (update: TelegramUpdate, args: string[]) => Promise<Response>;
15
16
  question: (update: TelegramUpdate, args: string[]) => Promise<Response>;
@@ -21,6 +21,33 @@ export default class TelegramBot extends TelegramApi {
21
21
  this.r2 = config.r2;
22
22
  this.bot_name = config.bot_name;
23
23
  }
24
+ // bot command: /translate
25
+ translate = async (update, args) => {
26
+ if (this.ai === undefined) {
27
+ return new Response("ok");
28
+ }
29
+ const ai = new Ai(this.ai);
30
+ let _prompt;
31
+ if (args[0][0] === "/") {
32
+ _prompt = args.slice(1).join(" ");
33
+ }
34
+ else {
35
+ _prompt = args.join(" ");
36
+ }
37
+ if (_prompt === "") {
38
+ _prompt = "";
39
+ }
40
+ const langs = ["french", "arabic", "german", "spanish", "russian"];
41
+ const inline_articles = await Promise.all(langs.map(async (lang) => {
42
+ const response = await ai.run("@cf/meta/m2m100-1.2b", {
43
+ text: _prompt,
44
+ source_lang: lang,
45
+ target_lang: "english",
46
+ });
47
+ return new TelegramInlineQueryResultArticle(response.translated_text, `${lang}: ${response.translated_text}`);
48
+ }));
49
+ return this.answerInlineQuery(update.inline_query?.id ?? 0, inline_articles);
50
+ };
24
51
  // bot command: /clear
25
52
  // reset the llama2 session by deleting messages from d1
26
53
  clear = async (update) => {
@@ -110,9 +137,12 @@ export default class TelegramBot extends TelegramApi {
110
137
  return acc + cur.content + "\n";
111
138
  }, "") +
112
139
  "</s>";
140
+ const p = system_prompt + "[INST]" + _prompt + "[/INST]";
141
+ const prompt = p.slice(p.length - 4096, p.length);
113
142
  const response = await ai
114
- .run("@hf/thebloke/llama-2-13b-chat-awq", {
115
- prompt: system_prompt + "[INST]" + _prompt + "[/INST]",
143
+ .run("@hf/thebloke/orca-2-13b-awq", {
144
+ prompt,
145
+ max_tokens: 596,
116
146
  })
117
147
  .then(({ response }) => response
118
148
  .replace(/(\[|)(\/|)INST(S|)(s|)(\]|)/, "")
@@ -155,6 +185,26 @@ export default class TelegramBot extends TelegramApi {
155
185
  if (_prompt === "") {
156
186
  _prompt = "";
157
187
  }
188
+ const results = await (async () => {
189
+ if (this.db) {
190
+ const { results } = await this.db
191
+ .prepare("SELECT * FROM Messages WHERE userId=?")
192
+ .bind(update.inline_query
193
+ ? update.inline_query.from.id
194
+ : update.message?.from.id)
195
+ .all();
196
+ return results;
197
+ }
198
+ })();
199
+ const old_messages = (() => {
200
+ if (results) {
201
+ return results.map((col) => ({
202
+ role: "system",
203
+ content: col.content,
204
+ }));
205
+ }
206
+ return [];
207
+ })();
158
208
  const system_prompt = "<s>" +
159
209
  [
160
210
  `Your name is ${this.bot_name}.`,
@@ -167,14 +217,32 @@ export default class TelegramBot extends TelegramApi {
167
217
  ].reduce((acc, cur) => {
168
218
  return acc + cur + "\n";
169
219
  }) +
220
+ old_messages.reduce((acc, cur) => {
221
+ return acc + cur.content + "\n";
222
+ }, "") +
170
223
  "</s>";
224
+ const p = system_prompt + "[INST]" + _prompt + "[/INST]";
225
+ const prompt = p.slice(p.length - 4096, p.length);
171
226
  const response = await ai
172
- .run("@hf/thebloke/llama-2-13b-chat-awq", {
173
- prompt: system_prompt + "[INST]" + _prompt + "[/INST]",
227
+ .run("@hf/thebloke/orca-2-13b-awq", {
228
+ prompt,
229
+ max_tokens: 596,
174
230
  })
175
231
  .then(({ response }) => response
176
232
  .replace(/(\[|)(\/|)INST(S|)(s|)(\]|)/, "")
177
- .replace(/<<(\/|)SYS>>/, ""));
233
+ .replace(/<<(\/|)SYS>>/, "")
234
+ .replace(/[OUT]/, ""));
235
+ if (this.db) {
236
+ const { success } = await this.db
237
+ .prepare("INSERT INTO Messages (id, userId, content) VALUES (?, ?, ?)")
238
+ .bind(crypto.randomUUID(), update.inline_query
239
+ ? update.inline_query.from.id
240
+ : update.message?.from.id, "[INST] " + _prompt + " [/INST]" + "\n" + response)
241
+ .run();
242
+ if (!success) {
243
+ console.log("failed to insert data into d1");
244
+ }
245
+ }
178
246
  if (update.inline_query) {
179
247
  return this.answerInlineQuery(update.inline_query.id, [
180
248
  new TelegramInlineQueryResultArticle(response),
@@ -206,7 +274,7 @@ export default class TelegramBot extends TelegramApi {
206
274
  ? [
207
275
  new TelegramInlineQueryResultArticle(`${instant_answer_url}\n\n<a href="${addSearchParams(new URL(duckduckgo_url), {
208
276
  q: args
209
- .slice(1)
277
+ .slice(2)
210
278
  .join(" ")
211
279
  .replace(/^!\w* /, ""),
212
280
  }).href}">Results From DuckDuckGo</a>`, instant_answer_url, "HTML", thumb_url),
@@ -15,4 +15,5 @@ export default class TelegramCommands {
15
15
  static code: TelegramCommand;
16
16
  static commandList: TelegramCommand;
17
17
  static image: TelegramCommand;
18
+ static translate: TelegramCommand;
18
19
  }
@@ -14,4 +14,5 @@ export default class TelegramCommands {
14
14
  static code = async (bot, update) => bot.code(update);
15
15
  static commandList = async (bot, update) => bot.commandList(update);
16
16
  static image = async (bot, update, args) => bot.image(update, args);
17
+ static translate = async (bot, update, args) => bot.translate(update, args);
17
18
  }
@@ -6,6 +6,7 @@ interface Environment {
6
6
  SECRET_TELEGRAM_API_TOKEN2: string;
7
7
  SECRET_TELEGRAM_API_TOKEN3: string;
8
8
  SECRET_TELEGRAM_API_TOKEN4: string;
9
+ SECRET_TELEGRAM_API_TOKEN5: string;
9
10
  AI: string;
10
11
  DB: D1Database;
11
12
  R2: R2Bucket;
@@ -23,7 +23,7 @@ export default {
23
23
  "/clear": TelegramCommands.clear,
24
24
  "/help": TelegramCommands.commandList,
25
25
  "/image": TelegramCommands.image,
26
- "/start": TelegramCommands.commandList,
26
+ "/start": TelegramCommands.question,
27
27
  },
28
28
  kv: { get_set: env.KV_GET_SET, uid_data: env.KV_UID_DATA },
29
29
  ai: env.AI,
@@ -76,5 +76,16 @@ export default {
76
76
  ai: env.AI,
77
77
  db: env.DB,
78
78
  },
79
+ {
80
+ bot_name: "@TranslatePartyBot",
81
+ api: TelegramBot,
82
+ webhook: new TelegramWebhook(new URL(`https://api.telegram.org/bot${env.SECRET_TELEGRAM_API_TOKEN5}`), env.SECRET_TELEGRAM_API_TOKEN5, new URL(new URL(request.url).origin)),
83
+ commands: {
84
+ default: TelegramCommands.translate,
85
+ inline: TelegramCommands.translate,
86
+ "/start": TelegramCommands.commandList,
87
+ },
88
+ ai: env.AI,
89
+ },
79
90
  ]).handle(request),
80
91
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codebam/cf-workers-telegram-bot",
3
- "version": "5.14.0",
3
+ "version": "5.15.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",
@@ -29,17 +29,17 @@
29
29
  "url": "https://github.com/codebam/cf-workers-telegram-bot.git"
30
30
  },
31
31
  "devDependencies": {
32
- "@cloudflare/workers-types": "^4.20231121.0",
33
- "@typescript-eslint/eslint-plugin": "^6.12.0",
34
- "@typescript-eslint/parser": "^6.12.0",
35
- "eslint": "^8.54.0",
36
- "eslint-config-prettier": "^9.0.0",
37
- "lerna": "^8.0.0",
38
- "prettier": "^3.1.0",
39
- "typescript": "^5.3.2"
32
+ "@cloudflare/workers-types": "^4.20240320.1",
33
+ "@typescript-eslint/eslint-plugin": "^7.4.0",
34
+ "@typescript-eslint/parser": "^7.4.0",
35
+ "eslint": "^8.57.0",
36
+ "eslint-config-prettier": "^9.1.0",
37
+ "lerna": "^8.1.2",
38
+ "prettier": "^3.2.5",
39
+ "typescript": "^5.4.3"
40
40
  },
41
41
  "dependencies": {
42
- "@cloudflare/ai": "^1.0.33"
42
+ "@cloudflare/ai": "1.0.53"
43
43
  },
44
- "gitHead": "b61227dbb262c62ceb5c2401b71a353caa3e6346"
44
+ "gitHead": "f590f9423dda46b7b591d8344c13504f6fa69d6e"
45
45
  }