@codebam/cf-workers-telegram-bot 5.14.0 → 5.16.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}`)
@@ -9,7 +9,9 @@ export default class TelegramBot extends TelegramApi {
9
9
  db: D1Database;
10
10
  r2: R2Bucket;
11
11
  bot_name: string;
12
+ chat_model: string;
12
13
  constructor(config: Config);
14
+ translate: (update: TelegramUpdate, args: string[]) => Promise<Response>;
13
15
  clear: (update: TelegramUpdate) => Promise<Response>;
14
16
  image: (update: TelegramUpdate, args: string[]) => Promise<Response>;
15
17
  question: (update: TelegramUpdate, args: string[]) => Promise<Response>;
@@ -11,6 +11,7 @@ export default class TelegramBot extends TelegramApi {
11
11
  db;
12
12
  r2;
13
13
  bot_name;
14
+ chat_model;
14
15
  constructor(config) {
15
16
  super(config.commands, config.webhook, config.handler);
16
17
  this.url = config.url;
@@ -20,7 +21,35 @@ export default class TelegramBot extends TelegramApi {
20
21
  this.db = config.db;
21
22
  this.r2 = config.r2;
22
23
  this.bot_name = config.bot_name;
24
+ this.chat_model = config.chat_model;
23
25
  }
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
+ };
24
53
  // bot command: /clear
25
54
  // reset the llama2 session by deleting messages from d1
26
55
  clear = async (update) => {
@@ -110,9 +139,13 @@ export default class TelegramBot extends TelegramApi {
110
139
  return acc + cur.content + "\n";
111
140
  }, "") +
112
141
  "</s>";
142
+ const p = system_prompt + "[INST]" + _prompt + "[/INST]";
143
+ const prompt = p.slice(p.length - 4096, p.length);
113
144
  const response = await ai
114
- .run("@hf/thebloke/llama-2-13b-chat-awq", {
115
- prompt: system_prompt + "[INST]" + _prompt + "[/INST]",
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,
116
149
  })
117
150
  .then(({ response }) => response
118
151
  .replace(/(\[|)(\/|)INST(S|)(s|)(\]|)/, "")
@@ -155,6 +188,26 @@ export default class TelegramBot extends TelegramApi {
155
188
  if (_prompt === "") {
156
189
  _prompt = "";
157
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
+ })();
158
211
  const system_prompt = "<s>" +
159
212
  [
160
213
  `Your name is ${this.bot_name}.`,
@@ -167,14 +220,33 @@ export default class TelegramBot extends TelegramApi {
167
220
  ].reduce((acc, cur) => {
168
221
  return acc + cur + "\n";
169
222
  }) +
223
+ old_messages.reduce((acc, cur) => {
224
+ return acc + cur.content + "\n";
225
+ }, "") +
170
226
  "</s>";
227
+ const p = system_prompt + "[INST]" + _prompt + "[/INST]";
228
+ const prompt = p.slice(p.length - 4096, p.length);
171
229
  const response = await ai
172
- .run("@hf/thebloke/llama-2-13b-chat-awq", {
173
- prompt: system_prompt + "[INST]" + _prompt + "[/INST]",
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,
174
234
  })
175
235
  .then(({ response }) => response
176
236
  .replace(/(\[|)(\/|)INST(S|)(s|)(\]|)/, "")
177
- .replace(/<<(\/|)SYS>>/, ""));
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
+ }
178
250
  if (update.inline_query) {
179
251
  return this.answerInlineQuery(update.inline_query.id, [
180
252
  new TelegramInlineQueryResultArticle(response),
@@ -206,7 +278,7 @@ export default class TelegramBot extends TelegramApi {
206
278
  ? [
207
279
  new TelegramInlineQueryResultArticle(`${instant_answer_url}\n\n<a href="${addSearchParams(new URL(duckduckgo_url), {
208
280
  q: args
209
- .slice(1)
281
+ .slice(2)
210
282
  .join(" ")
211
283
  .replace(/^!\w* /, ""),
212
284
  }).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
  }
@@ -19,6 +19,7 @@ export declare class Config {
19
19
  ai: any;
20
20
  db: any;
21
21
  r2: any;
22
+ chat_model: string;
22
23
  constructor(config?: Partial<Config>);
23
24
  }
24
25
  export declare const localhost: URL;
