@codebam/cf-workers-telegram-bot 5.17.0 → 6.2.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/README.md +18 -6
  2. package/dist/main/src/bot_api.d.ts +3 -3
  3. package/dist/main/src/commands/bored.d.ts +5 -0
  4. package/dist/main/src/commands/bored.js +8 -0
  5. package/dist/main/src/commands/clear.d.ts +5 -0
  6. package/dist/main/src/commands/clear.js +14 -0
  7. package/dist/main/src/commands/code.d.ts +5 -0
  8. package/dist/main/src/commands/code.js +4 -0
  9. package/dist/main/src/commands/commandlist.d.ts +5 -0
  10. package/dist/main/src/commands/commandlist.js +1 -0
  11. package/dist/main/src/commands/dog.d.ts +5 -0
  12. package/dist/main/src/commands/dog.js +7 -0
  13. package/dist/main/src/commands/duckduckgo.d.ts +5 -0
  14. package/dist/main/src/commands/duckduckgo.js +42 -0
  15. package/dist/main/src/commands/epoch.d.ts +5 -0
  16. package/dist/main/src/commands/epoch.js +4 -0
  17. package/dist/main/src/commands/getchatinfo.d.ts +5 -0
  18. package/dist/main/src/commands/getchatinfo.js +2 -0
  19. package/dist/main/src/commands/image.d.ts +5 -0
  20. package/dist/main/src/commands/image.js +19 -0
  21. package/dist/main/src/commands/joke.d.ts +5 -0
  22. package/dist/main/src/commands/joke.js +8 -0
  23. package/dist/main/src/commands/kanye.d.ts +5 -0
  24. package/dist/main/src/commands/kanye.js +8 -0
  25. package/dist/main/src/commands/ping.d.ts +5 -0
  26. package/dist/main/src/commands/ping.js +1 -0
  27. package/dist/main/src/commands/question.d.ts +5 -0
  28. package/dist/main/src/commands/question.js +74 -0
  29. package/dist/main/src/commands/roll.d.ts +5 -0
  30. package/dist/main/src/commands/roll.js +6 -0
  31. package/dist/main/src/commands/sean.d.ts +5 -0
  32. package/dist/main/src/commands/sean.js +76 -0
  33. package/dist/main/src/commands/toss.d.ts +5 -0
  34. package/dist/main/src/commands/toss.js +1 -0
  35. package/dist/main/src/commands/translate.d.ts +5 -0
  36. package/dist/main/src/commands/translate.js +26 -0
  37. package/dist/main/src/handler.d.ts +2 -2
  38. package/dist/main/src/handler.js +5 -7
  39. package/dist/main/src/libs.js +6 -11
  40. package/dist/main/src/main.d.ts +11 -11
  41. package/dist/main/src/main.js +11 -11
  42. package/dist/main/src/telegram_api.d.ts +3 -3
  43. package/dist/main/src/telegram_api.js +20 -27
  44. package/dist/main/src/telegram_bot.d.ts +20 -21
  45. package/dist/main/src/telegram_bot.js +52 -334
  46. package/dist/main/src/telegram_commands.d.ts +1 -1
  47. package/dist/main/src/telegram_commands.js +16 -16
  48. package/dist/main/src/telegram_webhook.d.ts +2 -2
  49. package/dist/main/src/telegram_webhook.js +5 -6
  50. package/dist/main/src/types/Balance.d.ts +6 -0
  51. package/dist/main/src/types/Balance.js +1 -0
  52. package/dist/main/src/types/Bored.d.ts +10 -0
  53. package/dist/main/src/types/Bored.js +1 -0
  54. package/dist/main/src/types/Command.d.ts +5 -0
  55. package/dist/main/src/types/Command.js +1 -0
  56. package/dist/main/src/types/Commands.d.ts +3 -0
  57. package/dist/main/src/types/Commands.js +1 -0
  58. package/dist/main/src/types/Config.d.ts +20 -0
  59. package/dist/main/src/types/Config.js +33 -0
  60. package/dist/main/src/types/DDGQueryResponse.d.ts +12 -0
  61. package/dist/main/src/types/DDGQueryResponse.js +1 -0
  62. package/dist/main/src/types/Joke.d.ts +20 -0
  63. package/dist/main/src/types/Joke.js +1 -0
  64. package/dist/main/src/types/Kv.d.ts +3 -0
  65. package/dist/main/src/types/Kv.js +1 -0
  66. package/dist/main/src/types/PartialTelegramUpdate.d.ts +11 -0
  67. package/dist/main/src/types/PartialTelegramUpdate.js +1 -0
  68. package/dist/main/src/types/TelegramChat.d.ts +21 -0
  69. package/dist/main/src/types/TelegramChat.js +1 -0
  70. package/dist/main/src/types/TelegramCommand.d.ts +5 -0
  71. package/dist/main/src/types/TelegramCommand.js +1 -0
  72. package/dist/main/src/types/TelegramFrom.d.ts +8 -0
  73. package/dist/main/src/types/TelegramFrom.js +1 -0
  74. package/dist/main/src/types/TelegramInlineQuery.d.ts +9 -0
  75. package/dist/main/src/types/TelegramInlineQuery.js +1 -0
  76. package/dist/main/src/types/TelegramInlineQueryResult.d.ts +6 -0
  77. package/dist/main/src/types/TelegramInlineQueryResult.js +8 -0
  78. package/dist/main/src/types/TelegramInlineQueryResultArticle.d.ts +8 -0
  79. package/dist/main/src/types/TelegramInlineQueryResultArticle.js +15 -0
  80. package/dist/main/src/types/TelegramInlineQueryResultPhoto.d.ts +13 -0
  81. package/dist/main/src/types/TelegramInlineQueryResultPhoto.js +19 -0
  82. package/dist/main/src/types/TelegramInlineQueryType.d.ts +2 -0
  83. package/dist/main/src/types/TelegramInlineQueryType.js +1 -0
  84. package/dist/main/src/types/TelegramInputMessageContent.d.ts +5 -0
  85. package/dist/main/src/types/TelegramInputMessageContent.js +1 -0
  86. package/dist/main/src/types/TelegramMessage.d.ts +42 -0
  87. package/dist/main/src/types/TelegramMessage.js +1 -0
  88. package/dist/main/src/types/TelegramMessageEntity.d.ts +10 -0
  89. package/dist/main/src/types/TelegramMessageEntity.js +1 -0
  90. package/dist/main/src/types/TelegramPhotoSize.d.ts +8 -0
  91. package/dist/main/src/types/TelegramPhotoSize.js +1 -0
  92. package/dist/main/src/types/TelegramUpdate.d.ts +13 -0
  93. package/dist/main/src/types/TelegramUpdate.js +36 -0
  94. package/dist/main/src/types/TelegramUser.d.ts +12 -0
  95. package/dist/main/src/types/TelegramUser.js +1 -0
  96. package/dist/main/src/types/Update.d.ts +3 -0
  97. package/dist/main/src/types/Update.js +2 -0
  98. package/dist/main/src/types/WebhookCommands.d.ts +4 -0
  99. package/dist/main/src/types/WebhookCommands.js +2 -0
  100. package/dist/main/src/types/localhost.d.ts +3 -0
  101. package/dist/main/src/types/localhost.js +1 -0
  102. package/dist/main/src/types.d.ts +28 -215
  103. package/dist/main/src/types.js +10 -113
  104. package/dist/main/src/webhook.d.ts +1 -1
  105. package/dist/main/src/webhook.js +3 -4
  106. package/dist/worker/src/worker.js +37 -37
  107. package/package.json +4 -7
