chz-telegram-bot 0.0.43 → 0.0.45

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 (137) hide show
  1. package/entities/actions/commandAction.ts +2 -0
  2. package/entities/actions/scheduledAction.ts +14 -3
  3. package/entities/botInstance.ts +8 -5
  4. package/entities/context/chatContext.ts +17 -8
  5. package/entities/context/messageContext.ts +21 -14
  6. package/entities/incomingMessage.ts +1 -0
  7. package/package.json +29 -29
  8. package/services/telegramApi.ts +6 -4
  9. package/dist/entities/actionExecutionResult.d.ts +0 -7
  10. package/dist/entities/actionExecutionResult.d.ts.map +0 -1
  11. package/dist/entities/actionExecutionResult.js +0 -10
  12. package/dist/entities/actions/commandAction.d.ts +0 -23
  13. package/dist/entities/actions/commandAction.d.ts.map +0 -1
  14. package/dist/entities/actions/commandAction.js +0 -89
  15. package/dist/entities/actions/scheduledAction.d.ts +0 -24
  16. package/dist/entities/actions/scheduledAction.d.ts.map +0 -1
  17. package/dist/entities/actions/scheduledAction.js +0 -70
  18. package/dist/entities/botInstance.d.ts +0 -31
  19. package/dist/entities/botInstance.d.ts.map +0 -1
  20. package/dist/entities/botInstance.js +0 -103
  21. package/dist/entities/cachedStateFactory.d.ts +0 -7
  22. package/dist/entities/cachedStateFactory.d.ts.map +0 -1
  23. package/dist/entities/cachedStateFactory.js +0 -10
  24. package/dist/entities/commandTriggerCheckResult.d.ts +0 -10
  25. package/dist/entities/commandTriggerCheckResult.d.ts.map +0 -1
  26. package/dist/entities/commandTriggerCheckResult.js +0 -23
  27. package/dist/entities/context/chatContext.d.ts +0 -52
  28. package/dist/entities/context/chatContext.d.ts.map +0 -1
  29. package/dist/entities/context/chatContext.js +0 -64
  30. package/dist/entities/context/messageContext.d.ts +0 -59
  31. package/dist/entities/context/messageContext.d.ts.map +0 -1
  32. package/dist/entities/context/messageContext.js +0 -77
  33. package/dist/entities/incomingMessage.d.ts +0 -14
  34. package/dist/entities/incomingMessage.d.ts.map +0 -1
  35. package/dist/entities/incomingMessage.js +0 -43
  36. package/dist/entities/responses/imageMessage.d.ts +0 -16
  37. package/dist/entities/responses/imageMessage.d.ts.map +0 -1
  38. package/dist/entities/responses/imageMessage.js +0 -17
  39. package/dist/entities/responses/reaction.d.ts +0 -13
  40. package/dist/entities/responses/reaction.d.ts.map +0 -1
  41. package/dist/entities/responses/reaction.js +0 -15
  42. package/dist/entities/responses/textMessage.d.ts +0 -15
  43. package/dist/entities/responses/textMessage.d.ts.map +0 -1
  44. package/dist/entities/responses/textMessage.js +0 -17
  45. package/dist/entities/responses/unpin.d.ts +0 -11
  46. package/dist/entities/responses/unpin.d.ts.map +0 -1
  47. package/dist/entities/responses/unpin.js +0 -14
  48. package/dist/entities/responses/videoMessage.d.ts +0 -16
  49. package/dist/entities/responses/videoMessage.d.ts.map +0 -1
  50. package/dist/entities/responses/videoMessage.js +0 -17
  51. package/dist/entities/states/actionStateBase.d.ts +0 -6
  52. package/dist/entities/states/actionStateBase.d.ts.map +0 -1
  53. package/dist/entities/states/actionStateBase.js +0 -10
  54. package/dist/entities/taskRecord.d.ts +0 -8
  55. package/dist/entities/taskRecord.d.ts.map +0 -1
  56. package/dist/entities/taskRecord.js +0 -11
  57. package/dist/helpers/builders/commandActionBuilder.d.ts +0 -69
  58. package/dist/helpers/builders/commandActionBuilder.d.ts.map +0 -1
  59. package/dist/helpers/builders/commandActionBuilder.js +0 -96
  60. package/dist/helpers/builders/scheduledActionBuilder.d.ts +0 -60
  61. package/dist/helpers/builders/scheduledActionBuilder.d.ts.map +0 -1
  62. package/dist/helpers/builders/scheduledActionBuilder.js +0 -82
  63. package/dist/helpers/inverseRecord.d.ts +0 -2
  64. package/dist/helpers/inverseRecord.d.ts.map +0 -1
  65. package/dist/helpers/inverseRecord.js +0 -6
  66. package/dist/helpers/noop.d.ts +0 -6
  67. package/dist/helpers/noop.d.ts.map +0 -1
  68. package/dist/helpers/noop.js +0 -14
  69. package/dist/helpers/reverseMap.d.ts +0 -2
  70. package/dist/helpers/reverseMap.d.ts.map +0 -1
  71. package/dist/helpers/reverseMap.js +0 -6
  72. package/dist/helpers/reverseRecord.d.ts +0 -2
  73. package/dist/helpers/reverseRecord.d.ts.map +0 -1
  74. package/dist/helpers/reverseRecord.js +0 -6
  75. package/dist/helpers/timeConvertions.d.ts +0 -5
  76. package/dist/helpers/timeConvertions.d.ts.map +0 -1
  77. package/dist/helpers/timeConvertions.js +0 -14
  78. package/dist/helpers/toArray.d.ts +0 -2
  79. package/dist/helpers/toArray.d.ts.map +0 -1
  80. package/dist/helpers/toArray.js +0 -6
  81. package/dist/index.d.ts +0 -10
  82. package/dist/index.d.ts.map +0 -1
  83. package/dist/index.js +0 -29
  84. package/dist/main.d.ts +0 -35
  85. package/dist/main.d.ts.map +0 -1
  86. package/dist/main.js +0 -43
  87. package/dist/services/jsonFileStorage.d.ts +0 -22
  88. package/dist/services/jsonFileStorage.d.ts.map +0 -1
  89. package/dist/services/jsonFileStorage.js +0 -102
  90. package/dist/services/logger.d.ts +0 -9
  91. package/dist/services/logger.d.ts.map +0 -1
  92. package/dist/services/logger.js +0 -28
  93. package/dist/services/taskScheduler.d.ts +0 -11
  94. package/dist/services/taskScheduler.d.ts.map +0 -1
  95. package/dist/services/taskScheduler.js +0 -33
  96. package/dist/services/telegramApi.d.ts +0 -36
  97. package/dist/services/telegramApi.d.ts.map +0 -1
  98. package/dist/services/telegramApi.js +0 -102
  99. package/dist/types/actionState.d.ts +0 -5
  100. package/dist/types/actionState.d.ts.map +0 -1
  101. package/dist/types/actionState.js +0 -2
  102. package/dist/types/actionWithState.d.ts +0 -9
  103. package/dist/types/actionWithState.d.ts.map +0 -1
  104. package/dist/types/actionWithState.js +0 -2
  105. package/dist/types/cachedValueAccessor.d.ts +0 -2
  106. package/dist/types/cachedValueAccessor.d.ts.map +0 -1
  107. package/dist/types/cachedValueAccessor.js +0 -2
  108. package/dist/types/commandCondition.d.ts +0 -4
  109. package/dist/types/commandCondition.d.ts.map +0 -1
  110. package/dist/types/commandCondition.js +0 -2
  111. package/dist/types/commandTrigger.d.ts +0 -3
  112. package/dist/types/commandTrigger.d.ts.map +0 -1
  113. package/dist/types/commandTrigger.js +0 -2
  114. package/dist/types/daysOfTheWeek.d.ts +0 -10
  115. package/dist/types/daysOfTheWeek.d.ts.map +0 -1
  116. package/dist/types/daysOfTheWeek.js +0 -13
  117. package/dist/types/handlers.d.ts +0 -17
  118. package/dist/types/handlers.d.ts.map +0 -1
  119. package/dist/types/handlers.js +0 -2
  120. package/dist/types/messageSendingOptions.d.ts +0 -7
  121. package/dist/types/messageSendingOptions.d.ts.map +0 -1
  122. package/dist/types/messageSendingOptions.js +0 -2
  123. package/dist/types/messageTypes.d.ts +0 -16
  124. package/dist/types/messageTypes.d.ts.map +0 -1
  125. package/dist/types/messageTypes.js +0 -17
  126. package/dist/types/replyMessage.d.ts +0 -8
  127. package/dist/types/replyMessage.d.ts.map +0 -1
  128. package/dist/types/replyMessage.js +0 -2
  129. package/dist/types/response.d.ts +0 -27
  130. package/dist/types/response.d.ts.map +0 -1
  131. package/dist/types/response.js +0 -10
  132. package/dist/types/storage.d.ts +0 -12
  133. package/dist/types/storage.d.ts.map +0 -1
  134. package/dist/types/storage.js +0 -2
  135. package/dist/types/timeValues.d.ts +0 -11
  136. package/dist/types/timeValues.d.ts.map +0 -1
  137. package/dist/types/timeValues.js +0 -2
