Repository navigation
Expand file tree
/
Copy pathtelegram-remote.js
More file actions
356 lines (307 loc) · 11.2 KB
/
Copy pathtelegram-remote.js
File metadata and controls
356 lines (307 loc) · 11.2 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
'use strict';
// Telegram Bot two-way remote control for Cursor.
// Sends screenshots when blocked, receives user replies, injects them into Cursor.
const TG = `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN || ''}`;
const CHAT_ID = process.env.TELEGRAM_CHAT_ID || '';
// Proxy support for regions where Telegram is blocked.
// Set HTTPS_PROXY or HTTP_PROXY env var, e.g. http://127.0.0.1:7890
const PROXY_URL = process.env.HTTPS_PROXY || process.env.HTTP_PROXY || process.env.ALL_PROXY || '';
let proxyDispatcher = null;
if (PROXY_URL) {
try {
const { ProxyAgent } = require('undici');
proxyDispatcher = new ProxyAgent(PROXY_URL);
} catch {}
}
let updateOffset = 0;
let _getPage = null; // () => Promise<Page>
let _getCDPClient = null; // () => Promise<CDPSession>
function enabled() {
return !!(process.env.TELEGRAM_BOT_TOKEN && CHAT_ID);
}
function log(msg) {
console.log(`[${new Date().toLocaleTimeString()}] 🤖 TG: ${msg}`);
}
// ── Telegram API helpers ───────────────────────────────────────────
async function tgApi(method, body, formData) {
const url = `${TG}/${method}`;
const opts = { method: 'POST' };
if (proxyDispatcher) opts.dispatcher = proxyDispatcher;
if (formData) {
opts.body = formData;
} else if (body) {
opts.headers = { 'Content-Type': 'application/json' };
opts.body = JSON.stringify(body);
}
const res = await fetch(url, opts);
return res.json();
}
async function sendText(text, inlineButtons) {
const body = { chat_id: CHAT_ID, text, parse_mode: 'HTML' };
if (inlineButtons) {
body.reply_markup = { inline_keyboard: inlineButtons };
}
return tgApi('sendMessage', body);
}
async function sendScreenshot(page, caption, inlineButtons) {
try {
const buf = await page.screenshot({ encoding: 'binary' });
const form = new FormData();
form.append('chat_id', CHAT_ID);
form.append('caption', caption || '');
form.append('parse_mode', 'HTML');
form.append('photo', new Blob([buf], { type: 'image/png' }), 'cursor.png');
if (inlineButtons) {
form.append('reply_markup', JSON.stringify({ inline_keyboard: inlineButtons }));
}
return tgApi('sendPhoto', null, form);
} catch (e) {
return sendText(`⚠️ Screenshot failed: ${e.message}`);
}
}
// ── Cursor interaction via CDP ─────────────────────────────────────
async function typeIntoCursor(text) {
const page = await _getPage();
if (!page) return;
const client = await page.target().createCDPSession();
for (const ch of text) {
await client.send('Input.dispatchKeyEvent', { type: 'char', text: ch });
}
// Press Enter
await client.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13,
});
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter' });
await client.detach();
}
async function sendKeyCombo(keys) {
const page = await _getPage();
if (!page) return;
const client = await page.target().createCDPSession();
const keyMap = {
cmd: { key: 'Meta', code: 'MetaLeft', mod: 8 },
shift: { key: 'Shift', code: 'ShiftLeft', mod: 2 },
alt: { key: 'Alt', code: 'AltLeft', mod: 4 },
ctrl: { key: 'Control', code: 'ControlLeft', mod: 1 },
enter: { key: 'Enter', code: 'Enter' },
esc: { key: 'Escape', code: 'Escape' },
tab: { key: 'Tab', code: 'Tab' },
};
const parts = keys.toLowerCase().split('+').map(s => s.trim());
const modifiers = [];
let mainKey = null;
for (const p of parts) {
if (keyMap[p] && keyMap[p].mod) modifiers.push(keyMap[p]);
else mainKey = p;
}
let modFlag = modifiers.reduce((f, m) => f | m.mod, 0);
for (const m of modifiers) {
await client.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: m.key, code: m.code, modifiers: modFlag,
});
}
if (mainKey) {
const mapped = keyMap[mainKey];
if (mapped) {
await client.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: mapped.key, code: mapped.code, modifiers: modFlag,
});
await client.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: mapped.key, code: mapped.code, modifiers: modFlag,
});
} else if (mainKey.length === 1) {
await client.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: mainKey, code: `Key${mainKey.toUpperCase()}`,
text: mainKey, modifiers: modFlag,
});
await client.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: mainKey, code: `Key${mainKey.toUpperCase()}`, modifiers: modFlag,
});
}
}
for (const m of modifiers.reverse()) {
await client.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: m.key, code: m.code, modifiers: 0,
});
}
await client.detach();
}
async function clickButtonByText(targetText) {
const page = await _getPage();
if (!page) return false;
const lower = targetText.toLowerCase();
for (const frame of page.frames()) {
try {
const found = await frame.evaluate((target) => {
const els = document.querySelectorAll('button, [role="button"], a.monaco-button, .ui-button, span.truncate');
for (const el of els) {
const text = (el.textContent || '').trim().replace(/\s+/g, ' ').toLowerCase()
.replace(/[\u23CE\u21B5\u238B]/g, '');
if (text.includes(target) && el.offsetParent !== null) {
const clickable = el.closest('button, a, [role="button"], div[class*="cursor-pointer"]') || el;
clickable.click();
return true;
}
}
return false;
}, lower);
if (found) return true;
} catch {}
}
return false;
}
// ── Handle incoming TG messages ────────────────────────────────────
async function handleMessage(msg) {
const text = (msg.text || '').trim();
const page = await _getPage();
if (!text || !page) return;
if (text === '/screenshot' || text === '/ss') {
log('Screenshot requested');
await sendScreenshot(page, '📸 Current Cursor state');
return;
}
if (text === '/status') {
await sendText('✅ Auto-accept script is running.');
return;
}
if (text === '/help') {
await sendText(
'🤖 <b>Cursor Remote Control</b>\n\n' +
'/ss — Screenshot\n' +
'/status — Check if running\n' +
'/click <text> — Click button by text\n' +
'/key <combo> — Key combo (e.g. cmd+shift+p, enter, esc)\n' +
'/type <text> — Type without pressing Enter\n' +
'Any other text — Type into Cursor chat + Enter'
);
return;
}
if (text.startsWith('/click ')) {
const target = text.slice(7).trim();
log(`Click requested: "${target}"`);
const ok = await clickButtonByText(target);
await sendText(ok ? `✅ Clicked "${target}"` : `❌ Button "${target}" not found`);
return;
}
if (text.startsWith('/key ')) {
const combo = text.slice(5).trim();
log(`Key combo: ${combo}`);
await sendKeyCombo(combo);
await sendText(`⌨️ Sent: ${combo}`);
return;
}
if (text.startsWith('/type ')) {
const content = text.slice(6);
log(`Type (no enter): "${content}"`);
const page2 = await _getPage();
const client = await page2.target().createCDPSession();
for (const ch of content) {
await client.send('Input.dispatchKeyEvent', { type: 'char', text: ch });
}
await client.detach();
await sendText(`✅ Typed: ${content}`);
return;
}
// Default: type into Cursor chat + press Enter
log(`Typing into Cursor: "${text}"`);
await typeIntoCursor(text);
await sendText(`✅ Sent to Cursor: ${text}`);
}
async function handleCallbackQuery(cb) {
const data = cb.data || '';
const page = await _getPage();
if (!page) return;
// Acknowledge the callback
tgApi('answerCallbackQuery', { callback_query_id: cb.id }).catch(() => {});
if (data.startsWith('click:')) {
const target = data.slice(6);
log(`Inline button click: "${target}"`);
const ok = await clickButtonByText(target);
await sendText(ok ? `✅ Clicked "${target}"` : `❌ "${target}" not found`);
} else if (data === 'screenshot') {
await sendScreenshot(page, '📸 Updated screenshot');
} else if (data === 'ignore') {
await sendText('👌 Ignored');
}
}
// ── Polling loop ───────────────────────────────────────────────────
async function pollOnce() {
try {
const res = await tgApi('getUpdates', {
offset: updateOffset,
timeout: 10,
allowed_updates: ['message', 'callback_query'],
});
if (!res.ok) {
log(`getUpdates failed: ${JSON.stringify(res).slice(0, 200)}`);
return;
}
if (!res.result || res.result.length === 0) return;
log(`Received ${res.result.length} update(s)`);
for (const update of res.result) {
updateOffset = update.update_id + 1;
try {
if (update.message) {
const chatId = String(update.message.chat.id);
const expected = String(CHAT_ID);
if (chatId === expected) {
await handleMessage(update.message);
} else {
log(`Ignored message from chat ${chatId} (expected ${expected})`);
}
}
if (update.callback_query) {
const fromId = String(update.callback_query.from.id);
if (fromId === String(CHAT_ID)) {
await handleCallbackQuery(update.callback_query);
}
}
} catch (e) {
log(`Error handling update: ${e.message}`);
}
}
} catch (e) {
log(`Poll error: ${e.message}`);
}
}
async function startPolling() {
if (PROXY_URL) log(`Using proxy: ${PROXY_URL}`);
log('Telegram bot polling started');
while (true) {
await pollOnce();
await new Promise(r => setTimeout(r, 500));
}
}
// ── Public API ─────────────────────────────────────────────────────
function init(pageGetter) {
_getPage = pageGetter;
}
async function notifyBlocked(description, buttonLabels) {
if (!enabled()) return;
const page = await _getPage();
const buttons = [];
if (buttonLabels?.length) {
const row = buttonLabels.slice(0, 4).map(label => ({
text: label, callback_data: `click:${label}`,
}));
buttons.push(row);
}
buttons.push([
{ text: '📸 Screenshot', callback_data: 'screenshot' },
{ text: '👌 Ignore', callback_data: 'ignore' },
]);
if (page) {
await sendScreenshot(page, `🔔 <b>Cursor needs attention</b>\n${description}`, buttons);
} else {
await sendText(`🔔 <b>Cursor needs attention</b>\n${description}`, buttons);
}
}
let _pollingStarted = false;
function start(pageGetter) {
if (!enabled()) return;
init(pageGetter);
if (_pollingStarted) return;
_pollingStarted = true;
startPolling().catch(e => log(`Polling error: ${e.message}`));
}
module.exports = { enabled, start, init, notifyBlocked, sendText, sendScreenshot };