package/README.md CHANGED
@@ -1,12 +1,20 @@
1
1
  # cf-workers-telegram-bot
2
2
 
3
+ [![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/codebam/cf-workers-telegram-bot)
4
+
5
+ ![screenshot of cf-workers-telegram-bot](/screenshot.png)
6
+
3
7
  serverless telegram bot on cf workers
4
8
 
5
9
  The original `worker.js` is the content of Nikhil John's
6
10
  https://github.com/nikhiljohn10/telegram-bot-worker which is licensed with MIT.
7
11
  My modifications are licensed under the Apache license.
8
12
 
9
- [![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/codebam/cf-workers-telegram-bot)
13
+ The first bot configuration is fully featured, and responds to all received
14
+ messages with llama2 if a command isn't found.
15
+
16
+ To get continuous conversation with llama2 working make sure you add a database
17
+ to your wrangler.toml and initailize it with the schema.sql
10
18
 
11
19
  To use the deploy button:
12
20
 
@@ -14,8 +22,8 @@ To use the deploy button:
14
22
  - Navigate to your new **GitHub repository > Settings > Secrets** and add the following secrets:
15
23
 
16
24
  ```yaml
17
- - Name: CF_API_TOKEN (should be added automatically)
18
- - Name: CF_ACCOUNT_ID (should be added automatically)
25
+ - Name: CLOUDFLARE_API_TOKEN (should be added automatically)
26
+ - Name: CLOUDFLARE_ACCOUNT_ID (should be added automatically)
19
27
 
20
28
  - Name: SECRET_TELEGRAM_API_TOKEN
21
29
  - Value: your-telegram-bot-token
@@ -26,9 +34,13 @@ To use the deploy button:
26
34
  To fork this repo and use wrangler:
27
35
 
28
36
  - Click fork
37
+ - `npm i -g wrangler`
29
38
  - `wrangler secret put SECRET_TELEGRAM_API_TOKEN` and set it to your telegram
30
39
  bot token
31
- - `wrangler publish`
40
+ - `wrangler d1 create llama2`
41
+ - put the database block from the command in your wrangler.toml
42
+ - `wrangler d1 execute --remote llama2 --file ./schema.sql`
43
+ - `wrangler deploy`
32
44
  - Done!
33
45
 
34
46
  ## Getting started with cf-workers-telegram-bot
@@ -36,10 +48,10 @@ To fork this repo and use wrangler:
36
48
  Once you've deployed the bot you can get your Webhook command URL by doing any
37
49
  of the following.
38
50
 
39
- - sha256sum(YourTelegramSecretKey) is the path to your webhook commands and
51
+ - sha256sum(SECRET_TELEGRAM_API_TOKEN) is the path to your webhook commands and
40
52
  should be put at the end of your worker URL to access commands such as
41
53
  setting your webhook
42
- - Use `sha256sum <<< "your secret key"` to get the path
54
+ - Use `echo -n yoursecretkey | sha256sum` to get the path
43
55
  - Open the Cloudflare Worker Logs under **Workers &gt; cf-workers-telegram-bot
44
56
  &gt; Logs &gt; Begin log stream** and make a GET request (open it in your browser)
45
57
  to your Worker URL and look at the logs to see your Access URL
@@ -1,9 +1,9 @@
1
1
  /// <reference types="@cloudflare/workers-types" />
2
- import Handler from "./handler";
3
- import { Commands, Config, Update } from "./types";
2
+ import Handler from './handler';
3
+ import { Commands, Config, Update } from './types';
4
4
  export default class BotApi {
5
5
  commands: Commands;
6
- webhook: Config["webhook"];
6
+ webhook: Config['webhook'];
7
7
  handler: Handler;
8
8
  update: (update: Update) => Promise<Response>;
9
9
  constructor(config: Partial<Config>);
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,8 @@
1
+ import { responseToJSON } from '../libs';
2
+ import { TelegramInlineQueryResultArticle } from '../types';
3
+ export default async (self, update) => fetch('https://boredapi.com/api/activity/')
4
+ .then((response) => responseToJSON(response))
5
+ .then((json) => json)
6
+ .then((bored_response) => update.inline_query
7
+ ? self.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultArticle(bored_response.activity)], 0)
8
+ : self.sendMessage(update.message?.chat.id ?? 0, bored_response.activity));
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,14 @@
1
+ import { TelegramInlineQueryResultArticle } from '../types';
2
+ export default async (self, update) => {
3
+ const { success } = await self.db
4
+ .prepare('DELETE FROM Messages WHERE userId=?')
5
+ .bind(update.inline_query ? update.inline_query.from.id : update.message?.from.id)
6
+ .run();
7
+ if (success) {
8
+ if (update.inline_query) {
9
+ return self.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultArticle('_')]);
10
+ }
11
+ return self.sendMessage(update.message?.chat.id ?? 0, '_');
12
+ }
13
+ return self.sendMessage(update.message?.chat.id ?? 0, 'failed');
14
+ };
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,4 @@
1
+ import { TelegramInlineQueryResultArticle } from '../types';
2
+ export default async (self, update) => ((url) => update.inline_query
3
+ ? self.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultArticle(url)])
4
+ : self.sendMessage(update.message?.chat.id ?? 0, url))('https://github.com/codebam/cf-workers-telegram-bot');
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1 @@
1
+ export default async (self, update) => self.sendMessage(update.message?.chat.id ?? 0, `${Object.keys(self.commands).join('\n')}`, 'HTML');
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,7 @@
1
+ import { TelegramInlineQueryResultPhoto } from '../types';
2
+ export default async (self, update) => fetch('https://shibe.online/api/shibes')
3
+ .then((response) => response.json())
4
+ .then((json) => json)
5
+ .then((shibe_response) => update.inline_query
6
+ ? self.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultPhoto(shibe_response[0])], 0)
7
+ : self.sendPhoto(update.message?.chat.id ?? 0, shibe_response[0]));
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,42 @@
1
+ import { addSearchParams } from '../libs';
2
+ import { TelegramInlineQueryResultArticle } from '../types';
3
+ export default async (self, update, args) => ((query) => ((duckduckgo_url) => update.inline_query && query === ''
4
+ ? self.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultArticle('https://duckduckgo.com')])
5
+ : update.inline_query
6
+ ? fetch(addSearchParams(new URL('https://api.duckduckgo.com'), {
7
+ q: query,
8
+ format: 'json',
9
+ t: 'telegram_bot',
10
+ no_redirect: '1',
11
+ }).href).then((response) => response
12
+ .json()
13
+ .then((results) => results)
14
+ .then((ddg_response) => ((instant_answer_url, thumb_url, default_thumb_url = 'https://duckduckgo.com/assets/icons/meta/DDG-icon_256x256.png') => self.answerInlineQuery(update.inline_query?.id ?? 0, instant_answer_url !== ''
15
+ ? [
16
+ new TelegramInlineQueryResultArticle(`${instant_answer_url}\n\n<a href="${addSearchParams(new URL(duckduckgo_url), {
17
+ q: args
18
+ .slice(2)
19
+ .join(' ')
20
+ .replace(/^!\w* /, ''),
21
+ }).href}">Results From DuckDuckGo</a>`, instant_answer_url, 'HTML', thumb_url),
22
+ new TelegramInlineQueryResultArticle(duckduckgo_url, duckduckgo_url, '', default_thumb_url),
23
+ ]
24
+ : [new TelegramInlineQueryResultArticle(duckduckgo_url, duckduckgo_url, '', default_thumb_url)], 3600))(ddg_response.Redirect ?? ddg_response.AbstractURL, ddg_response.Redirect === ''
25
+ ? `https://duckduckgo.com${ddg_response.Image !== '' && ddg_response.Image
26
+ ? ddg_response.Image
27
+ : ddg_response.RelatedTopics.length !== 0 && ddg_response.RelatedTopics[0].Icon.URL !== ''
28
+ ? ddg_response.RelatedTopics[0].Icon.URL
29
+ : '/i/f96d4798.png'}`
30
+ : '')))
31
+ : self.sendMessage(update.message?.chat.id ?? 0, duckduckgo_url))(query === ''
32
+ ? 'https://duckduckgo.com'
33
+ : (() => {
34
+ if (query[0][0] !== '/') {
35
+ return addSearchParams(new URL('https://duckduckgo.com'), {
36
+ q: query,
37
+ }).href;
38
+ }
39
+ return addSearchParams(new URL('https://duckduckgo.com'), {
40
+ q: query.split(' ').slice(1).join(' '),
41
+ }).href;
42
+ })()))(args.join(' '));
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,4 @@
1
+ import { TelegramInlineQueryResultArticle } from '../types';
2
+ export default async (self, update) => ((seconds) => update.inline_query
3
+ ? self.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultArticle(seconds)], 0)
4
+ : self.sendMessage(update.message?.chat.id ?? 0, seconds))(Math.floor(Date.now() / 1000).toString());
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,2 @@
1
+ import { preTagString, prettyJSON } from '../libs';
2
+ export default async (self, update) => self.sendMessage(update.message?.chat.id ?? 0, preTagString(prettyJSON(update.message?.chat ?? 0)), 'HTML');
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,19 @@
1
+ export default async (self, update, args) => {
2
+ let _prompt;
3
+ if (args[0][0] === '/') {
4
+ _prompt = args.slice(1).join(' ');
5
+ }
6
+ else {
7
+ _prompt = args.join(' ');
8
+ }
9
+ if (_prompt === '') {
10
+ _prompt = '';
11
+ }
12
+ const inputs = { prompt: _prompt, num_steps: 20 };
13
+ await self.sendMessage(update.message?.chat.id ?? 0, 'image is processing. please wait...');
14
+ const response = await self.ai.run('@cf/stabilityai/stable-diffusion-xl-base-1.0', inputs);
15
+ const id = crypto.randomUUID();
16
+ await self.r2.put(id, response);
17
+ const url = 'https://r2.seanbehan.ca/' + id;
18
+ return self.sendPhoto(update.message?.chat.id ?? 0, url);
19
+ };
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,8 @@
1
+ import { responseToJSON } from '../libs';
2
+ import { TelegramInlineQueryResultArticle } from '../types';
3
+ export default async (self, update) => fetch('https://v2.jokeapi.dev/joke/Any?safe-mode')
4
+ .then((response) => responseToJSON(response))
5
+ .then((joke) => joke)
6
+ .then((joke_response) => ((message) => update.inline_query
7
+ ? self.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultArticle(message, joke_response.joke ?? joke_response.setup, 'HTML')], 0)
8
+ : self.sendMessage(update.message?.chat.id ?? 0, message, 'HTML'))(joke_response.joke ?? `${joke_response.setup}\n\n<tg-spoiler>${joke_response.delivery}</tg-spoiler>`));
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,8 @@
1
+ import { responseToJSON } from '../libs';
2
+ import { TelegramInlineQueryResultArticle } from '../types';
3
+ export default async (self, update) => fetch('https://api.kanye.rest')
4
+ .then((response) => responseToJSON(response))
5
+ .then((json) => ((message) => update.inline_query
6
+ ? self.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultArticle(message)])
7
+ : self.sendMessage(update.message?.chat.id ?? 0, message))(`Kanye says... ${json.quote}`))
8
+ .catch(() => new Response('Failed to parse JSON'));
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1 @@
1
+ export default async (self, update, args) => self.sendMessage(update.message?.chat.id ?? 0, args.length === 1 ? 'pong' : args.slice(1).join(' '));
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,74 @@
1
+ import { TelegramInlineQueryResultArticle } from '../types';
2
+ export default async (self, update, args) => {
3
+ if (self.ai === undefined) {
4
+ return new Response('ok');
5
+ }
6
+ let _prompt;
7
+ if (args[0][0] === '/') {
8
+ _prompt = args.slice(1).join(' ');
9
+ }
10
+ else {
11
+ _prompt = args.join(' ');
12
+ }
13
+ if (_prompt === '') {
14
+ _prompt = '';
15
+ }
16
+ const results = await (async () => {
17
+ if (self.db) {
18
+ const { results } = await self.db
19
+ .prepare('SELECT * FROM Messages WHERE userId=?')
20
+ .bind(update.inline_query ? update.inline_query.from.id : update.message?.from.id)
21
+ .all();
22
+ return results;
23
+ }
24
+ })();
25
+ const old_messages = (() => {
26
+ if (results) {
27
+ return results.map((col) => ({
28
+ role: 'system',
29
+ content: col.content,
30
+ }));
31
+ }
32
+ return [];
33
+ })();
34
+ const system_prompt = '<s>' +
35
+ [
36
+ `Your name is ${self.bot_name}.`,
37
+ `You are talking to ${update.message?.from.first_name}.`,
38
+ `Your source code is at https://github.com/codebam/cf-workers-telegram-bot .`,
39
+ `the current date is ${new Date().toString()}`,
40
+ ].reduce((acc, cur) => {
41
+ return acc + cur + '\n';
42
+ }) +
43
+ old_messages.reduce((acc, cur) => {
44
+ return acc + cur.content + '\n';
45
+ }, '') +
46
+ '</s>';
47
+ const p = system_prompt + '[INST]' + _prompt + '[/INST]';
48
+ const prompt = p.slice(p.length - 4096, p.length);
49
+ const response = await self.ai
50
+ // @ts-expect-error chat model might not match
51
+ .run(self.chat_model, {
52
+ prompt,
53
+ max_tokens: 596,
54
+ })
55
+ /* eslint-disable @typescript-eslint/no-explicit-any */
56
+ .then(({ response }) => response.replace(/(\[|)(\/|)INST(S|)(s|)(\]|)/, '').replace(/<<(\/|)SYS>>/, ''));
57
+ if (self.db) {
58
+ const { success } = await self.db
59
+ .prepare('INSERT INTO Messages (id, userId, content) VALUES (?, ?, ?)')
60
+ .bind(crypto.randomUUID(), update.inline_query ? update.inline_query.from.id : update.message?.from.id, '[INST] ' + _prompt + ' [/INST]' + '\n' + response)
61
+ .run();
62
+ if (!success) {
63
+ console.log('failed to insert data into d1');
64
+ }
65
+ }
66
+ if (response === '') {
67
+ self.clear(self, update);
68
+ return self.question(self, update, args);
69
+ } // sometimes llama2 doesn't respond when given lots of system prompts
70
+ if (update.inline_query) {
71
+ return self.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultArticle(response)]);
72
+ }
73
+ return self.sendMessage(update.message?.chat.id ?? 0, response, '', false, false, update.message?.message_id);
74
+ };
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,6 @@
1
+ import { TelegramInlineQueryResultArticle } from '../types';
2
+ export default async (self, update, args) => ((outcome, message) => update.inline_query
3
+ ? self.answerInlineQuery(update.inline_query.id, [
4
+ new TelegramInlineQueryResultArticle(message(update.inline_query.from.username, update.inline_query.from.first_name, outcome)),
5
+ ])
6
+ : self.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}`);
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,76 @@
1
+ import { TelegramInlineQueryResultArticle } from '../types';
2
+ export default async (self, update, args) => {
3
+ if (self.ai === undefined) {
4
+ return new Response('ok');
5
+ }
6
+ let _prompt;
7
+ if (args[0][0] === '/') {
8
+ _prompt = args.slice(1).join(' ');
9
+ }
10
+ else {
11
+ _prompt = args.join(' ');
12
+ }
13
+ if (_prompt === '') {
14
+ _prompt = '';
15
+ }
16
+ const results = await (async () => {
17
+ if (self.db) {
18
+ const { results } = await self.db
19
+ .prepare('SELECT * FROM Messages WHERE userId=?')
20
+ .bind(update.inline_query ? update.inline_query.from.id : update.message?.from.id)
21
+ .all();
22
+ return results;
23
+ }
24
+ })();
25
+ const old_messages = (() => {
26
+ if (results) {
27
+ return results.map((col) => ({
28
+ role: 'system',
29
+ content: col.content,
30
+ }));
31
+ }
32
+ return [];
33
+ })();
34
+ const system_prompt = '<s>' +
35
+ [
36
+ `Your name is ${self.bot_name}.`,
37
+ `You are talking to ${update.message?.from.first_name}.`,
38
+ `Your source code is at https://github.com/codebam/cf-workers-telegram-bot .`,
39
+ `the current date is ${new Date().toString()}`,
40
+ 'Sean Behan is a full stack developer who goes by the username codebam.',
41
+ 'Sean Behan likes programming and video games.',
42
+ "Pretend to be Sean Behan but don't make things up.",
43
+ ].reduce((acc, cur) => {
44
+ return acc + cur + '\n';
45
+ }) +
46
+ old_messages.reduce((acc, cur) => {
47
+ return acc + cur.content + '\n';
48
+ }, '') +
49
+ '</s>';
50
+ const p = system_prompt + '[INST]' + _prompt + '[/INST]';
51
+ const prompt = p.slice(p.length - 4096, p.length);
52
+ const response = await self.ai
53
+ // @ts-expect-error model might not match
54
+ .run(self.chat_model, {
55
+ prompt,
56
+ max_tokens: 596,
57
+ })
58
+ /* eslint-disable @typescript-eslint/no-explicit-any */
59
+ .then(({ response }) => response
60
+ .replace(/(\[|)(\/|)INST(S|)(s|)(\]|)/, '')
61
+ .replace(/<<(\/|)SYS>>/, '')
62
+ .replace(/[OUT]/, ''));
63
+ if (self.db) {
64
+ const { success } = await self.db
65
+ .prepare('INSERT INTO Messages (id, userId, content) VALUES (?, ?, ?)')
66
+ .bind(crypto.randomUUID(), update.inline_query ? update.inline_query.from.id : update.message?.from.id, '[INST] ' + _prompt + ' [/INST]' + '\n' + response)
67
+ .run();
68
+ if (!success) {
69
+ console.log('failed to insert data into d1');
70
+ }
71
+ }
72
+ if (update.inline_query) {
73
+ return self.answerInlineQuery(update.inline_query.id, [new TelegramInlineQueryResultArticle(response)]);
74
+ }
75
+ return self.sendMessage(update.message?.chat.id ?? 0, response, '', false, false, update.message?.message_id);
76
+ };
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1 @@
1
+ export default async (self, update) => self.sendMessage(update.message?.chat.id ?? 0, Math.floor(Math.random() * 2) == 0 ? 'heads' : 'tails');
@@ -0,0 +1,5 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import TelegramBot from '../telegram_bot';
3
+ import { TelegramUpdate } from '../types';
4
+ declare const _default: (self: TelegramBot, update: TelegramUpdate, args: string[]) => Promise<Response>;
5
+ export default _default;
@@ -0,0 +1,26 @@
1
+ import { TelegramInlineQueryResultArticle } from '../types';
2
+ export default async (self, update, args) => {
3
+ if (self.ai === undefined) {
4
+ return new Response('ok');
5
+ }
6
+ let _prompt;
7
+ if (args[0][0] === '/') {
8
+ _prompt = args.slice(1).join(' ');
9
+ }
10
+ else {
11
+ _prompt = args.join(' ');
12
+ }
13
+ if (_prompt === '') {
14
+ _prompt = '';
15
+ }
16
+ const langs = ['french', 'arabic', 'german', 'spanish', 'russian'];
17
+ const inline_articles = await Promise.all(langs.map(async (lang) => {
18
+ const response = await self.ai.run('@cf/meta/m2m100-1.2b', {
19
+ text: _prompt,
20
+ source_lang: lang,
21
+ target_lang: 'english',
22
+ });
23
+ return new TelegramInlineQueryResultArticle(response.translated_text, `${lang}: ${response.translated_text}`);
24
+ }));
25
+ return self.answerInlineQuery(update.inline_query?.id ?? 0, inline_articles);
26
+ };
@@ -1,6 +1,6 @@
1
1
  /// <reference types="@cloudflare/workers-types" />