package/dist/main.js DELETED
@@ -1,43 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.startBot = startBot;
4
- exports.stopBots = stopBots;
5
- const promises_1 = require("fs/promises");
6
- const logger_1 = require("./services/logger");
7
- const taskScheduler_1 = require("./services/taskScheduler");
8
- const botInstance_1 = require("./entities/botInstance");
9
- const bots = [];
10
- function log(text) {
11
- logger_1.Logger.logWithTraceId('ALL BOTS', 'System:Bot', 'System', text);
12
- }
13
- /**
14
- * Starts bot
15
- */
16
- async function startBot(options) {
17
- const token = await (0, promises_1.readFile)(options.tokenFilePath, 'utf8');
18
- const bot = new botInstance_1.BotInstance({
19
- name: options.name,
20
- token,
21
- commands: options.commands,
22
- scheduled: options.scheduled,
23
- chats: options.chats,
24
- storageClient: options.storageClient,
25
- storagePath: options.storagePath,
26
- scheduledPeriod: options.scheduledPeriod,
27
- verboseLoggingForIncomingMessage: options.verboseLoggingForIncomingMessage
28
- });
29
- bots.push(bot);
30
- return bot;
31
- }
32
- /**
33
- * Terminates all scheduled tasks, closes storage connections and stops all bots.
34
- */
35
- async function stopBots(reason) {
36
- log(`Recieved termination code: ${reason}`);
37
- taskScheduler_1.Scheduler.stopAll();
38
- log('Acquiring storage semaphore...');
39
- log('Stopping bots...');
40
- for (const bot of bots) {
41
- await bot.stop(reason);
42
- }
43
- }
@@ -1,22 +0,0 @@
1
- import { IStorageClient } from '../types/storage';
2
- import { ActionExecutionResult } from '../entities/actionExecutionResult';
3
- import { IActionState } from '../types/actionState';
4
- import { IActionWithState, ActionKey } from '../types/actionWithState';
5
- export declare class JsonFileStorage implements IStorageClient {
6
- private locks;
7
- private cache;
8
- private storagePath;
9
- private botName;
10
- constructor(botName: string, actions: IActionWithState[], path?: string);
11
- private lock;
12
- private loadInternal;
13
- private save;
14
- private buidPathFromKey;
15
- load<TActionState extends IActionState>(key: ActionKey): Promise<Record<number, TActionState>>;
16
- saveMetadata(actions: IActionWithState[], botName: string): Promise<void>;
17
- getActionState<TActionState extends IActionState>(action: IActionWithState, chatId: number): Promise<TActionState>;
18
- saveActionExecutionResult(action: IActionWithState, chatId: number, transactionResult: ActionExecutionResult): Promise<void>;
19
- close(): Promise<void>;
20
- updateStateFor<TActionState extends IActionState>(action: IActionWithState, chatId: number, update: (state: TActionState) => Promise<void>): Promise<void>;
21
- }
22
- //# sourceMappingURL=jsonFileStorage.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"jsonFileStorage.d.ts","sourceRoot":"","sources":["../../services/jsonFileStorage.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AAC1E,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAEvE,qBAAa,eAAgB,YAAW,cAAc;IAClD,OAAO,CAAC,KAAK,CAAmC;IAChD,OAAO,CAAC,KAAK,CAA4C;IACzD,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,OAAO,CAAS;gBAEZ,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,EAAE,IAAI,CAAC,EAAE,MAAM;YAgBzD,IAAI;YAgBJ,YAAY;YAqBZ,IAAI;IAalB,OAAO,CAAC,eAAe;IAOjB,IAAI,CAAC,YAAY,SAAS,YAAY,EAAE,GAAG,EAAE,SAAS;IAMtD,YAAY,CAAC,OAAO,EAAE,gBAAgB,EAAE,EAAE,OAAO,EAAE,MAAM;IAUzD,cAAc,CAAC,YAAY,SAAS,YAAY,EAClD,MAAM,EAAE,gBAAgB,EACxB,MAAM,EAAE,MAAM;IAYZ,yBAAyB,CAC3B,MAAM,EAAE,gBAAgB,EACxB,MAAM,EAAE,MAAM,EACd,iBAAiB,EAAE,qBAAqB;IAYtC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAMtB,cAAc,CAAC,YAAY,SAAS,YAAY,EAClD,MAAM,EAAE,gBAAgB,EACxB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC;CAcrD"}
@@ -1,102 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.JsonFileStorage = void 0;
4
- const fs_1 = require("fs");
5
- const path_1 = require("path");
6
- const promises_1 = require("fs/promises");
7
- const async_sema_1 = require("async-sema");
8
- class JsonFileStorage {
9
- constructor(botName, actions, path) {
10
- this.locks = new Map();
11
- this.cache = new Map();
12
- this.botName = botName;
13
- this.storagePath = path ?? 'storage';
14
- if (!(0, fs_1.existsSync)(`${this.storagePath}/${this.botName}/`)) {
15
- (0, fs_1.mkdirSync)(`${this.storagePath}/${this.botName}/`, {
16
- recursive: true
17
- });
18
- }
19
- for (const action of actions) {
20
- this.locks.set(action.key, new async_sema_1.Sema(1));
21
- }
22
- }
23
- async lock(key, action) {
24
- const lock = this.locks.get(key);
25
- if (!lock) {
26
- throw new Error(`Lock for action ${key} not found`);
27
- }
28
- await lock.acquire();
29
- try {
30
- return await action();
31
- }
32
- finally {
33
- lock.release();
34
- }
35
- }
36
- async loadInternal(key) {
37
- if (!this.cache.has(key)) {
38
- const targetPath = this.buidPathFromKey(key);
39
- if (!(0, fs_1.existsSync)(targetPath)) {
40
- return {};
41
- }
42
- const fileContent = await (0, promises_1.readFile)(targetPath, 'utf8');
43
- if (fileContent) {
44
- const data = JSON.parse(fileContent);
45
- this.cache.set(key, data);
46
- }
47
- }
48
- return (this.cache.get(key) ?? {});
49
- }
50
- async save(data, key) {
51
- this.cache.delete(key);
52
- const targetPath = this.buidPathFromKey(key);
53
- const folderName = (0, path_1.dirname)(targetPath);
54
- if (!(0, fs_1.existsSync)(folderName)) {
55
- await (0, promises_1.mkdir)(folderName, { recursive: true });
56
- }
57
- await (0, promises_1.writeFile)(targetPath, JSON.stringify(data), { flag: 'w+' });
58
- }
59
- buidPathFromKey(key) {
60
- return `${this.storagePath}/${this.botName}/${key.replaceAll(':', '/')}.json`;
61
- }
62
- async load(key) {
63
- return await this.lock(key, async () => {
64
- return this.loadInternal(key);
65
- });
66
- }
67
- async saveMetadata(actions, botName) {
68
- const targetPath = this.buidPathFromKey(`Metadata-${botName}`);
69
- await (0, promises_1.writeFile)(targetPath, JSON.stringify(actions), {
70
- flag: 'w+'
71
- });
72
- }
73
- async getActionState(action, chatId) {
74
- return await this.lock(action.key, async () => {
75
- const data = await this.loadInternal(action.key);
76
- return Object.assign(action.stateConstructor(), data[chatId]);
77
- });
78
- }
79
- async saveActionExecutionResult(action, chatId, transactionResult) {
80
- await this.lock(action.key, async () => {
81
- const data = await this.loadInternal(action.key);
82
- if (transactionResult.shouldUpdate) {
83
- data[chatId] = transactionResult.data;
84
- await this.save(data, action.key);
85
- }
86
- });
87
- }
88
- async close() {
89
- for (const lock of this.locks.values()) {
90
- await lock.acquire();
91
- }
92
- }
93
- async updateStateFor(action, chatId, update) {
94
- await this.lock(action.key, async () => {
95
- const data = await this.loadInternal(action.key);
96
- const state = Object.assign(action.stateConstructor(), data[chatId]);
97
- await update(state);
98
- await this.save(data, action.key);
99
- });
100
- }
101
- }
102
- exports.JsonFileStorage = JsonFileStorage;
@@ -1,9 +0,0 @@
1
- declare class JsonLogger {
2
- private serializeError;
3
- logObjectWithTraceId(botName: string, traceId: string | number, chatName: string, data: any): void;
4
- logWithTraceId(botName: string, traceId: string | number, chatName: string, text: string): void;
5
- errorWithTraceId<TData>(botName: string, traceId: string | number, chatName: string, errorObj: unknown, extraData?: TData | undefined): void;
6
- }
7
- export declare const Logger: JsonLogger;
8
- export {};
9
- //# sourceMappingURL=logger.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../services/logger.ts"],"names":[],"mappings":"AAAA,cAAM,UAAU;IAEZ,OAAO,CAAC,cAAc;IAQtB,oBAAoB,CAChB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,GAAG,MAAM,EACxB,QAAQ,EAAE,MAAM,EAEhB,IAAI,EAAE,GAAG;IAQb,cAAc,CACV,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,GAAG,MAAM,EACxB,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM;IAOhB,gBAAgB,CAAC,KAAK,EAClB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,GAAG,MAAM,EACxB,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,OAAO,EACjB,SAAS,CAAC,EAAE,KAAK,GAAG,SAAS;CAQpC;AAED,eAAO,MAAM,MAAM,YAAmB,CAAC"}
@@ -1,28 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Logger = void 0;
4
- class JsonLogger {
5
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6
- serializeError(error) {
7
- const plainObject = {};
8
- Object.getOwnPropertyNames(error).forEach(function (key) {
9
- plainObject[key] = error[key];
10
- });
11
- return JSON.stringify(plainObject);
12
- }
13
- logObjectWithTraceId(botName, traceId, chatName,
14
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
- data) {
16
- data.botName = botName;
17
- data.traceId = traceId;
18
- data.chatName = chatName;
19
- console.log(data);
20
- }
21
- logWithTraceId(botName, traceId, chatName, text) {
22
- console.log(`{"botName":"${botName}","traceId":"${traceId}","chatName":"${chatName}","text":"${text}"}`);
23
- }
24
- errorWithTraceId(botName, traceId, chatName, errorObj, extraData) {
25
- console.error(`{"botName":"${botName}","traceId":"${traceId}","chatName":"${chatName}","error":${this.serializeError(errorObj)}${extraData ? `,"extraData":${JSON.stringify(extraData)}` : ''}}`);
26
- }
27
- }
28
- exports.Logger = new JsonLogger();
@@ -1,11 +0,0 @@
1
- import { TaskRecord } from '../entities/taskRecord';
2
- import { Milliseconds } from '../types/timeValues';
3
- declare class TaskScheduler {
4
- activeTasks: TaskRecord[];
5
- stopAll(): void;
6
- createTask(name: string, action: () => void, interval: Milliseconds, executeRightAway: boolean, ownerName: string): void;
7
- createOnetimeTask(name: string, action: () => void, delay: Milliseconds, ownerName: string): void;
8
- }
9
- export declare const Scheduler: TaskScheduler;
10
- export {};
11
- //# sourceMappingURL=taskScheduler.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"taskScheduler.d.ts","sourceRoot":"","sources":["../../services/taskScheduler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGnD,cAAM,aAAa;IACf,WAAW,EAAE,UAAU,EAAE,CAAM;IAE/B,OAAO;IAMP,UAAU,CACN,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,IAAI,EAClB,QAAQ,EAAE,YAAY,EACtB,gBAAgB,EAAE,OAAO,EACzB,SAAS,EAAE,MAAM;IAmBrB,iBAAiB,CACb,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,IAAI,EAClB,KAAK,EAAE,YAAY,EACnB,SAAS,EAAE,MAAM;CAoBxB;AAED,eAAO,MAAM,SAAS,eAAsB,CAAC"}
@@ -1,33 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Scheduler = void 0;
4
- const taskRecord_1 = require("../entities/taskRecord");
5
- const logger_1 = require("./logger");
6
- class TaskScheduler {
7
- constructor() {
8
- this.activeTasks = [];
9
- }
10
- stopAll() {
11
- this.activeTasks.forEach((task) => {
12
- clearInterval(task.taskId);
13
- });
14
- }
15
- createTask(name, action, interval, executeRightAway, ownerName) {
16
- const taskId = setInterval(action, interval);
17
- const task = new taskRecord_1.TaskRecord(name, taskId, interval);
18
- if (executeRightAway) {
19
- setImmediate(action);
20
- }
21
- logger_1.Logger.logWithTraceId(ownerName, `System:TaskScheduler-${ownerName}-${name}`, 'System', `Created task [${taskId}]${name}, that will run every ${interval}ms.`);
22
- this.activeTasks.push(task);
23
- }
24
- createOnetimeTask(name, action, delay, ownerName) {
25
- const actionWrapper = () => {
26
- logger_1.Logger.logWithTraceId(ownerName, `System:TaskScheduler-${ownerName}-${name}`, 'System', `Executing delayed oneshot [${taskId}]${name}`);
27
- action();
28
- };
29
- const taskId = setTimeout(actionWrapper, delay);
30
- logger_1.Logger.logWithTraceId(ownerName, `System:TaskScheduler-${ownerName}-${name}`, 'System', `Created oneshot task [${taskId}]${name}, that will run in ${delay}ms.`);
31
- }
32
- }
33
- exports.Scheduler = new TaskScheduler();
@@ -1,36 +0,0 @@
1
- import { ChatContext } from '../entities/context/chatContext';
2
- import { MessageContext } from '../entities/context/messageContext';
3
- import { IStorageClient } from '../types/storage';
4
- import { Reaction } from '../entities/responses/reaction';
5
- import { IncomingMessage } from '../entities/incomingMessage';
6
- import { BotResponse } from '../types/response';
7
- import { UnpinResponse } from '../entities/responses/unpin';
8
- import { TextMessage } from '../entities/responses/textMessage';
9
- import { VideoMessage } from '../entities/responses/videoMessage';
10
- import { ImageMessage } from '../entities/responses/imageMessage';
11
- import { Telegram } from 'telegraf/typings/telegram';
12
- import { ScheduledAction } from '../entities/actions/scheduledAction';
13
- import { IActionState } from '../types/actionState';
14
- import { CommandAction } from '../entities/actions/commandAction';
15
- export declare class TelegramApiService {
16
- isFlushing: boolean;
17
- messageQueue: BotResponse[];
18
- botName: string;
19
- telegram: Telegram;
20
- chats: Record<number, string>;
21
- storage: IStorageClient;
22
- interactions: IBotApiInteractions;
23
- constructor(botName: string, telegram: Telegram, storage: IStorageClient, chats: Record<string, number>);
24
- flushResponses(): Promise<void>;
25
- private pinIfShould;
26
- private processResponse;
27
- private enqueue;
28
- createContextForMessage<TActionState extends IActionState>(incomingMessage: IncomingMessage, command: CommandAction<TActionState>): MessageContext<TActionState>;
29
- createContextForChat<TActionState extends IActionState>(chatId: number, scheduledAction: ScheduledAction<TActionState>): ChatContext<TActionState>;
30
- }
31
- export interface IBotApiInteractions {
32
- respond: (response: TextMessage | VideoMessage | ImageMessage) => void;
33
- react: (reaction: Reaction) => void;
34
- unpin: (unpinMessage: UnpinResponse) => void;
35
- }
36
- //# sourceMappingURL=telegramApi.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"telegramApi.d.ts","sourceRoot":"","sources":["../../services/telegramApi.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAEpE,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,OAAO,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAiB,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,mCAAmC,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAClE,OAAO,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAGrD,OAAO,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAIlE,qBAAa,kBAAkB;IAC3B,UAAU,UAAS;IACnB,YAAY,EAAE,WAAW,EAAE,CAAM;IAEjC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,QAAQ,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B,OAAO,EAAE,cAAc,CAAC;IACxB,YAAY,EAAE,mBAAmB,CAAC;gBAG9B,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,cAAc,EACvB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAc3B,cAAc;YA2BN,WAAW;YAqBX,eAAe;IA2E7B,OAAO,CAAC,OAAO;IAIf,uBAAuB,CAAC,YAAY,SAAS,YAAY,EACrD,eAAe,EAAE,eAAe,EAChC,OAAO,EAAE,aAAa,CAAC,YAAY,CAAC;IAWxC,oBAAoB,CAAC,YAAY,SAAS,YAAY,EAClD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,eAAe,CAAC,YAAY,CAAC;CAYrD;AAED,MAAM,WAAW,mBAAmB;IAChC,OAAO,EAAE,CAAC,QAAQ,EAAE,WAAW,GAAG,YAAY,GAAG,YAAY,KAAK,IAAI,CAAC;IACvE,KAAK,EAAE,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;IACpC,KAAK,EAAE,CAAC,YAAY,EAAE,aAAa,KAAK,IAAI,CAAC;CAChD"}
@@ -1,102 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TelegramApiService = void 0;
4
- const chatContext_1 = require("../entities/context/chatContext");
5
- const messageContext_1 = require("../entities/context/messageContext");
6
- const inverseRecord_1 = require("../helpers/inverseRecord");
7
- const logger_1 = require("./logger");
8
- const promises_1 = require("timers/promises");
9
- const TELEGRAM_RATELIMIT_DELAY = 35;
10
- class TelegramApiService {
11
- constructor(botName, telegram, storage, chats) {
12
- this.isFlushing = false;
13
- this.messageQueue = [];
14
- this.telegram = telegram;
15
- this.botName = botName;
16
- this.chats = (0, inverseRecord_1.inverseRecord)(chats);
17
- this.storage = storage;
18
- this.interactions = {
19
- react: (reaction) => this.enqueue(reaction),
20
- respond: (response) => this.enqueue(response),
21
- unpin: (unpinMessage) => this.enqueue(unpinMessage)
22
- };
23
- }
24
- async flushResponses() {
25
- if (this.isFlushing)
26
- return;
27
- this.isFlushing = true;
28
- while (this.messageQueue.length) {
29
- const message = this.messageQueue.pop();
30
- if (!message)
31
- break;
32
- try {
33
- await this.processResponse(message);
34
- await (0, promises_1.setTimeout)(TELEGRAM_RATELIMIT_DELAY);
35
- }
36
- catch (error) {
37
- logger_1.Logger.errorWithTraceId(this.botName, message.traceId, this.chats[message.chatId], error, message);
38
- }
39
- }
40
- this.isFlushing = false;
41
- }
42
- async pinIfShould(response, sentMessage) {
43
- if (response.shouldPin) {
44
- await this.telegram.pinChatMessage(response.chatId, sentMessage.message_id, { disable_notification: true });
45
- await this.storage.updateStateFor(response.action, response.chatId, async (state) => {
46
- state.pinnedMessages.push(sentMessage.message_id);
47
- });
48
- }
49
- }
50
- async processResponse(response) {
51
- let sentMessage;
52
- switch (response.kind) {
53
- case 'text':
54
- sentMessage = await this.telegram.sendMessage(response.chatId, response.content, {
55
- reply_to_message_id: response.replyId,
56
- parse_mode: 'MarkdownV2',
57
- disable_web_page_preview: response.disableWebPreview
58
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
- });
60
- await this.pinIfShould(response, sentMessage);
61
- break;
62
- case 'image':
63
- sentMessage = await this.telegram.sendPhoto(response.chatId, response.content, response.replyId
64
- ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
65
- { reply_to_message_id: response.replyId }
66
- : undefined);
67
- await this.pinIfShould(response, sentMessage);
68
- break;
69
- case 'video':
70
- sentMessage = await this.telegram.sendVideo(response.chatId, response.content, response.replyId
71
- ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
72
- { reply_to_message_id: response.replyId }
73
- : undefined);
74
- await this.pinIfShould(response, sentMessage);
75
- break;
76
- case 'react':
77
- await this.telegram.setMessageReaction(response.chatId, response.messageId, [
78
- {
79
- type: 'emoji',
80
- emoji: response.emoji
81
- }
82
- ], true);
83
- return;
84
- case 'unpin':
85
- await this.telegram.unpinChatMessage(response.chatId, response.messageId);
86
- await this.storage.updateStateFor(response.action, response.chatId, async (state) => {
87
- state.pinnedMessages = state.pinnedMessages.filter((x) => x != response.messageId);
88
- });
89
- break;
90
- }
91
- }
92
- enqueue(response) {
93
- this.messageQueue.push(response);
94
- }
95
- createContextForMessage(incomingMessage, command) {
96
- return new messageContext_1.MessageContext(this.botName, command, this.interactions, incomingMessage, this.storage);
97
- }
98
- createContextForChat(chatId, scheduledAction) {
99
- return new chatContext_1.ChatContext(this.botName, scheduledAction, this.interactions, chatId, this.chats[chatId], `Scheduled:${scheduledAction.key}:${chatId}`, this.storage);
100
- }
101
- }
102
- exports.TelegramApiService = TelegramApiService;
@@ -1,5 +0,0 @@
1
- export interface IActionState {
2
- lastExecutedDate: number;
3
- pinnedMessages: number[];
4
- }
5
- //# sourceMappingURL=actionState.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"actionState.d.ts","sourceRoot":"","sources":["../../types/actionState.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,YAAY;IACzB,gBAAgB,EAAE,MAAM,CAAC;IACzB,cAAc,EAAE,MAAM,EAAE,CAAC;CAC5B"}
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,9 +0,0 @@
1
- import { IActionState } from './actionState';
2
- export type ActionKey = string & {
3
- __brand: 'actionKey';
4
- };
5
- export interface IActionWithState {
6
- key: ActionKey;
7
- stateConstructor: () => IActionState;
8
- }
9
- //# sourceMappingURL=actionWithState.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"actionWithState.d.ts","sourceRoot":"","sources":["../../types/actionWithState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG;IAAE,OAAO,EAAE,WAAW,CAAA;CAAE,CAAC;AAE1D,MAAM,WAAW,gBAAgB;IAC7B,GAAG,EAAE,SAAS,CAAC;IACf,gBAAgB,EAAE,MAAM,YAAY,CAAC;CACxC"}
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- export type CachedValueAccessor = <TResult>(key: string) => Promise<TResult>;
2
- //# sourceMappingURL=cachedValueAccessor.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cachedValueAccessor.d.ts","sourceRoot":"","sources":["../../types/cachedValueAccessor.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC"}
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,4 +0,0 @@
1
- import { MessageContext } from '../entities/context/messageContext';
2
- import { IActionState } from './actionState';
3
- export type CommandCondition<TActionState extends IActionState> = (ctx: MessageContext<TActionState>) => Promise<boolean>;
4
- //# sourceMappingURL=commandCondition.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"commandCondition.d.ts","sourceRoot":"","sources":["../../types/commandCondition.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C,MAAM,MAAM,gBAAgB,CAAC,YAAY,SAAS,YAAY,IAAI,CAC9D,GAAG,EAAE,cAAc,CAAC,YAAY,CAAC,KAChC,OAAO,CAAC,OAAO,CAAC,CAAC"}
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,3 +0,0 @@
1
- import { MessageTypeValue } from './messageTypes';
2
- export type CommandTrigger = MessageTypeValue | string | RegExp;
3
- //# sourceMappingURL=commandTrigger.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"commandTrigger.d.ts","sourceRoot":"","sources":["../../types/commandTrigger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAElD,MAAM,MAAM,cAAc,GAAG,gBAAgB,GAAG,MAAM,GAAG,MAAM,CAAC"}
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,10 +0,0 @@
1
- export declare enum Day {
2
- Sunday = 0,
3
- Monday = 1,
4
- Tuesday = 2,
5
- Wednesday = 3,
6
- Thursday = 4,
7
- Friday = 5,
8
- Saturday = 6
9
- }
10
- //# sourceMappingURL=daysOfTheWeek.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"daysOfTheWeek.d.ts","sourceRoot":"","sources":["../../types/daysOfTheWeek.ts"],"names":[],"mappings":"AAAA,oBAAY,GAAG;IACX,MAAM,IAAI;IACV,MAAM,IAAI;IACV,OAAO,IAAI;IACX,SAAS,IAAI;IACb,QAAQ,IAAI;IACZ,MAAM,IAAI;IACV,QAAQ,IAAI;CACf"}
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Day = void 0;
4
- var Day;
5
- (function (Day) {
6
- Day[Day["Sunday"] = 0] = "Sunday";
7
- Day[Day["Monday"] = 1] = "Monday";
8
- Day[Day["Tuesday"] = 2] = "Tuesday";
9
- Day[Day["Wednesday"] = 3] = "Wednesday";
10
- Day[Day["Thursday"] = 4] = "Thursday";
11
- Day[Day["Friday"] = 5] = "Friday";
12
- Day[Day["Saturday"] = 6] = "Saturday";
13
- })(Day || (exports.Day = Day = {}));
@@ -1,17 +0,0 @@
1
- import { ChatContext } from '../entities/context/chatContext';
2
- import { MessageContext } from '../entities/context/messageContext';
3
- import { IActionState } from './actionState';
4
- import { CachedValueAccessor } from './cachedValueAccessor';
5
- export type CommandHandler<TActionState extends IActionState> = (
6
- /** Context of action executed in chat, in response to a message. */
7
- ctx: MessageContext<TActionState>,
8
- /** State of an action being executed. */
9
- state: TActionState) => Promise<void>;
10
- export type ScheduledHandler<TActionState extends IActionState> = (
11
- /** Context of action executed in chat. */
12
- ctx: ChatContext<TActionState>,
13
- /** Function that will attempt to get value from cache. If there is no value found, corresponding cached state factory will be called. */
14
- getCached: CachedValueAccessor,
15
- /** State of an action being executed. */
16
- state: TActionState) => Promise<void>;
17
- //# sourceMappingURL=handlers.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"handlers.d.ts","sourceRoot":"","sources":["../../types/handlers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,MAAM,MAAM,cAAc,CAAC,YAAY,SAAS,YAAY,IAAI;AAC5D,oEAAoE;AACpE,GAAG,EAAE,cAAc,CAAC,YAAY,CAAC;AACjC,yCAAyC;AACzC,KAAK,EAAE,YAAY,KAClB,OAAO,CAAC,IAAI,CAAC,CAAC;AAEnB,MAAM,MAAM,gBAAgB,CAAC,YAAY,SAAS,YAAY,IAAI;AAC9D,0CAA0C;AAC1C,GAAG,EAAE,WAAW,CAAC,YAAY,CAAC;AAC9B,yIAAyI;AACzI,SAAS,EAAE,mBAAmB;AAC9B,yCAAyC;AACzC,KAAK,EAAE,YAAY,KAClB,OAAO,CAAC,IAAI,CAAC,CAAC"}
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,7 +0,0 @@
1
- export interface MessageSendingOptions {
2
- pin?: boolean;
3
- }
4
- export interface TextMessageSendingOptions extends MessageSendingOptions {
5
- disableWebPreview?: boolean;
6
- }
7
- //# sourceMappingURL=messageSendingOptions.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"messageSendingOptions.d.ts","sourceRoot":"","sources":["../../types/messageSendingOptions.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,qBAAqB;IAClC,GAAG,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,yBAA0B,SAAQ,qBAAqB;IACpE,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC/B"}
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,16 +0,0 @@
1
- export declare const MessageType: {
2
- readonly Text: "__msg:Text";
3
- readonly Sticker: "__msg:Sticker";
4
- readonly Animation: "__msg:Animation";
5
- readonly Document: "__msg:Document";
6
- readonly Voice: "__msg:Voice";
7
- readonly Audio: "__msg:Audio";
8
- readonly LeftChatMember: "__msg:LeftChatMember";
9
- readonly NewChatMember: "__msg:NewChatMember";
10
- readonly Poll: "__msg:Poll";
11
- readonly Location: "__msg:Location";
12
- readonly Photo: "__msg:Photo";
13
- readonly Unknown: "__msg:Unknown";
14
- };
15
- export type MessageTypeValue = (typeof MessageType)[keyof typeof MessageType];
16
- //# sourceMappingURL=messageTypes.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"messageTypes.d.ts","sourceRoot":"","sources":["../../types/messageTypes.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW;;;;;;;;;;;;;CAad,CAAC;AAEX,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,OAAO,WAAW,CAAC,CAAC"}
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MessageType = void 0;
4
- exports.MessageType = {
5
- Text: '__msg:Text',
6
- Sticker: '__msg:Sticker',
7
- Animation: '__msg:Animation',
8
- Document: '__msg:Document',
9
- Voice: '__msg:Voice',
10
- Audio: '__msg:Audio',
11
- LeftChatMember: '__msg:LeftChatMember',
12
- NewChatMember: '__msg:NewChatMember',
13
- Poll: '__msg:Poll',
14
- Location: '__msg:Location',
15
- Photo: '__msg:Photo',
16
- Unknown: '__msg:Unknown'
17
- };
@@ -1,8 +0,0 @@
1
- export interface IReplyMessage<TType> {
2
- content: TType;
3
- chatId: number;
4
- replyId: number | undefined;
5
- traceId: number | string;
6
- disableWebPreview: boolean;
7
- }
8
- //# sourceMappingURL=replyMessage.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"replyMessage.d.ts","sourceRoot":"","sources":["../../types/replyMessage.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,aAAa,CAAC,KAAK;IAChC,OAAO,EAAE,KAAK,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC;IACzB,iBAAiB,EAAE,OAAO,CAAC;CAC9B"}
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });