utilitas 1992.2.2 → 1992.2.4

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.
package/index.mjs CHANGED
@@ -11,6 +11,7 @@ import * as dbio from './lib/dbio.mjs';
11
11
  import * as email from './lib/email.mjs';
12
12
  import * as encryption from './lib/encryption.mjs';
13
13
  import * as event from './lib/event.mjs';
14
+ import * as hal from './lib/hal.mjs';
14
15
  import * as network from './lib/network.mjs';
15
16
  import * as sentinel from './lib/sentinel.mjs';
16
17
  import * as shekel from './lib/shekel.mjs';
@@ -30,7 +31,7 @@ export {
30
31
  // dependencies
31
32
  fileType, math, uuid,
32
33
  // features
33
- bot, cache, callosum, color, dbio, email, encryption, event, manifest,
34
+ bot, cache, callosum, color, dbio, email, encryption, event, hal, manifest,
34
35
  network, sentinel, shekel, shell, shot, sms, storage, tape, uoid, utilitas,
35
36
  };
36
37
 
package/lib/bot.mjs CHANGED
@@ -16,29 +16,47 @@ const end = async (options) => bot && bot.stop(options?.signal);
16
16
  let bot;
17
17
 
18
18
  const questions = [{
19
- q: ['THE THREE LAWS'],
19
+ q: ['/THE THREE LAWS'],
20
20
  a: ['- A robot may not injure a human being or, through inaction, allow a human being to come to harm.',
21
21
  '- A robot must obey the orders given it by human beings except where such orders would conflict with the First Law.',
22
22
  '- A robot must protect its own existence as long as such protection does not conflict with the First or Second Laws.'].join('\n'),
23
23
  }, {
24
- q: ['The Ultimate Question of Life, the Universe, and Everything',
24
+ q: ['/The Ultimate Question of Life, the Universe, and Everything',
25
25
  'The answer to life the universe and everything'],
26
26
  a: '42',
27
27
  }];
28
28
 
29
+ const handleText = async (ctx, next) => {
30
+ let key;
31
+ if (ctx.update.message) { key = 'message'; }
32
+ else if (ctx.update.edited_message) { key = 'edited_message'; }
33
+ questions.map(s => {
34
+ s.q.map(x => iCmp(x, ctx.update[key].text) && ctx.reply(s.a))
35
+ });
36
+ for (let name in bot.ai || []) {
37
+ Array.isArray(bot.ai) && (name = null);
38
+ (async () => {
39
+ let resp;
40
+ try {
41
+ resp = (await bot.ai[name].send(
42
+ ctx.update[key].text, { session: ctx.update[key].chat.id }
43
+ )).responseRendered;
44
+ } catch (err) { resp = err.message; log(err); }
45
+ ctx.reply(`${name ? `🤖️ ${name}: ` : ''}${resp}\n\n---`);
46
+ })();
47
+ }
48
+ next && await next();
49
+ };
50
+
29
51
  const subconscious = {
30
52
  run: true, name: 'subconscious', func: async (bot) => {
31
53
  bot.use(async (ctx, next) => {
32
54
  log(`Updated: ${ctx.update.update_id}`);
33
55
  process.stdout.write(`${JSON.stringify(ctx.update)}\n`);
56
+ ctx.update.edited_message && await handleText(ctx);
34
57
  await next();
35
58
  });
36
- bot.on('text', async (ctx, next) => {
37
- questions.map(s => {
38
- s.q.map(x => iCmp(x, ctx.update.message.text) && ctx.reply(s.a))
39
- });
40
- await next();
41
- });
59
+ bot.on('text', handleText);
42
60
  },
43
61
  };
44
62
 
@@ -62,6 +80,7 @@ const init = async (options) => {
62
80
  // https://github.com/telegraf/telegraf
63
81
  const { Telegraf } = await need('telegraf', { raw: true });
64
82
  bot = new Telegraf(options?.botToken);
83
+ bot.ai = options?.ai; // Should be an array of a map of AIs.
65
84
  const [mods, pmsTrain] = [[{
66
85
  ...subconscious, run: !options?.silent
67
86
  }, ...ensureArray(options?.skill)], []];
package/lib/hal.mjs ADDED
@@ -0,0 +1,61 @@
1
+ import { ensureString, renderText, throwError } from "./utilitas.mjs";
2
+
3
+ const _NEED = ['@waylaidwanderer/chatgpt-api'];
4
+
5
+ const init = async (options) => {
6
+ const sessions = {};
7
+ let provider, engine, client;
8
+ switch ((provider = ensureString(options?.provider, { case: 'UP' }))) {
9
+ case 'BING':
10
+ // https://github.com/waylaidwanderer/node-chatgpt-api/blob/main/demos/use-bing-client.js
11
+ engine = (await import('@waylaidwanderer/chatgpt-api')).BingAIClient;
12
+ client = new engine(options?.clientOptions);
13
+ break;
14
+ case 'CHATGPT':
15
+ // https://github.com/waylaidwanderer/node-chatgpt-api/blob/main/demos/use-client.js
16
+ engine = (await import('@waylaidwanderer/chatgpt-api')).ChatGPTClient;
17
+ client = new engine(options?.clientOptions?.apiKey, {
18
+ modelOptions: {
19
+ model: 'gpt-3.5-turbo',
20
+ ...options?.clientOptions?.modelOptions || {}
21
+ }, ...options?.clientOptions || {}
22
+ }, options?.cacheOptions);
23
+ break;
24
+ default:
25
+ throwError('Invalid AI provider.', 500);
26
+ }
27
+ const send = async (message, options) => {
28
+ const _session = options?.session || '_';
29
+ sessions[_session] = await client.sendMessage(message, {
30
+ conversationSignature: sessions?.[_session]?.conversationSignature,
31
+ conversationId: sessions?.[_session]?.conversationId,
32
+ clientId: sessions?.[_session]?.clientId,
33
+ invocationId: sessions?.[_session]?.invocationId,
34
+ ...options || {},
35
+ });
36
+ sessions[_session].responseRendered = renderText(
37
+ sessions[_session].response
38
+ );
39
+ const cards = sessions[_session]?.details?.adaptiveCards || [];
40
+ if (cards.length) {
41
+ sessions[_session].responseRendered += `\n\n***\nLearn more:\n`;
42
+ sessions[_session].responseRendered += cards[0].body[0].text.split('\n\n')[0];
43
+ }
44
+ const sources = sessions[_session]?.details?.sourceAttributions || [];
45
+ if (sources.length) {
46
+ sessions[_session].responseRendered += `\n\n***\nSource:`;
47
+ }
48
+ for (let i in sources) {
49
+ sessions[_session].responseRendered
50
+ += `\n${~~i + 1}. [${sources[i].providerDisplayName}](${sources[i].seeMoreUrl})`;
51
+ }
52
+ return sessions[_session];
53
+ };
54
+ return { engine, client, send };
55
+ };
56
+
57
+ export default init;
58
+ export {
59
+ _NEED,
60
+ init,
61
+ };
package/lib/manifest.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  const manifest = {
2
2
  "name": "utilitas",
3
3
  "description": "Just another common utility for JavaScript.",
4
- "version": "1992.2.2",
4
+ "version": "1992.2.4",
5
5
  "private": false,
6
6
  "homepage": "https://github.com/Leask/utilitas",
7
7
  "main": "index.mjs",
@@ -22,6 +22,7 @@ const manifest = {
22
22
  },
23
23
  "devDependencies": {
24
24
  "@sentry/node": "^7.37.1",
25
+ "@waylaidwanderer/chatgpt-api": "^1.22.5",
25
26
  "browserify-fs": "^1.0.0",
26
27
  "buffer": "^6.0.3",
27
28
  "fast-geoip": "^1.1.88",
package/lib/utilitas.mjs CHANGED
@@ -442,10 +442,14 @@ const fullLengthLog = (string, options) => {
442
442
  return { string, maxLength };
443
443
  };
444
444
 
445
+ const lineSplit = (string, options) => {
446
+ const str = ensureString(string, options);
447
+ return str.length ? str.split(options?.separator || /\r\n|\n\r|\r|\n/) : [];
448
+ };
449
+
445
450
  const renderCode = (code, options) => {
446
451
  let i = 0;
447
- const strCode = ensureString(code, options);
448
- const arrCode = strCode.length ? strCode.split(/\r\n|\n\r|\r|\n/) : [];
452
+ const arrCode = Array.isArray(code) ? code : lineSplit(code);
449
453
  const bits = String(arrCode.length).length;
450
454
  const s = options?.separator ?? '|';
451
455
  return arrCode.map(
@@ -453,6 +457,24 @@ const renderCode = (code, options) => {
453
457
  ).join('\n');
454
458
  };
455
459
 
460
+ const renderText = (text, options) => {
461
+ const [arrText, code, result] = [lineSplit(text), [], []];
462
+ arrText.map(line => {
463
+ const codeBlock = /^```/.test(line);
464
+ if (codeBlock && !code.length) { // start code block
465
+ code.push(line);
466
+ } else if (codeBlock && code.length) { // end code block
467
+ result.push(code.shift(), renderCode(code.join('\n'), options), line);
468
+ code.length = 0;
469
+ } else if (code.length) { // in code block
470
+ code.push(line);
471
+ } else { // normal text
472
+ result.push(line);
473
+ }
474
+ });
475
+ return result.join('\n');
476
+ };
477
+
456
478
  const range = (from, to, options) => {
457
479
  options = options || {};
458
480
  options.base = ensureInt(options.base, { min: 0 });
@@ -620,6 +642,7 @@ export {
620
642
  isNull,
621
643
  isSet,
622
644
  isUndefined,
645
+ lineSplit,
623
646
  log,
624
647
  makeStringByLength,
625
648
  mapKeys,
@@ -635,6 +658,7 @@ export {
635
658
  purgeEmoji,
636
659
  range,
637
660
  renderCode,
661
+ renderText,
638
662
  resolve,
639
663
  rotate,
640
664
  shiftTime,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "utilitas",
3
3
  "description": "Just another common utility for JavaScript.",
4
- "version": "1992.2.2",
4
+ "version": "1992.2.4",
5
5
  "private": false,
6
6
  "homepage": "https://github.com/Leask/utilitas",
7
7
  "main": "index.mjs",
@@ -33,6 +33,7 @@
33
33
  },
34
34
  "devDependencies": {
35
35
  "@sentry/node": "^7.37.1",
36
+ "@waylaidwanderer/chatgpt-api": "^1.22.5",
36
37
  "browserify-fs": "^1.0.0",
37
38
  "buffer": "^6.0.3",
38
39
  "fast-geoip": "^1.1.88",