forked from yunus-0x/meridian
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram.js
More file actions
494 lines (445 loc) · 15.8 KB
/
Copy pathtelegram.js
File metadata and controls
494 lines (445 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { log } from "./logger.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const USER_CONFIG_PATH = path.join(__dirname, "user-config.json");
const TOKEN = process.env.TELEGRAM_BOT_TOKEN || null;
const BASE = TOKEN ? `https://api.telegram.org/bot${TOKEN}` : null;
const ALLOWED_USER_IDS = new Set(
String(process.env.TELEGRAM_ALLOWED_USER_IDS || "")
.split(",")
.map((id) => id.trim())
.filter(Boolean)
);
let chatId = process.env.TELEGRAM_CHAT_ID || null;
let _offset = 0;
let _polling = false;
let _liveMessageDepth = 0;
let _warnedMissingChatId = false;
let _warnedMissingAllowedUsers = false;
// ─── chatId persistence ──────────────────────────────────────────
function loadChatId() {
try {
if (fs.existsSync(USER_CONFIG_PATH)) {
const cfg = JSON.parse(fs.readFileSync(USER_CONFIG_PATH, "utf8"));
if (cfg.telegramChatId) chatId = cfg.telegramChatId;
}
} catch (error) {
log("telegram_warn", `Invalid user-config.json; chatId not loaded: ${error.message}`);
}
}
function saveChatId(id) {
try {
let cfg = fs.existsSync(USER_CONFIG_PATH)
? JSON.parse(fs.readFileSync(USER_CONFIG_PATH, "utf8"))
: {};
cfg.telegramChatId = id;
fs.writeFileSync(USER_CONFIG_PATH, JSON.stringify(cfg, null, 2));
} catch (e) {
log("telegram_error", `Failed to persist chatId: ${e.message}`);
}
}
loadChatId();
function isAuthorizedIncomingMessage(msg) {
const incomingChatId = String(msg.chat?.id || "");
const senderUserId = msg.from?.id != null ? String(msg.from.id) : null;
const chatType = msg.chat?.type || "unknown";
if (!chatId) {
if (!_warnedMissingChatId) {
log("telegram_warn", "Ignoring inbound Telegram messages because TELEGRAM_CHAT_ID / user-config.telegramChatId is not configured. Auto-registration is disabled for safety.");
_warnedMissingChatId = true;
}
return false;
}
if (incomingChatId !== chatId) return false;
if (chatType !== "private" && ALLOWED_USER_IDS.size === 0) {
if (!_warnedMissingAllowedUsers) {
log("telegram_warn", "Ignoring group Telegram messages because TELEGRAM_ALLOWED_USER_IDS is not configured. Set explicit allowed user IDs for command/control.");
_warnedMissingAllowedUsers = true;
}
return false;
}
if (ALLOWED_USER_IDS.size > 0) {
if (!senderUserId || !ALLOWED_USER_IDS.has(senderUserId)) return false;
}
return true;
}
// ─── Core send ───────────────────────────────────────────────────
export function isEnabled() {
return !!TOKEN;
}
async function postTelegram(method, body) {
if (!TOKEN || !chatId) return null;
try {
const res = await fetch(`${BASE}/${method}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ chat_id: chatId, ...body }),
});
if (!res.ok) {
const err = await res.text();
log("telegram_error", `${method} ${res.status}: ${err.slice(0, 200)}`);
return null;
}
return await res.json();
} catch (e) {
log("telegram_error", `${method} failed: ${e.message}`);
return null;
}
}
async function postTelegramRaw(method, body) {
if (!TOKEN) return null;
try {
const res = await fetch(`${BASE}/${method}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const err = await res.text();
log("telegram_error", `${method} ${res.status}: ${err.slice(0, 200)}`);
return null;
}
return await res.json();
} catch (e) {
log("telegram_error", `${method} failed: ${e.message}`);
return null;
}
}
export async function sendMessage(text) {
if (!TOKEN || !chatId) return;
return postTelegram("sendMessage", { text: String(text).slice(0, 4096) });
}
export async function sendMessageWithButtons(text, inlineKeyboard) {
if (!TOKEN || !chatId) return;
return postTelegram("sendMessage", {
text: String(text).slice(0, 4096),
reply_markup: { inline_keyboard: inlineKeyboard },
});
}
export async function sendHTML(html) {
if (!TOKEN || !chatId) return;
return postTelegram("sendMessage", { text: html.slice(0, 4096), parse_mode: "HTML" });
}
export async function editMessage(text, messageId) {
if (!TOKEN || !chatId || !messageId) return null;
return postTelegram("editMessageText", {
message_id: messageId,
text: String(text).slice(0, 4096),
});
}
export async function editMessageWithButtons(text, messageId, inlineKeyboard) {
if (!TOKEN || !chatId || !messageId) return null;
return postTelegram("editMessageText", {
message_id: messageId,
text: String(text).slice(0, 4096),
reply_markup: { inline_keyboard: inlineKeyboard },
});
}
export async function answerCallbackQuery(callbackQueryId, text = "") {
if (!TOKEN || !callbackQueryId) return null;
return postTelegramRaw("answerCallbackQuery", {
callback_query_id: callbackQueryId,
...(text ? { text: String(text).slice(0, 200) } : {}),
});
}
export function hasActiveLiveMessage() {
return _liveMessageDepth > 0;
}
function createTypingIndicator() {
if (!TOKEN || !chatId) {
return { stop() {} };
}
let stopped = false;
let timer = null;
async function tick() {
if (stopped) return;
await postTelegram("sendChatAction", { action: "typing" });
timer = setTimeout(() => {
tick().catch(() => null);
}, 4000);
}
tick().catch(() => null);
return {
stop() {
stopped = true;
if (timer) clearTimeout(timer);
timer = null;
},
};
}
function toolLabel(name) {
const labels = {
get_token_info: "get token info",
get_token_narrative: "get token narrative",
get_token_holders: "get token holders",
get_top_candidates: "get top candidates",
get_pool_detail: "get pool detail",
get_active_bin: "get active bin",
deploy_position: "deploy position",
close_position: "close position",
claim_fees: "claim fees",
swap_token: "swap token",
update_config: "update config",
get_my_positions: "get positions",
get_wallet_balance: "get wallet balance",
check_smart_wallets_on_pool: "check smart wallets",
study_top_lpers: "study top LPers",
get_top_lpers: "get top LPers",
search_pools: "search pools",
discover_pools: "discover pools",
};
return labels[name] || name.replace(/_/g, " ");
}
function summarizeToolResult(name, result) {
if (!result) return "";
if (result.error) return result.error;
if (result.reason && result.blocked) return result.reason;
switch (name) {
case "deploy_position":
return result.position ? `position ${String(result.position).slice(0, 8)}...` : "submitted";
case "close_position":
return result.success ? "closed" : (result.reason || "failed");
case "claim_fees":
return result.claimed_amount != null ? `claimed ${result.claimed_amount}` : "done";
case "update_config":
return Object.keys(result.applied || {}).join(", ") || "updated";
case "get_top_candidates":
return `${result.candidates?.length ?? 0} candidates`;
case "get_my_positions":
return `${result.total_positions ?? result.positions?.length ?? 0} positions`;
case "get_wallet_balance":
return `${result.sol ?? "?"} SOL`;
case "study_top_lpers":
case "get_top_lpers":
return `${result.lpers?.length ?? 0} LPers`;
default:
return result.success === false ? "failed" : "done";
}
}
export async function createLiveMessage(title, intro = "Starting...") {
if (!TOKEN || !chatId) return null;
const typing = createTypingIndicator();
const state = {
title,
intro,
toolLines: [],
footer: "",
messageId: null,
flushTimer: null,
flushPromise: null,
flushRequested: false,
};
function render() {
const sections = [state.title];
if (state.intro) sections.push(state.intro);
if (state.toolLines.length > 0) sections.push(state.toolLines.join("\n"));
if (state.footer) sections.push(state.footer);
return sections.join("\n\n").slice(0, 4096);
}
async function flushNow() {
state.flushTimer = null;
state.flushRequested = false;
const text = render();
if (!state.messageId) {
const sent = await sendMessage(text);
state.messageId = sent?.result?.message_id ?? null;
return;
}
await editMessage(text, state.messageId);
}
function scheduleFlush(delay = 300) {
if (state.flushTimer) {
state.flushRequested = true;
return;
}
state.flushTimer = setTimeout(() => {
state.flushPromise = flushNow().catch(() => null);
}, delay);
}
async function upsertToolLine(name, icon, suffix = "") {
const label = toolLabel(name);
const line = `${icon} ${label}${suffix ? ` ${suffix}` : ""}`;
const idx = state.toolLines.findIndex((entry) => entry.includes(` ${label}`));
if (idx >= 0) state.toolLines[idx] = line;
else state.toolLines.push(line);
scheduleFlush();
}
_liveMessageDepth += 1;
await flushNow();
return {
async toolStart(name) {
await upsertToolLine(name, "ℹ️", "...");
},
async toolFinish(name, result, success) {
const icon = success ? "✅" : "❌";
const summary = summarizeToolResult(name, result);
await upsertToolLine(name, icon, summary ? `— ${summary}` : "");
},
async note(text) {
state.intro = text;
scheduleFlush();
},
async finalize(finalText) {
if (state.flushTimer) {
clearTimeout(state.flushTimer);
state.flushTimer = null;
}
if (state.flushPromise) await state.flushPromise;
state.footer = finalText;
await flushNow();
_liveMessageDepth = Math.max(0, _liveMessageDepth - 1);
typing.stop();
},
async fail(errorText) {
if (state.flushTimer) {
clearTimeout(state.flushTimer);
state.flushTimer = null;
}
if (state.flushPromise) await state.flushPromise;
state.footer = `❌ ${errorText}`;
await flushNow();
_liveMessageDepth = Math.max(0, _liveMessageDepth - 1);
typing.stop();
},
};
}
// ─── Long polling ────────────────────────────────────────────────
async function poll(onMessage) {
while (_polling) {
try {
const res = await fetch(
`${BASE}/getUpdates?offset=${_offset}&timeout=30`,
{ signal: AbortSignal.timeout(35_000) }
);
if (!res.ok) { await sleep(5000); continue; }
const data = await res.json();
for (const update of data.result || []) {
_offset = update.update_id + 1;
const callback = update.callback_query;
if (callback?.data && callback?.message) {
const callbackMsg = {
chat: callback.message.chat,
from: callback.from,
text: callback.data,
};
if (!isAuthorizedIncomingMessage(callbackMsg)) continue;
await onMessage({
...callbackMsg,
isCallback: true,
callbackQueryId: callback.id,
callbackData: callback.data,
messageId: callback.message.message_id,
});
continue;
}
const msg = update.message;
if (!msg?.text) continue;
if (!isAuthorizedIncomingMessage(msg)) continue;
await onMessage(msg);
}
} catch (e) {
if (!e.message?.includes("aborted")) {
log("telegram_error", `Poll error: ${e.message}`);
}
await sleep(5000);
}
}
}
const BOT_COMMANDS = [
{ command: "help", description: "Show commands" },
{ command: "status", description: "Wallet + positions snapshot" },
{ command: "wallet", description: "Wallet, deploy amount, HiveMind status" },
{ command: "positions", description: "List open positions" },
{ command: "pool", description: "Detailed info for one open position" },
{ command: "close", description: "Close one position by index" },
{ command: "closeall", description: "Close all open positions" },
{ command: "set", description: "Set note/instruction on position" },
{ command: "config", description: "Show important runtime config" },
{ command: "settings", description: "Button menu for common config" },
{ command: "setcfg", description: "Update persisted config key" },
{ command: "screen", description: "Refresh deterministic candidate list" },
{ command: "candidates", description: "Show latest cached candidates" },
{ command: "deploy", description: "Deploy candidate by cached index" },
{ command: "briefing", description: "Morning briefing" },
{ command: "hive", description: "HiveMind sync status" },
{ command: "pause", description: "Stop cron cycles" },
{ command: "resume", description: "Start cron cycles again" },
{ command: "stop", description: "Shut down agent" },
];
async function registerCommands() {
if (!BASE) return;
try {
await fetch(`${BASE}/setMyCommands`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ commands: BOT_COMMANDS }),
});
log("telegram", "Bot commands registered");
} catch (e) {
log("telegram_warn", `Failed to register bot commands: ${e.message}`);
}
}
export function startPolling(onMessage) {
if (!TOKEN) return;
_polling = true;
poll(onMessage); // fire-and-forget
registerCommands();
log("telegram", "Bot polling started");
}
export function stopPolling() {
_polling = false;
}
// ─── Notification helpers ────────────────────────────────────────
export async function notifyDeploy({ pair, amountSol, position, tx, priceRange, rangeCoverage, binStep, baseFee }) {
if (hasActiveLiveMessage()) return;
const priceStr = priceRange
? `Price range: ${priceRange.min < 0.0001 ? priceRange.min.toExponential(3) : priceRange.min.toFixed(6)} – ${priceRange.max < 0.0001 ? priceRange.max.toExponential(3) : priceRange.max.toFixed(6)}\n`
: "";
const coverageStr = rangeCoverage
? `Range cover: ${fmtPct(rangeCoverage.downside_pct)} downside | ${fmtPct(rangeCoverage.upside_pct)} upside | ${fmtPct(rangeCoverage.width_pct)} total\n`
: "";
const poolStr = (binStep || baseFee)
? `Bin step: ${binStep ?? "?"} | Base fee: ${baseFee != null ? baseFee + "%" : "?"}\n`
: "";
await sendHTML(
`✅ <b>Deployed</b> ${pair}\n` +
`Amount: ${amountSol} SOL\n` +
priceStr +
coverageStr +
poolStr +
`Position: <code>${position?.slice(0, 8)}...</code>\n` +
`Tx: <code>${tx?.slice(0, 16)}...</code>`
);
}
export async function notifyClose({ pair, pnlUsd, pnlPct }) {
if (hasActiveLiveMessage()) return;
const sign = pnlUsd >= 0 ? "+" : "";
await sendHTML(
`🔒 <b>Closed</b> ${pair}\n` +
`PnL: ${sign}$${(pnlUsd ?? 0).toFixed(2)} (${sign}${(pnlPct ?? 0).toFixed(2)}%)`
);
}
export async function notifySwap({ inputSymbol, outputSymbol, amountIn, amountOut, tx }) {
if (hasActiveLiveMessage()) return;
await sendHTML(
`🔄 <b>Swapped</b> ${inputSymbol} → ${outputSymbol}\n` +
`In: ${amountIn ?? "?"} | Out: ${amountOut ?? "?"}\n` +
`Tx: <code>${tx?.slice(0, 16)}...</code>`
);
}
export async function notifyOutOfRange({ pair, minutesOOR }) {
if (hasActiveLiveMessage()) return;
await sendHTML(
`⚠️ <b>Out of Range</b> ${pair}\n` +
`Been OOR for ${minutesOOR} minutes`
);
}
function sleep(ms) {
return new Promise((r) => setTimeout(r, ms));
}
function fmtPct(value) {
const n = Number(value);
return Number.isFinite(n) ? `${n.toFixed(2)}%` : "?";
}