-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
339 lines (320 loc) · 15.8 KB
/
Copy pathscript.js
File metadata and controls
339 lines (320 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
/* Paste this file into the console at web.telegram.org/a/ or /k/.
* The OpenAI key is requested at runtime and is not stored in this file.
*/
(async () => {
'use strict';
const NAME = 'Telegram Web OpenAI Integration';
const VERSION = '2.3';
const CONFIG = {
model: 'gpt-4.1-mini',
systemPrompt: 'Ты — дружелюбный помощник проекта. Отвечай на языке клиента. Если не знаешь ответа, скажи об этом. Не выдумывай цены, сроки и обещания.',
pollMs: 2000,
retryMs: 30000,
historyLimit: 20,
maxReplyCharacters: 3500,
dryRun: false
};
if (!/^https:\/\/web\.telegram\.org\/(a|k)\//.test(location.href)) {
console.error(NAME + ': open Telegram Web A or K first.');
return;
}
if (window.TelegramWebOpenAIIntegration) window.TelegramWebOpenAIIntegration.stop();
const variant = location.pathname.startsWith('/a/') ? 'A' : 'K';
function requestKey() {
return new Promise(resolve => {
const panel = document.createElement('div');
panel.id = 'telegram-openai-key-panel';
panel.style.cssText = 'position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.65);font:14px Arial,sans-serif';
const box = document.createElement('div');
box.style.cssText = 'width:min(420px,90vw);padding:24px;border-radius:12px;background:#fff;color:#111;box-shadow:0 8px 32px #0006';
const title = document.createElement('div');
title.textContent = 'OpenAI API key';
title.style.cssText = 'font-size:18px;font-weight:bold;margin-bottom:10px';
const note = document.createElement('div');
note.textContent = 'Ключ останется только в памяти этой вкладки. Не вставляйте его в консоль.';
note.style.cssText = 'margin-bottom:14px;line-height:1.4';
const input = document.createElement('input');
input.type = 'password';
input.autocomplete = 'off';
input.placeholder = 'sk-...';
input.setAttribute('aria-label', 'OpenAI API key');
input.style.cssText = 'box-sizing:border-box;width:100%;padding:10px;border:1px solid #999;border-radius:6px';
const actions = document.createElement('div');
actions.style.cssText = 'display:flex;gap:8px;justify-content:flex-end;margin-top:16px';
const cancel = document.createElement('button');
cancel.type = 'button';
cancel.textContent = 'Отмена';
const submit = document.createElement('button');
submit.type = 'button';
submit.textContent = 'Запустить';
for (const button of [cancel, submit]) button.style.cssText = 'padding:8px 14px;cursor:pointer';
function finish(value) {
input.value = '';
panel.remove();
resolve(value);
}
cancel.addEventListener('click', () => finish(''));
submit.addEventListener('click', () => finish(input.value.trim()));
actions.append(cancel, submit);
box.append(title, note, input, actions);
panel.append(box);
document.body.append(panel);
input.focus();
});
}
const key = CONFIG.dryRun ? '' : await requestKey();
if (!CONFIG.dryRun && (!key || !key.trim())) {
console.warn(NAME + ': no API key; nothing started.');
return;
}
const seenRows = new Map();
const seenMessages = new Map();
const completed = new Map();
const pending = new Set();
const retryAfter = new Map();
let timer = null;
let stopped = false;
let busy = false;
let abortController = null;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const log = (...args) => console.log('[' + NAME + ' ' + VERSION + ']', ...args);
const warn = (...args) => console.warn('[' + NAME + ' ' + VERSION + ']', ...args);
function chatRows() {
const selector = variant === 'A' ? '.chat-list .chat-item-clickable' : '.chatlist .row-clickable';
return [...document.querySelectorAll(selector)].map(element => {
const link = element.matches('a[href]') ? element : element.querySelector('a[href]');
const href = link?.getAttribute('href') || element.getAttribute('href') || '';
const id = href.match(/#([^/?]+)/)?.[1] || element.getAttribute('data-peer-id');
if (!id) return null;
const isGroup = element.classList.contains('group') || element.classList.contains('channel') || id.startsWith('-');
const muted = !!element.querySelector('.icon-muted, .dialog-subtitle-badge.muted');
const badge = variant === 'A'
? element.querySelector('.chat-badge-transition')
: element.querySelector('.dialog-subtitle-badge.unread');
const unread = !!badge;
const unreadCount = (badge?.textContent || '').trim();
const preview = (element.querySelector('.last-message-summary, .dialog-subtitle-span-last')?.textContent || '').trim();
const date = (element.querySelector('.date, .time, .dialog-title-details')?.textContent || '').trim();
return { element, id, isGroup, muted, unread, preview, signature: [preview, date, unreadCount, unread].join('\u0000') };
}).filter(Boolean);
}
function currentChatId() {
return location.hash.match(/^#([^/?]+)/)?.[1] || '';
}
function messageElements() {
return variant === 'A'
? [...document.querySelectorAll('.messages-layout .message-list-item')]
: [...document.querySelectorAll('.bubbles-date-group .bubble[data-mid], .bubbles-date-group .bubble[data-message-id]')];
}
function readMessage(element, index) {
const own = element.classList.contains('own') || element.classList.contains('is-out');
const id = element.getAttribute('data-message-id') || element.getAttribute('data-mid') || element.id || '';
const content = element.querySelector('.text-content, .translatable-message, .message');
if (!content) return null;
const copy = content.cloneNode(true);
copy.querySelectorAll('.MessageMeta, .message-time, .time, .reactions, .reply, .forwarded, .MessageOutgoingStatus').forEach(node => node.remove());
const text = (copy.textContent || '').replace(/[\uE000-\uF8FF]/g, '').replace(/\s+/g, ' ').trim();
return text ? { id: id || index + ':' + text, own, text } : null;
}
function currentMessages() {
return messageElements().map(readMessage).filter(Boolean);
}
function lastLoadedMessage() {
const elements = messageElements();
return elements.length ? readMessage(elements[elements.length - 1], elements.length - 1) : null;
}
function composer() {
return variant === 'A'
? document.querySelector('#editable-message-text[contenteditable="true"]')
: document.querySelector('.chat-input .input-message-input[contenteditable="true"]');
}
async function openChat(row) {
const target = row.element.matches('a') ? row.element : row.element.querySelector('a[href]') || row.element;
if (currentChatId() !== row.id) {
target.dispatchEvent(new MouseEvent('mousedown', { view: window, bubbles: true, cancelable: true }));
await sleep(150);
if (currentChatId() !== row.id) target.click();
}
for (let i = 0; i < 20 && !stopped; i++) {
const freshRow = chatRows().find(item => item.id === row.id);
const selected = variant !== 'A' || !!freshRow?.element.classList.contains('selected');
if (currentChatId() === row.id && selected && composer()) {
await sleep(500);
return true;
}
await sleep(150);
}
return false;
}
async function requestReply(messages) {
abortController = new AbortController();
const timeout = setTimeout(() => abortController.abort(), 30000);
try {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + key.trim() },
body: JSON.stringify({
model: CONFIG.model,
messages: [
{ role: 'system', content: CONFIG.systemPrompt },
...messages.slice(-CONFIG.historyLimit).map(m => ({ role: m.own ? 'assistant' : 'user', content: m.text }))
]
}),
signal: abortController.signal
});
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error('OpenAI HTTP ' + response.status + ': ' + (data.error?.message || response.statusText));
const reply = data.choices?.[0]?.message?.content;
if (typeof reply !== 'string' || !reply.trim()) throw new Error('OpenAI returned an empty reply');
return reply.trim().slice(0, CONFIG.maxReplyCharacters);
} finally {
clearTimeout(timeout);
abortController = null;
}
}
async function sendReply(chatId, expectedId, reply) {
if (stopped || currentChatId() !== chatId) return false;
const before = lastLoadedMessage();
if (!before || before.id !== expectedId || before.own) return false;
const input = composer();
if (!input || input.textContent.trim()) {
warn('Composer unavailable or contains a draft; reply was not sent.');
return false;
}
input.focus();
if (!document.execCommand('insertText', false, reply)) {
warn('Telegram editor rejected text insertion; reply was not sent.');
return false;
}
await sleep(200);
if (currentChatId() !== chatId || input.textContent.trim() !== reply) {
warn('Chat or draft changed before sending; reply was not sent.');
return false;
}
const button = variant === 'A'
? document.querySelector('button[title="Send Message"], button[aria-label="Send Message"]')
: document.querySelector('.chat-input .btn-send');
if (!button || button.disabled) {
warn('Send button was not found; reply remains in the draft.');
return false;
}
button.click();
for (let i = 0; i < 12 && !stopped; i++) {
await sleep(250);
const after = lastLoadedMessage();
if (after?.own && after.text === reply) return true;
}
warn('Send was clicked, but no outgoing message was verified. Automatic retry is disabled for this message.');
return undefined;
}
async function handle(row) {
if (!await openChat(row)) throw new Error('Could not open chat ' + row.id);
const messages = currentMessages();
const last = lastLoadedMessage();
if (!last || last.own || completed.get(row.id) === last.id) return true;
if (CONFIG.dryRun) {
log('Dry run: incoming text detected', { chatId: row.id, messageId: last.id });
completed.set(row.id, last.id);
return true;
}
const reply = await requestReply(messages);
const sent = await sendReply(row.id, last.id, reply);
if (sent === undefined) {
completed.set(row.id, last.id);
return true;
}
if (sent) {
completed.set(row.id, last.id);
log('Reply sent', { chatId: row.id, messageId: last.id });
}
return sent;
}
async function tick() {
if (stopped || busy) return;
busy = true;
try {
const rows = chatRows();
if (!rows.length) {
warn('No chat list found for Web ' + variant + '; waiting.');
return;
}
const active = rows.find(row => row.id === currentChatId());
if (active && !active.isGroup && !active.muted && active.id !== '777000') {
const last = lastLoadedMessage();
if (last) {
const previousId = seenMessages.get(active.id);
seenMessages.set(active.id, last.id);
if (previousId && previousId !== last.id && !last.own &&
(retryAfter.get(active.id) || 0) <= Date.now()) {
try {
const success = await handle(active);
if (success) {
retryAfter.delete(active.id);
pending.delete(active.id);
}
else retryAfter.set(active.id, Date.now() + CONFIG.retryMs);
} catch (error) {
warn('Chat ' + active.id + ':', error);
retryAfter.set(active.id, Date.now() + CONFIG.retryMs);
}
return;
}
}
}
for (const row of rows) {
if (row.isGroup || row.muted || row.id === '777000') continue;
const previous = seenRows.get(row.id);
seenRows.set(row.id, row.signature);
// Rows present at startup were recorded below. An unknown row appeared later,
// so it may be a newly arrived private chat even when Web A shows no badge.
if (previous === undefined && !row.preview) continue;
if (previous === row.signature && !retryAfter.has(row.id) && !pending.has(row.id)) continue;
if ((retryAfter.get(row.id) || 0) > Date.now()) continue;
try {
const success = await handle(row);
if (success) {
retryAfter.delete(row.id);
pending.delete(row.id);
} else retryAfter.set(row.id, Date.now() + CONFIG.retryMs);
} catch (error) {
warn('Chat ' + row.id + ':', error);
retryAfter.set(row.id, Date.now() + CONFIG.retryMs);
}
break;
}
} finally {
busy = false;
if (!stopped) timer = setTimeout(tick, CONFIG.pollMs);
}
}
window.TelegramWebOpenAIIntegration = {
version: VERSION,
variant,
stop() {
stopped = true;
clearTimeout(timer);
abortController?.abort();
log('Stopped');
},
status() {
return { version: VERSION, variant, running: !stopped, busy, watchedChats: seenRows.size, dryRun: CONFIG.dryRun };
},
async processCurrent() {
const row = chatRows().find(item => item.id === currentChatId());
if (!row || row.isGroup || row.id === '777000') throw new Error('Open a private user chat first');
if (busy) throw new Error('Already processing another chat');
busy = true;
try { return await handle(row); }
finally { busy = false; }
}
};
for (const row of chatRows()) {
seenRows.set(row.id, row.signature);
if (row.unread && !row.isGroup && !row.muted && row.id !== '777000') pending.add(row.id);
}
const initialId = currentChatId();
const initialLast = lastLoadedMessage();
if (initialId && initialLast) seenMessages.set(initialId, initialLast.id);
log('Started for Telegram Web ' + variant, window.TelegramWebOpenAIIntegration.status());
timer = setTimeout(tick, CONFIG.pollMs);
})();