@ai.ntellect/core 0.4.1 → 0.6.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 (125) hide show
  1. package/.mocharc.json +1 -1
  2. package/README.md +311 -272
  3. package/dist/graph/controller.js +63 -0
  4. package/dist/graph/engine.js +563 -0
  5. package/dist/index.js +6 -6
  6. package/dist/memory/adapters/meilisearch/index.js +249 -0
  7. package/dist/memory/adapters/redis/index.js +96 -0
  8. package/dist/memory/index.js +9 -0
  9. package/dist/services/agenda.js +115 -0
  10. package/dist/services/embedding.js +40 -0
  11. package/dist/services/queue.js +99 -103
  12. package/dist/test/graph/controller.test.js +170 -0
  13. package/dist/test/graph/engine.test.js +465 -0
  14. package/dist/test/memory/adapters/meilisearch.test.js +250 -0
  15. package/dist/test/memory/adapters/redis.test.js +143 -0
  16. package/dist/test/memory/base.test.js +209 -0
  17. package/dist/test/services/agenda.test.js +230 -0
  18. package/dist/test/services/queue.test.js +258 -0
  19. package/dist/types/index.js +2 -0
  20. package/dist/utils/generate-object.js +32 -11
  21. package/dist/utils/inject-actions.js +2 -2
  22. package/dist/utils/queue-item-transformer.js +2 -2
  23. package/dist/utils/state-manager.js +20 -0
  24. package/graph/controller.ts +60 -0
  25. package/graph/engine.ts +709 -0
  26. package/index.ts +7 -7
  27. package/interfaces/index.ts +119 -0
  28. package/memory/adapters/meilisearch/index.ts +286 -0
  29. package/memory/adapters/redis/index.ts +103 -0
  30. package/memory/index.ts +22 -0
  31. package/package.json +9 -2
  32. package/services/agenda.ts +118 -0
  33. package/services/embedding.ts +26 -0
  34. package/services/queue.ts +5 -32
  35. package/test/.env.test +4 -0
  36. package/test/graph/controller.test.ts +186 -0
  37. package/test/graph/engine.test.ts +563 -0
  38. package/test/memory/adapters/meilisearch.test.ts +297 -0
  39. package/test/memory/adapters/redis.test.ts +160 -0
  40. package/test/memory/base.test.ts +229 -0
  41. package/test/services/agenda.test.ts +280 -0
  42. package/test/services/queue.test.ts +286 -44
  43. package/tsconfig.json +10 -9
  44. package/types/index.ts +270 -0
  45. package/utils/generate-object.js +111 -0
  46. package/utils/generate-object.ts +24 -12
  47. package/utils/header-builder.js +34 -0
  48. package/utils/inject-actions.js +16 -0
  49. package/utils/inject-actions.ts +3 -3
  50. package/utils/queue-item-transformer.js +24 -0
  51. package/utils/queue-item-transformer.ts +8 -11
  52. package/utils/sanitize-results.js +60 -0
  53. package/utils/schema-generator.js +46 -0
  54. package/utils/state-manager.js +20 -0
  55. package/utils/state-manager.ts +30 -0
  56. package/.nvmrc +0 -1
  57. package/README.FR.md +0 -365
  58. package/agent/index.ts +0 -244
  59. package/agent/tools/get-rss.ts +0 -64
  60. package/bull.ts +0 -5
  61. package/dist/agent/index.d.ts +0 -38
  62. package/dist/agent/index.js +0 -143
  63. package/dist/agent/tools/get-rss.d.ts +0 -16
  64. package/dist/agent/tools/get-rss.js +0 -62
  65. package/dist/bull.d.ts +0 -1
  66. package/dist/bull.js +0 -9
  67. package/dist/examples/index.d.ts +0 -2
  68. package/dist/examples/index.js +0 -89
  69. package/dist/index.d.ts +0 -7
  70. package/dist/llm/interpreter/context.d.ts +0 -15
  71. package/dist/llm/interpreter/context.js +0 -89
  72. package/dist/llm/interpreter/index.d.ts +0 -21
  73. package/dist/llm/interpreter/index.js +0 -87
  74. package/dist/llm/memory-manager/context.d.ts +0 -2
  75. package/dist/llm/memory-manager/context.js +0 -22
  76. package/dist/llm/memory-manager/index.d.ts +0 -17
  77. package/dist/llm/memory-manager/index.js +0 -107
  78. package/dist/llm/orchestrator/context.d.ts +0 -2
  79. package/dist/llm/orchestrator/context.js +0 -23
  80. package/dist/llm/orchestrator/index.d.ts +0 -44
  81. package/dist/llm/orchestrator/index.js +0 -139
  82. package/dist/llm/orchestrator/types.d.ts +0 -12
  83. package/dist/memory/cache.d.ts +0 -22
  84. package/dist/memory/cache.js +0 -165
  85. package/dist/memory/persistent.d.ts +0 -57
  86. package/dist/memory/persistent.js +0 -189
  87. package/dist/services/queue.d.ts +0 -13
  88. package/dist/services/redis-cache.d.ts +0 -37
  89. package/dist/services/redis-cache.js +0 -93
  90. package/dist/services/scheduler.d.ts +0 -40
  91. package/dist/services/scheduler.js +0 -99
  92. package/dist/services/telegram-monitor.d.ts +0 -0
  93. package/dist/services/telegram-monitor.js +0 -118
  94. package/dist/t.d.ts +0 -46
  95. package/dist/t.js +0 -102
  96. package/dist/test.d.ts +0 -0
  97. package/dist/test.js +0 -438
  98. package/dist/types.d.ts +0 -258
  99. package/dist/types.js +0 -22
  100. package/dist/utils/generate-object.d.ts +0 -12
  101. package/dist/utils/header-builder.d.ts +0 -11
  102. package/dist/utils/inject-actions.d.ts +0 -2
  103. package/dist/utils/queue-item-transformer.d.ts +0 -7
  104. package/dist/utils/sanitize-results.d.ts +0 -17
  105. package/dist/utils/schema-generator.d.ts +0 -16
  106. package/examples/index.ts +0 -103
  107. package/llm/interpreter/context.ts +0 -101
  108. package/llm/interpreter/index.ts +0 -136
  109. package/llm/memory-manager/context.ts +0 -21
  110. package/llm/memory-manager/index.ts +0 -163
  111. package/llm/orchestrator/context.ts +0 -22
  112. package/llm/orchestrator/index.ts +0 -232
  113. package/llm/orchestrator/types.ts +0 -14
  114. package/memory/cache.ts +0 -221
  115. package/memory/persistent.ts +0 -265
  116. package/services/redis-cache.ts +0 -128
  117. package/services/scheduler.ts +0 -128
  118. package/services/telegram-monitor.ts +0 -138
  119. package/t.py +0 -79
  120. package/t.spec +0 -38
  121. package/t.ts +0 -133
  122. package/test/llm/orchestrator.test.ts +0 -47
  123. package/test/llm/synthesizer.test.ts +0 -31
  124. package/types.ts +0 -288
  125. /package/dist/{llm/orchestrator/types.js → interfaces/index.js} +0 -0