@@ -16,6 +16,7 @@ export class Config {
16
16
  db;
17
17
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
18
  r2;
19
+ chat_model;
19
20
  constructor(config = {}) {
20
21
  this.bot_name = config.bot_name || "";
21
22
  this.api = config.api || BotApi;
@@ -27,6 +28,7 @@ export class Config {
27
28
  this.ai = config.ai;
28
29
  this.db = config.db;
29
30
  this.r2 = config.r2;
31
+ this.chat_model = config.chat_model;
30
32
  }
31
33
  }
32
34
  export const localhost = new URL("http://localhost");
@@ -6,9 +6,11 @@ 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;
13
+ CHAT_MODEL: string;
12
14
  }
13
15
  declare const _default: {
14
16
  fetch: (request: Request, env: Environment) => Promise<Response>;
@@ -23,12 +23,13 @@ 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,
30
30
  db: env.DB,
31
31
  r2: env.R2,
32
+ chat_model: env.CHAT_MODEL,
32
33
  },
33
34
  {
34
35
  bot_name: "@duckduckbot",
@@ -76,5 +77,16 @@ export default {
76
77
  ai: env.AI,
77
78
  db: env.DB,
78
79
  },
80
+ {
81
+ bot_name: "@TranslatePartyBot",
82
+ api: TelegramBot,
83
+ 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)),
84
+ commands: {
85
+ default: TelegramCommands.translate,
86
+ inline: TelegramCommands.translate,
87
+ "/start": TelegramCommands.commandList,
88
+ },
89
+ ai: env.AI,
90
+ },
79
91
  ]).handle(request),
80
92
  };
package/package.json CHANGED
@@ -1,45 +1,48 @@
1
1
  {
2
- "name": "@codebam/cf-workers-telegram-bot",
3
- "version": "5.14.0",
4
- "description": "serverless telegram bot on cf workers",
5
- "main": "./dist/main/src/main.js",
6
- "module": "./dist/main/src/main.js",
7
- "files": [
8
- "dist",
9
- "LICENSE",
10
- "LICENSE_MIT",
11
- "README.md"
12
- ],
13
- "keywords": [
14
- "cloudflare",
15
- "telegram",
16
- "worker",
17
- "webhook"
18
- ],
19
- "type": "module",
20
- "private": false,
21
- "scripts": {
22
- "build": "tsc --project tsconfig.json",
23
- "lint": "eslint src"
24
- },
25
- "author": "codebam",
26
- "license": "Apache-2.0",
27
- "repository": {
28
- "type": "git",
29
- "url": "https://github.com/codebam/cf-workers-telegram-bot.git"
30
- },
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"
40
- },
41
- "dependencies": {
42
- "@cloudflare/ai": "^1.0.33"
43
- },
44
- "gitHead": "b61227dbb262c62ceb5c2401b71a353caa3e6346"
2
+ "name": "@codebam/cf-workers-telegram-bot",
3
+ "version": "5.16.0",
4
+ "description": "serverless telegram bot on cf workers",
5
+ "main": "./dist/main/src/main.js",
6
+ "module": "./dist/main/src/main.js",
7
+ "files": [
8
+ "dist",
9
+ "LICENSE",
10
+ "LICENSE_MIT",
11
+ "README.md"
12
+ ],
13
+ "keywords": [
14
+ "cloudflare",
15
+ "telegram",
16
+ "worker",
17
+ "webhook"
18
+ ],
19
+ "type": "module",
20
+ "private": false,
21
+ "scripts": {
22
+ "build": "tsc --project tsconfig.json",
23
+ "lint": "eslint src"
24
+ },
25
+ "author": "codebam",
26
+ "license": "Apache-2.0",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "https://github.com/codebam/cf-workers-telegram-bot.git"
30
+ },
31
+ "devDependencies": {
32
+ "@cloudflare/workers-types": "^4.20240502.0",
33
+ "@eslint/js": "^9.1.1",
34
+ "@typescript-eslint/eslint-plugin": "^7.8.0",
35
+ "@typescript-eslint/parser": "^7.8.0",
36
+ "eslint": "^8.56.0",
37
+ "eslint-config-prettier": "^9.1.0",
38
+ "globals": "^15.1.0",
39
+ "lerna": "^8.1.2",
40
+ "prettier": "^3.2.5",
41
+ "typescript": "^5.4.5",
42
+ "typescript-eslint": "^7.8.0"
43
+ },
44
+ "dependencies": {
45
+ "@cloudflare/ai": "1.0.53"
46
+ },
47
+ "gitHead": "fb3449a1162c24d725a1cde10ea9a5b3fde0fba0"
45
48
  }