2
- import BotApi from "./bot_api";
3
- import { Config } from "./types";
2
+ import BotApi from './bot_api';
3
+ import { Config } from './types';
4
4
  export default class Handler {
5
5
  configs: Partial<Config>[];
6
6
  constructor(configs: Partial<Config>[]);
@@ -1,5 +1,5 @@
1
- import { sha256, log } from "./libs";
2
- import { Config, localhost } from "./types";
1
+ import { sha256, log } from './libs';
2
+ import { Config, localhost } from './types';
3
3
  export default class Handler {
4
4
  configs;
5
5
  constructor(configs) {
@@ -12,19 +12,17 @@ export default class Handler {
12
12
  }
13
13
  return this.responses.default();
14
14
  };
15
- postResponse = async (_request, _bot) => _bot?.webhook.token === ""
15
+ postResponse = async (_request, _bot) => _bot?.webhook.token === ''
16
16
  ? this.responses.default()
17
17
  : _request
18
- ? _request
19
- .json()
20
- .then((update) => _bot.update(update))
18
+ ? _request.json().then((update) => _bot.update(update))
21
19
  : this.responses.default();
22
20
  responses = {
23
21
  GET: this.getResponse,
24
22
  POST: this.postResponse,
25
23
  default: () => new Promise(() => new Response()),
26
24
  };
27
- getAccessKeys = async (configs) => Promise.all(configs.map((bot_config) => sha256(bot_config.webhook?.token ?? "").then((hash) => {
25
+ getAccessKeys = async (configs) => Promise.all(configs.map((bot_config) => sha256(bot_config.webhook?.token ?? '').then((hash) => {
28
26
  console.log(hash);
29
27
  return [hash, bot_config];
30
28
  }))).then((result) => Object.fromEntries(result));
@@ -1,29 +1,24 @@
1
- export const sha256 = async (text) => crypto.subtle
2
- .digest("SHA-256", new TextEncoder().encode(text))
3
- .then((array_buffer) => Array.from(new Uint8Array(array_buffer))
4
- .map((b) => b.toString(16).padStart(2, "0"))
5
- .join(""));
1
+ export const sha256 = async (text) => crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)).then((array_buffer) => Array.from(new Uint8Array(array_buffer))
2
+ .map((b) => b.toString(16).padStart(2, '0'))
3
+ .join(''));
6
4
  // format json with line indents and newlines
7
5
  export const prettyJSON = (obj) => JSON.stringify(obj, null, 2);
8
6
  // Generate JSON response
9
7
  export const JSONResponse = (obj, status = 200) => new Response(prettyJSON(obj), {
10
8
  status: status,
11
9
  headers: {
12
- "content-type": "application/json",
10
+ 'content-type': 'application/json',
13
11
  },
14
12
  });
15
13
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
16
14
  export const log = (obj) => console.log(obj) === undefined && obj;
17
15
  export const preTagString = (str) => `<pre>${str}</pre>`;
18
- export const addSearchParams = (url, params = {}) => new URL(`${url.origin}${url.pathname}?${new URLSearchParams(Object.entries(Object.fromEntries([
19
- ...Array.from(url.searchParams.entries()),
20
- ...Object.entries(params),
21
- ]))).toString()}`);
16
+ export const addSearchParams = (url, params = {}) => new URL(`${url.origin}${url.pathname}?${new URLSearchParams(Object.entries(Object.fromEntries([...Array.from(url.searchParams.entries()), ...Object.entries(params)]))).toString()}`);
22
17
  export const responseToJSON = async (response) => response
23
18
  .clone()
24
19
  .text()
25
20
  .then((text) => JSON.parse(text))
26
- .catch(() => log({ error: "Failed to parse JSON of response" }));
21
+ .catch(() => log({ error: 'Failed to parse JSON of response' }));
27
22
  export const undefinedEmpty = (obj) => (obj === undefined ? [] : [obj]);
28
23
  export const fetch_json = async (url) => fetch(url.href)
29
24
  .then((response) => responseToJSON(response))
@@ -1,11 +1,11 @@
1
- import BotApi from "./bot_api";
2
- import Handler from "./handler";
3
- import * as Libs from "./libs";
4
- import TelegramApi from "./telegram_api";
5
- import TelegramBot from "./telegram_bot";
6
- import TelegramCommands from "./telegram_commands";
7
- import TelegramWebhook from "./telegram_webhook";
8
- import * as Types from "./types";
9
- import Webhook from "./webhook";
10
- import worker from "../../worker/src/worker";
11
- export { BotApi, Handler, Libs, TelegramApi, TelegramBot, TelegramCommands, TelegramWebhook, Types, Webhook, worker, };
1
+ import BotApi from './bot_api';
2
+ import Handler from './handler';
3
+ import * as Libs from './libs';
4
+ import TelegramApi from './telegram_api';
5
+ import TelegramBot from './telegram_bot';
6
+ import TelegramCommands from './telegram_commands';
7
+ import TelegramWebhook from './telegram_webhook';
8
+ import * as Types from './types';
9
+ import Webhook from './webhook';
10
+ import worker from '../../worker/src/worker';
11
+ export { BotApi, Handler, Libs, TelegramApi, TelegramBot, TelegramCommands, TelegramWebhook, Types, Webhook, worker };