@@ -1,265 +0,0 @@
1
- import { cosineSimilarity, embed, EmbeddingModel, embedMany } from "ai";
2
- import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
3
- import { LongTermMemory, MemoryScope } from "../types";
4
-
5
- interface SearchOptions {
6
- scope?: MemoryScope;
7
- userId?: string;
8
- maxResults?: number;
9
- similarityThreshold?: number;
10
- }
11
-
12
- interface MeilisearchSettings {
13
- searchableAttributes?: string[];
14
- sortableAttributes?: string[];
15
- }
16
-
17
- interface MeilisearchResponse {
18
- hits: Array<{
19
- createdAt: string;
20
- query: string;
21
- purpose: string;
22
- data?: any;
23
- chunks: Array<{
24
- content: string;
25
- embedding: number[];
26
- }>;
27
- }>;
28
- }
29
-
30
- interface ProcessedChunk {
31
- content: string;
32
- embedding: number[];
33
- }
34
-
35
- /**
36
- * Handles persistent memory storage using Meilisearch API
37
- */
38
- export class PersistentMemory {
39
- private readonly host: string;
40
- private readonly apiKey: string;
41
- private readonly INDEX_PREFIX: string;
42
- private readonly embeddingModel: EmbeddingModel<string>;
43
- constructor(options: {
44
- host: string;
45
- apiKey: string;
46
- indexPrefix?: string;
47
- embeddingModel: EmbeddingModel<string>;
48
- }) {
49
- this.host = options.host;
50
- this.apiKey = options.apiKey;
51
- this.INDEX_PREFIX = options.indexPrefix || "memory";
52
- this.embeddingModel = options.embeddingModel;
53
- }
54
-
55
- /**
56
- * Initialize indexes
57
- */
58
- async init() {
59
- try {
60
- // Create or get main index
61
- await this._getOrCreateIndex(this.INDEX_PREFIX);
62
- console.log(`✅ Index '${this.INDEX_PREFIX}' initialized successfully`);
63
- } catch (error) {
64
- console.error(`❌ Failed to initialize index: ${error}`);
65
- throw error;
66
- }
67
- }
68
-
69
- /**
70
- * Make API request to Meilisearch
71
- */
72
- private async _makeRequest<T = unknown>(
73
- path: string,
74
- options: RequestInit = {}
75
- ): Promise<T> {
76
- const url = `${this.host}${path}`;
77
- console.log("🔍 Making request to Meilisearch:", url);
78
- const response = await fetch(url, {
79
- ...options,
80
- headers: {
81
- "Content-Type": "application/json",
82
- Authorization: `Bearer ${this.apiKey}`,
83
- ...options.headers,
84
- },
85
- });
86
-
87
- if (!response.ok) {
88
- console.log({ response });
89
- throw new Error(`Meilisearch API error: ${response.statusText}`);
90
- }
91
-
92
- return response.json() as Promise<T>;
93
- }
94
-
95
- /**
96
- * Get or create an index with proper settings
97
- */
98
- private async _getOrCreateIndex(indexName: string) {
99
- try {
100
- // Check if index exists first
101
- const indexExists = await this._makeRequest(`/indexes/${indexName}`, {
102
- method: "GET",
103
- }).catch(() => false);
104
-
105
- if (!indexExists) {
106
- console.log(`Creating new index: ${indexName}`);
107
- await this._makeRequest("/indexes", {
108
- method: "POST",
109
- body: JSON.stringify({
110
- uid: indexName,
111
- primaryKey: "id",
112
- }),
113
- });
114
- }
115
-
116
- // Update index settings
117
- const settings: MeilisearchSettings = {
118
- searchableAttributes: ["query", "purpose", "chunks.content"],
119
- sortableAttributes: ["createdAt"],
120
- };
121
-
122
- await this._makeRequest(`/indexes/${indexName}/settings`, {
123
- method: "PATCH",
124
- body: JSON.stringify(settings),
125
- });
126
-
127
- console.log(`Index ${indexName} configured successfully`);
128
- } catch (error: any) {
129
- console.error(`Failed to configure index ${indexName}:`, error);
130
- throw error;
131
- }
132
- }
133
-
134
- async processContent(content: string): Promise<ProcessedChunk[]> {
135
- // Split content into chunks
136
- const textSplitter = new RecursiveCharacterTextSplitter({
137
- chunkSize: 1000,
138
- });
139
- const chunks = await textSplitter.createDocuments([content]);
140
-
141
- // Generate embeddings for all chunks
142
- const { embeddings } = await embedMany({
143
- model: this.embeddingModel,
144
- values: chunks.map((chunk) => chunk.pageContent),
145
- });
146
-
147
- // Create processed chunks with embeddings
148
- return chunks.map((chunk, i) => ({
149
- content: chunk.pageContent,
150
- embedding: embeddings[i],
151
- }));
152
- }
153
-
154
- /**
155
- * Store a memory in the database
156
- */
157
- async createMemory(memory: LongTermMemory) {
158
- try {
159
- console.log(`📝 Creating memory in index: ${this.INDEX_PREFIX}`);
160
-
161
- // Process content into chunks with embeddings
162
- const chunks = await this.processContent(memory.data);
163
-
164
- // Generate unique ID if not provided
165
- const id = memory.id || crypto.randomUUID();
166
-
167
- const document = {
168
- ...memory,
169
- chunks,
170
- createdAt: memory.createdAt.toISOString(),
171
- };
172
-
173
- const response = await this._makeRequest(
174
- `/indexes/${this.INDEX_PREFIX}/documents`,
175
- {
176
- method: "POST",
177
- body: JSON.stringify([document]),
178
- }
179
- );
180
-
181
- console.log("✅ Memory created successfully", { id });
182
- return response;
183
- } catch (error) {
184
- console.error("❌ Failed to create memory:", error);
185
- throw error;
186
- }
187
- }
188
-
189
- /**
190
- * Find best matching memories
191
- */
192
- async findRelevantDocuments(query: string, options: SearchOptions = {}) {
193
- console.log(`\n🔍 Searching in index: ${this.INDEX_PREFIX}`);
194
- console.log("Query:", query);
195
-
196
- try {
197
- // Generate embedding for the query
198
- const { embedding: queryEmbedding } = await embed({
199
- model: this.embeddingModel,
200
- value: query,
201
- });
202
-
203
- // Search in the index
204
- const searchResults = await this._makeRequest<MeilisearchResponse>(
205
- `/indexes/${this.INDEX_PREFIX}/search`,
206
- {
207
- method: "POST",
208
- body: JSON.stringify({
209
- q: query,
210
- limit: options.maxResults || 10,
211
- }),
212
- }
213
- );
214
-
215
- if (!searchResults?.hits?.length) {
216
- console.log("❌ No matches found");
217
- return [];
218
- }
219
-
220
- // Process and filter results using cosine similarity
221
- const results = searchResults.hits
222
- .flatMap((hit) => {
223
- const chunkSimilarities = hit.chunks.map((chunk) => ({
224
- query: hit.query,
225
- data: hit.data,
226
- similarityPercentage:
227
- (cosineSimilarity(queryEmbedding, chunk.embedding) + 1) * 50,
228
- createdAt: hit.createdAt,
229
- }));
230
-
231
- return chunkSimilarities.reduce(
232
- (best, current) =>
233
- current.similarityPercentage > best.similarityPercentage
234
- ? current
235
- : best,
236
- chunkSimilarities[0]
237
- );
238
- })
239
- .filter(
240
- (match) =>
241
- match.similarityPercentage >= (options.similarityThreshold || 70)
242
- )
243
- .sort((a, b) => b.similarityPercentage - a.similarityPercentage);
244
-
245
- console.log(`✨ Found ${results.length} relevant matches`);
246
- return results.map((result) => ({
247
- query: result.query,
248
- data: result.data,
249
- createdAt: result.createdAt,
250
- }));
251
- } catch (error) {
252
- console.error("❌ Search failed:", error);
253
- return [];
254
- }
255
- }
256
-
257
- /**
258
- * Delete memories for a given scope and user
259
- */
260
- async deleteMemories() {
261
- return this._makeRequest(`/indexes/${this.INDEX_PREFIX}`, {
262
- method: "DELETE",
263
- });
264
- }
265
- }
@@ -1,128 +0,0 @@
1
- import Redis from "ioredis";
2
- import cron from "node-cron";
3
-
4
- export interface CacheConfig {
5
- host: string;
6
- port: number;
7
- password?: string;
8
- ttl?: number; // Time to live in seconds (default 30 minutes)
9
- cleanupInterval?: string; // Cron expression (default every 30 minutes)
10
- }
11
-
12
- export class RedisCache {
13
- private redis: Redis;
14
- private readonly defaultTTL: number;
15
- private readonly cleanupJob: cron.ScheduledTask;
16
-
17
- constructor(config: CacheConfig) {
18
- this.redis = new Redis({
19
- host: config.host,
20
- port: config.port,
21
- password: config.password,
22
- });
23
-
24
- this.defaultTTL = config.ttl || 1800; // 30 minutes in seconds
25
-
26
- // Setup cleanup job (default: every 30 minutes)
27
- this.cleanupJob = cron.schedule(
28
- config.cleanupInterval || "*/30 * * * *",
29
- () => this.cleanup()
30
- );
31
- }
32
-
33
- /**
34
- * Store previous actions for a specific request
35
- */
36
- async storePreviousActions(requestId: string, actions: any[]): Promise<void> {
37
- const key = `previous_actions:${requestId}`;
38
- await this.redis.setex(
39
- key,
40
- this.defaultTTL,
41
- JSON.stringify({
42
- timestamp: new Date().toISOString(),
43
- actions,
44
- })
45
- );
46
- }
47
-
48
- /**
49
- * Get previous actions for a specific request
50
- */
51
- async getPreviousActions(requestId: string): Promise<any[]> {
52
- const key = `previous_actions:${requestId}`;
53
- const data = await this.redis.get(key);
54
- if (!data) return [];
55
-
56
- const parsed = JSON.parse(data);
57
- return parsed.actions;
58
- }
59
-
60
- /**
61
- * Store a recent message
62
- */
63
- async storeRecentMessage(
64
- message: string,
65
- metadata?: Record<string, any>
66
- ): Promise<void> {
67
- const id = crypto.randomUUID();
68
- const key = `recent_messages:${id}`;
69
- await this.redis.setex(
70
- key,
71
- this.defaultTTL,
72
- JSON.stringify({
73
- timestamp: new Date().toISOString(),
74
- message,
75
- metadata,
76
- })
77
- );
78
- }
79
-
80
- /**
81
- * Get recent messages
82
- */
83
- async getRecentMessages(limit: number = 10): Promise<any[]> {
84
- const keys = await this.redis.keys("recent_messages:*");
85
- if (!keys.length) return [];
86
-
87
- const messages = await Promise.all(
88
- keys.map(async (key) => {
89
- const data = await this.redis.get(key);
90
- return data ? JSON.parse(data) : null;
91
- })
92
- );
93
-
94
- return messages
95
- .filter(Boolean)
96
- .sort(
97
- (a, b) =>
98
- new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
99
- )
100
- .slice(0, limit);
101
- }
102
-
103
- /**
104
- * Cleanup expired keys
105
- */
106
- private async cleanup(): Promise<void> {
107
- console.log("🧹 Starting cache cleanup...");
108
- try {
109
- // Redis automatically removes expired keys
110
- // This is just for logging purposes
111
- const actionKeys = await this.redis.keys("previous_actions:*");
112
- const messageKeys = await this.redis.keys("recent_messages:*");
113
- console.log(
114
- `Cache status: ${actionKeys.length} actions, ${messageKeys.length} messages`
115
- );
116
- } catch (error) {
117
- console.error("❌ Cache cleanup error:", error);
118
- }
119
- }
120
-
121
- /**
122
- * Stop the cleanup job and close Redis connection
123
- */
124
- async close(): Promise<void> {
125
- this.cleanupJob.stop();
126
- await this.redis.quit();
127
- }
128
- }
@@ -1,128 +0,0 @@
1
- import cron from "node-cron";
2
- import { AgentRuntime } from "../llm/orchestrator";
3
- import { RedisCache } from "./redis-cache";
4
-
5
- interface ScheduledRequest {
6
- id: string;
7
- originalRequest: string;
8
- cronExpression: string;
9
- isRecurring: boolean;
10
- createdAt: Date;
11
- }
12
-
13
- export class TaskScheduler {
14
- private scheduledRequests: Map<string, ScheduledRequest> = new Map();
15
- private cronJobs: Map<string, cron.ScheduledTask> = new Map();
16
- private readonly agentRuntime: AgentRuntime;
17
- private readonly cache: RedisCache;
18
-
19
- constructor(agentRuntime: AgentRuntime, cache: RedisCache) {
20
- this.agentRuntime = agentRuntime;
21
- this.cache = cache;
22
- }
23
-
24
- /**
25
- * Schedule a new request to be processed later
26
- */
27
- async scheduleRequest(request: {
28
- originalRequest: string;
29
- cronExpression: string;
30
- }): Promise<string> {
31
- const id = crypto.randomUUID();
32
-
33
- const scheduledRequest: ScheduledRequest = {
34
- id,
35
- originalRequest: request.originalRequest,
36
- cronExpression: request.cronExpression,
37
- isRecurring: false,
38
- createdAt: new Date(),
39
- };
40
-
41
- // Create cron job
42
- const cronJob = cron.schedule(request.cronExpression, async () => {
43
- await this.executeScheduledRequest(scheduledRequest);
44
-
45
- if (!scheduledRequest.isRecurring) {
46
- this.cancelScheduledRequest(id);
47
- }
48
- });
49
-
50
- // Store request and job
51
- this.scheduledRequests.set(id, scheduledRequest);
52
- this.cronJobs.set(id, cronJob);
53
-
54
- console.log(
55
- `✅ Request scheduled with cron expression: ${request.cronExpression}`
56
- );
57
-
58
- return id;
59
- }
60
-
61
- /**
62
- * Execute a scheduled request by launching a new process
63
- */
64
- private async executeScheduledRequest(
65
- request: ScheduledRequest
66
- ): Promise<void> {
67
- try {
68
- console.log(`🔄 Executing scheduled request from ${request.createdAt}`);
69
-
70
- // Récupérer les actions précédentes du cache
71
- const previousActions = await this.cache.getPreviousActions(request.id);
72
-
73
- // Add context about when this request was scheduled
74
- const contextualRequest = `You are a scheduler.
75
- You were asked to execute this request: ${request.originalRequest}\n
76
- Date of the request: ${request.createdAt.toISOString()}\n
77
- Act like if you know the request was scheduled.
78
- Don't reschedule the same action.
79
- Just execute it.`;
80
-
81
- // Process the request as if it was just received
82
- const result = await this.agentRuntime.process({
83
- currentContext: contextualRequest,
84
- previousActions,
85
- });
86
-
87
- // Store the new actions in cache
88
- if (result.actions.length > 0) {
89
- await this.cache.storePreviousActions(request.id, result.actions);
90
- }
91
-
92
- console.log(`✅ Scheduled request executed successfully`);
93
- } catch (error) {
94
- console.error(`❌ Failed to execute scheduled request:`, error);
95
- }
96
- }
97
-
98
- /**
99
- * Cancel a scheduled request
100
- */
101
- cancelScheduledRequest(requestId: string): boolean {
102
- const cronJob = this.cronJobs.get(requestId);
103
- if (cronJob) {
104
- cronJob.stop();
105
- this.cronJobs.delete(requestId);
106
- }
107
- return this.scheduledRequests.delete(requestId);
108
- }
109
-
110
- /**
111
- * Get all scheduled requests
112
- */
113
- getScheduledRequests(): ScheduledRequest[] {
114
- return Array.from(this.scheduledRequests.values());
115
- }
116
-
117
- /**
118
- * Stop all cron jobs
119
- */
120
- stopAll(): void {
121
- for (const [id, cronJob] of this.cronJobs) {
122
- cronJob.stop();
123
- this.cronJobs.delete(id);
124
- this.scheduledRequests.delete(id);
125
- }
126
- console.log("All scheduled requests stopped");
127
- }
128
- }
@@ -1,138 +0,0 @@
1
- // import dotenv from "dotenv";
2
- // import promptSync from "prompt-sync";
3
- // import { TelegramClient } from "telegram";
4
- // import { NewMessage } from "telegram/events";
5
- // import { StringSession } from "telegram/sessions";
6
-
7
- // dotenv.config();
8
-
9
- // const prompt = promptSync({ sigint: true });
10
-
11
- // export interface TokenLaunch {
12
- // tokenAddress: string;
13
- // messageUrl: string;
14
- // timestamp: string;
15
- // }
16
-
17
- // export class TelegramMonitor {
18
- // private client: TelegramClient;
19
- // private botStartTime: Date;
20
-
21
- // constructor() {
22
- // if (!process.env.TELEGRAM_API_ID || !process.env.TELEGRAM_API_HASH) {
23
- // throw new Error("TELEGRAM_API_ID and TELEGRAM_API_HASH must be set");
24
- // }
25
- // this.botStartTime = new Date();
26
-
27
- // const apiId = parseInt(process.env.TELEGRAM_API_ID);
28
- // const apiHash = process.env.TELEGRAM_API_HASH;
29
-
30
- // // Utiliser une session stockée si disponible
31
- // const sessionString = process.env.TELEGRAM_SESSION;
32
- // this.client = new TelegramClient(
33
- // new StringSession(sessionString),
34
- // apiId,
35
- // apiHash,
36
- // {
37
- // connectionRetries: 5,
38
- // }
39
- // );
40
- // }
41
-
42
- // async connect() {
43
- // // Se connecter en tant qu'utilisateur
44
- // await this.client.start({
45
- // phoneNumber: async () => prompt("Numéro de téléphone ? "),
46
- // password: async () => prompt("Mot de passe ? "),
47
- // phoneCode: async () => prompt("Code reçu ? "),
48
- // onError: (err) => console.log(err),
49
- // });
50
-
51
- // // Sauvegarder la session pour une utilisation ultérieure
52
- // console.log("Session string à sauvegarder:", this.client.session.save());
53
- // }
54
-
55
- // async startMonitoring(
56
- // channelUsername: string,
57
- // callback: {
58
- // onNewLaunch: (message: string) => void;
59
- // }
60
- // ) {
61
- // console.log(`Démarrage du monitoring pour ${channelUsername}`);
62
-
63
- // try {
64
- // // S'assurer que le client est connecté
65
- // if (!this.client.connected) {
66
- // console.log("Client non connecté, tentative de connexion...");
67
- // await this.client.connect();
68
- // console.log("Client connecté avec succès");
69
- // }
70
-
71
- // console.log("État de la connexion:", this.client.connected);
72
-
73
- // // Vérifier si le canal existe et est accessible
74
- // try {
75
- // const channel = await this.client.getEntity(channelUsername);
76
- // console.log("Canal trouvé:", channel.id);
77
- // } catch (e) {
78
- // console.error("Erreur lors de l'accès au canal:", e);
79
- // }
80
-
81
- // this.client.addEventHandler(async (event: any) => {
82
- // const message = event.message;
83
- // if (!message) {
84
- // console.log("Pas de message dans l'événement");
85
- // return;
86
- // }
87
-
88
- // if (!message.text) {
89
- // console.log("Message sans texte:", message);
90
- // return;
91
- // }
92
-
93
- // try {
94
- // callback.onNewLaunch(message.text);
95
- // } catch (error) {
96
- // console.error("Erreur lors du traitement du message:", error);
97
- // }
98
- // }, new NewMessage({ chats: [channelUsername] }));
99
-
100
- // console.log("Handler d'événements ajouté avec succès");
101
- // } catch (error) {
102
- // console.error("Erreur lors du démarrage du monitoring:", error);
103
- // }
104
- // }
105
-
106
- // static async generateNewSession() {
107
- // // Supprimer la session existante
108
- // const client = new TelegramClient(
109
- // new StringSession(""),
110
- // parseInt(process.env.TELEGRAM_API_ID || ""),
111
- // process.env.TELEGRAM_API_HASH || "",
112
- // {
113
- // connectionRetries: 5,
114
- // }
115
- // );
116
-
117
- // // Se connecter en tant qu'utilisateur
118
- // await client.start({
119
- // phoneNumber: async () => prompt("Numéro de téléphone ? "),
120
- // password: async () => prompt("Mot de passe ? "),
121
- // phoneCode: async () => prompt("Code reçu ? "),
122
- // onError: (err) => console.log(err),
123
- // });
124
-
125
- // // Sauvegarder la nouvelle session pour une utilisation ultérieure
126
- // console.log(
127
- // "Nouvelle session string à sauvegarder:",
128
- // client.session.save()
129
- // );
130
- // }
131
- // }
132
-
133
- // const telegramMonitor = new TelegramMonitor();
134
- // telegramMonitor.startMonitoring("testcalldegen", {
135
- // onNewLaunch: (message: string) => {
136
- // console.log("Nouveau message:", message);
137
- // },
138
- // });