Repository navigation
Expand file tree
/
Copy pathadmin.html
More file actions
1076 lines (930 loc) · 52 KB
/
Copy pathadmin.html
File metadata and controls
1076 lines (930 loc) · 52 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<script>
// === CONFIGURATION ===
const BOT_TOKEN = 'ВАШ-ТОКЕН';
const SUPABASE_URL = 'https://your-database.supabase.co';
const SUPABASE_ANON_KEY = 'ВАШ-API-KEY';
</script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Telegram Bot Admin Panel</title>
<link rel="icon" type="image/x-icon" href="https://web.telegram.org/favicon.ico">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--bg-primary: #0e1621;
--bg-secondary: #0e1621;
--bg-tertiary: #2b5278;
--text-primary: #ffffff;
--text-secondary: #8b949e;
--text-active: #ffffff;
--accent-color: #5288c1;
--border-color: #0e1621;
--message-in: #182533;
--message-out: #2b5278;
--message-out-text: #ffffff;
--hover-bg: #17212b;
--listchats-color: #17212b;
}
body.light {
--bg-primary: #ffffff;
--bg-secondary: #6ca587;
--bg-tertiary: #419fd9;
--text-primary: #222222;
--text-secondary: #707579;
--accent-color: #0088cc;
--border-color: #e5e5e5;
--message-in: #ffffff;
--message-out: #effdde;
--message-out-text: #222222;
--hover-bg: #f8f8f8;
--listchats-color: #ffffff;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: var(--bg-secondary);
height: 100vh;
overflow: hidden;
color: var(--text-primary);
}
.container {
display: flex;
height: 100vh;
/*max-width: 1400px;*/
margin: 0 auto;
background: var(--bg-primary);
}
/* Боковая панель со списком чатов */
.sidebar {
width: 350px;
border-right: 1px solid var(--border-color);
display: flex;
flex-direction: column;
background: var(--bg-primary);
}
.sidebar-header {
padding: 20px;
background: var(--hover-bg);
color: var(--text-primary);
font-size: 18px;
font-weight: 600;
display: flex;
/*justify-content: space-between;*/
justify-content: start;
align-items: center;
}
.theme-toggle, .sound-toggle {
background: var(--accent-color);
border: none;
color: white;
padding: 8px 12px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
transition: opacity 0.2s;
margin-right:10px;
}
.theme-toggle:hover, .sound-toggle:hover {
opacity: 0.8;
}
.sound-toggle.muted {
opacity: 0.5;
}
.chat-list {
flex: 1;
overflow-y: auto;
background: var(--listchats-color);
}
.chat-item {
padding: 15px 20px;
border-bottom: 1px solid var(--border-color);
cursor: pointer;
transition: background 0.15s;
display: flex;
align-items: center;
gap: 12px;
}
.chat-item:hover {
background: var(--hover-bg);
}
.chat-item.active {
background: var(--bg-tertiary);
}
.chat-avatar {
width: 48px;
height: 48px;
border-radius: 50%;
/*background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);*/
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 600;
font-size: 18px;
flex-shrink: 0;
}
.chat-info {
flex: 1;
min-width: 0;
}
.chat-name {
font-weight: 600;
color: var(--text-primary);
margin-bottom: 4px;
}
.chat-preview {
font-size: 14px;
color: var(--text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.chat-time {
font-size: 12px;
color: var(--text-secondary);
white-space: nowrap;
}
.chat-item.active .chat-name {
color: var(--text-active);
}
.chat-item.active .chat-preview {
color: var(--text-active);
}
.chat-item.active .chat-time {
color: var(--text-active);
}
/* Область чата */
.chat-area {
flex: 1;
display: flex;
flex-direction: column;
background: var(--bg-secondary);
}
.chat-header {
padding: 15px 20px;
background: var(--hover-bg);
border-bottom: 1px solid var(--border-color);
display: flex;
align-items: center;
gap: 12px;
}
.chat-header-avatar {
width: 40px;
height: 40px;
border-radius: 50%;
/*background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);*/
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 600;
}
.chat-header-info h2 {
font-size: 16px;
color: var(--text-primary);
margin-bottom: 2px;
}
.chat-header-info p {
font-size: 13px;
color: var(--text-secondary);
}
.messages-container {
flex: 1;
overflow-y: auto;
padding: 20px;
display: flex;
flex-direction: column;
gap: 8px;
}
.message {
display: flex;
margin-bottom: 8px;
}
.message.user {
justify-content: flex-start;
}
.message.assistant {
justify-content: flex-end;
}
.message-bubble {
max-width: 65%;
padding: 10px 14px;
border-radius: 12px;
word-wrap: break-word;
position: relative;
}
.message.assistant .message-bubble {
background: var(--message-out);
color: var(--message-out-text);
border-bottom-right-radius: 4px;
}
.message.user .message-bubble {
background: var(--message-in);
color: var(--text-primary);
border-bottom-left-radius: 4px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.message-content {
margin-bottom: 4px;
line-height: 1.5;
}
.message-time {
font-size: 11px;
color: var(--text-secondary);
text-align: right;
}
.date-separator {
text-align: center;
margin: 16px 0;
font-size: 13px;
color: var(--text-secondary);
}
/* Поле ввода */
.input-area {
padding: 10px;
background: var(--listchats-color);
border-top: 1px solid var(--border-color);
display: flex;
gap: 12px;
align-items: flex-end;
}
.message-input {
flex: 1;
padding: 12px 16px;
border: none;
border-radius: 20px;
font-size: 15px;
font-family: inherit;
resize: none;
max-height: 120px;
overflow-y: auto;
color: var(--text-primary);
background: transparent;
}
.message-input:focus {
outline: none;
border-color: var(--accent-color);
}
.send-button {
width: 44px;
height: 44px;
border: none;
/*background: var(--accent-color);*/
background: transparent;
color: white;
/*border-radius: 50%;*/
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: opacity 0.2s;
flex-shrink: 0;
}
.send-button:hover {
opacity: 0.8;
}
.send-button:active {
transform: scale(0.95);
}
.send-button:disabled {
/*background: #d5d5d5;*/
cursor: not-allowed;
}
/* Пустое состояние */
.empty-state {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
color: var(--text-secondary);
font-size: 16px;
}
/* Загрузка */
.loading {
text-align: center;
padding: 20px;
color: var(--text-secondary);
}
/* Адаптивный дизайн */
@media (max-width: 768px) {
.sidebar {
width: 100%;
position: absolute;
z-index: 10;
height: 100vh;
}
.sidebar.hidden {
display: none;
}
.chat-area.hidden {
display: none;
}
}
/* Scrollbar styling */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: #c4c4c4;
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #a8a8a8;
}
/* START SCREEN */
.start-screen {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(14, 22, 33, 0.7);
backdrop-filter: blur(5px);
z-index: 9999;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: opacity 0.4s ease, visibility 0.4s ease;
}
body.light .start-screen {
background: rgba(255, 255, 255, 0.7);
}
.start-screen.hidden {
opacity: 0;
visibility: hidden;
pointer-events: none;
}
.start-content {
text-align: center;
animation: pulse 2s ease-in-out infinite;
}
.start-content h2 {
font-size: 28px;
margin-bottom: 10px;
color: var(--text-primary);
}
.start-content p {
font-size: 16px;
color: var(--text-secondary);
}
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.05); }
}
</style>
</head>
<body>
<div id="startScreen" class="start-screen">
<div class="start-content">
<h2>Telegram Bot Admin</h2>
<p>Click to enter</p>
</div>
</div>
<div class="container">
<div class="sidebar" id="sidebar">
<div class="sidebar-header">
<!--<span>Telegram Bot Admin</span>-->
<button class="theme-toggle" onclick="toggleTheme()">🌙 Light</button>
<button class="sound-toggle" onclick="toggleSound()">🔔 Sound</button>
</div>
<div class="chat-list" id="chatList">
<div class="loading">Loading chats...</div>
</div>
</div>
<div class="chat-area" id="chatArea">
<div class="empty-state">
Select a chat to start
</div>
</div>
</div>
<!-- Supabase CDN -->
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
<script>
// Палитра цветов для аватаров (Telegram-style пастельные градиенты)
const AVATAR_COLORS = [
['#e17076', '#d95c5c'],
['#faa774', '#f48847'],
['#a695e7', '#7f6fc8'],
['#6ec9cb', '#54b9bc'],
['#65aadd', '#4c8ed9'],
['#76c84d', '#5fb73e'],
['#f5bd5d', '#f3a543'],
['#ee7aae', '#e8669a'],
['#8e77c5', '#7b63b8'],
['#74abd0', '#5c9ac7']
];
// Простая хеш-функция для user_id
function getUserColorIndex(userId) {
let hash = 0;
const str = String(userId);
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + hash;
}
return hash % AVATAR_COLORS.length;
}
// Создание уведомлений
function createToastNotification(userName, userId, messageText) {
const container = document.getElementById('toastContainer');
if (!container) {
const newContainer = document.createElement('div');
newContainer.id = 'toastContainer';
newContainer.style.cssText = 'position: fixed; bottom: 20px; right: 20px; z-index: 10000; display: flex; flex-direction: column; gap: 10px; max-width: 350px;';
document.body.appendChild(newContainer);
}
const toast = document.createElement('div');
toast.className = 'toast-notification';
toast.style.cssText = 'opacity: 0.9; background: var(--message-in); border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); border: 1px solid var(--border-color); padding: 15px; cursor: pointer; transition: transform 0.2s; display: flex; gap: 12px; align-items: flex-start;';
const initial = userName.charAt(0).toUpperCase();
toast.innerHTML = `
<div style="width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); display: flex; align-items: center; justify-content: center; color: white; font-weight: 600; flex-shrink: 0;">${initial}</div>
<div style="flex: 1; min-width: 0;">
<div style="font-weight: 600; color: var(--text-primary); margin-bottom: 4px;">${userName}</div>
<div style="font-size: 14px; color: var(--text-secondary); overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; line-height: 1.4;">${messageText}</div>
</div>
<div onclick="event.stopPropagation(); this.parentElement.remove(); checkAndRemoveClearButton();" style="color: var(--text-secondary); cursor: pointer; font-size: 18px; line-height: 1; padding: 0 5px;">×</div>
`;
toast.onclick = function() {
if (typeof openChat === 'function') {
openChat(userId);
}
toast.remove();
checkAndRemoveClearButton();
};
toast.onmouseenter = function() {
this.style.transform = 'scale(1.02)';
};
toast.onmouseleave = function() {
this.style.transform = 'scale(1)';
};
document.getElementById('toastContainer').appendChild(toast);
// Автоскрытие через 5 секунд
setTimeout(() => {
if (toast.parentElement) {
toast.style.transition = 'opacity 0.3s, transform 0.3s';
toast.style.opacity = '0';
toast.style.transform = 'translateX(400px)';
setTimeout(() => {
toast.remove();
checkAndRemoveClearButton();
}, 300);
}
}, 10000);
}
// Функция создания кнопки "Скрыть все"
function createClearAllButton() {
const container = document.getElementById('toastContainer');
if (!container) return;
let clearBtn = document.getElementById('clearAllToasts');
if (!clearBtn) {
clearBtn = document.createElement('button');
clearBtn.id = 'clearAllToasts';
clearBtn.textContent = 'Hide all';
clearBtn.style.cssText = 'background: #0088cc; color: white; border: none; padding: 10px 15px; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 600; align-self: flex-end; width: 100%;';
clearBtn.onclick = function() {
const toasts = container.querySelectorAll('.toast-notification');
toasts.forEach(toast => {
toast.style.transition = 'opacity 0.3s, transform 0.3s';
toast.style.opacity = '0';
toast.style.transform = 'translateX(400px)';
setTimeout(() => toast.remove(), 300);
});
this.style.transition = 'opacity 0.3s';
this.style.opacity = '0';
setTimeout(() => this.remove(), 300);
};
container.insertBefore(clearBtn, container.firstChild);
}
}
// Проверка и удаление кнопки если нет уведомлений
function checkAndRemoveClearButton() {
const container = document.getElementById('toastContainer');
if (!container) return;
const toasts = container.querySelectorAll('.toast-notification');
const clearBtn = document.getElementById('clearAllToasts');
if (toasts.length === 0 && clearBtn) {
clearBtn.style.transition = 'opacity 0.3s, transform 0.3s';
clearBtn.style.opacity = '0';
clearBtn.style.transform = 'translateY(20px)';
setTimeout(() => clearBtn.remove(), 300);
}
}
// Обновленная функция показа уведомления с кнопкой
function showToast(userName, userId, messageText) {
createToastNotification(userName, userId, messageText);
createClearAllButton();
}
// Инициализация Supabase клиента
const supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
// Глобальные переменные
let chats = [];
let currentUserId = null;
let realtimeChannel = null;
let soundEnabled = true;
// Запрос разрешения на уведомления - БЕССМЫСЛЕННО ПРИ ИСПОЛЬЗОВАНИИ ЛОКАЛЬНО НА WINDOWS
if ('Notification' in window && Notification.permission === 'default') {
//Notification.requestPermission();
}
// Переключение темы
function toggleTheme() {
const body = document.body;
const button = document.querySelector('.theme-toggle');
body.classList.toggle('light');
if (body.classList.contains('light')) {
button.textContent = '🌙 Dark';
localStorage.setItem('theme', 'light');
} else {
button.textContent = '☀️ Light';
localStorage.setItem('theme', 'dark');
}
}
// Переключатель звука
function toggleSound() {
soundEnabled = !soundEnabled;
const button = document.querySelector('.sound-toggle');
if (soundEnabled) {
button.textContent = '🔔 Sound';
button.classList.remove('muted');
localStorage.setItem('sound', 'enabled');
} else {
button.textContent = '🔕 Muted';
button.classList.add('muted');
localStorage.setItem('sound', 'disabled');
}
}
// Загрузка сохраненной темы
function loadTheme() {
const savedSound = localStorage.getItem('sound');
const soundButton = document.querySelector('.sound-toggle');
if (savedSound === 'disabled') {
soundEnabled = false;
soundButton.textContent = '🔕 Muted';
soundButton.classList.add('muted');
} else {
soundEnabled = true;
soundButton.textContent = '🔔 Sound';
}
const savedTheme = localStorage.getItem('theme');
const button = document.querySelector('.theme-toggle');
if (savedTheme === 'light') {
document.body.classList.add('light');
button.textContent = '🌙 Dark';
} else {
button.textContent = '☀️ Light';
}
}
// Инициализация приложения
async function init() {
loadTheme();
await loadChats();
subscribeToRealtime();
}
// Загрузка списка чатов
async function loadChats() {
try {
const { data, error } = await supabase
.from('chat_logs')
.select('*')
.order('created_at', { ascending: false });
if (error) {
throw error;
}
// Группировка сообщений по user_id
const chatMap = new Map();
data.forEach(msg => {
const existing = chatMap.get(msg.user_id);
if (!existing || new Date(msg.created_at) > new Date(existing.last_time)) {
chatMap.set(msg.user_id, {
user_id: msg.user_id,
first_name: msg.first_name,
username: msg.username,
last_message: msg.content,
last_time: msg.created_at
});
}
});
chats = Array.from(chatMap.values());
chats.sort((a, b) => new Date(b.last_time) - new Date(a.last_time));
renderChatList();
} catch (error) {
console.error('Ошибка загрузки чатов:', error);
document.getElementById('chatList').innerHTML = '<div class="loading">Error loading chats</div>';
}
}
// Отображение списка чатов
function renderChatList() {
const chatListEl = document.getElementById('chatList');
if (chats.length === 0) {
chatListEl.innerHTML = '<div class="loading">The chat list is empty</div>';
return;
}
chatListEl.innerHTML = chats.map(chat => {
const displayName = chat.first_name || chat.username || 'User';
const initial = displayName.charAt(0).toUpperCase();
const preview = chat.last_message ? chat.last_message.substring(0, 50) : 'No messages';
const time = formatTime(chat.last_time);
const isActive = chat.user_id === currentUserId ? 'active' : '';
const colorIndex = getUserColorIndex(chat.user_id);
const colors = AVATAR_COLORS[colorIndex];
const gradient = `linear-gradient(135deg, ${colors[0]} 0%, ${colors[1]} 100%)`;
return `
<div class="chat-item ${isActive}" onclick="openChat('${chat.user_id}')">
<div class="chat-avatar" style="background: ${gradient}">${initial}</div>
<div class="chat-info">
<div class="chat-name">${displayName}</div>
<div class="chat-preview">${preview}</div>
</div>
<div class="chat-time">${time}</div>
</div>
`;
}).join('');
}
// Открытие чата
async function openChat(userId) {
currentUserId = userId;
renderChatList();
const chat = chats.find(c => c.user_id === userId);
const displayName = chat.first_name || chat.username || 'User';
const initial = displayName.charAt(0).toUpperCase();
// Загрузка сообщений
try {
const { data, error } = await supabase
.from('chat_logs')
.select('*')
.eq('user_id', userId)
.order('created_at', { ascending: true });
if (error) {
throw error;
}
renderChatArea(displayName, initial, data);
// Скрытие sidebar на мобильных
if (window.innerWidth <= 768) {
document.getElementById('sidebar').classList.add('hidden');
}
} catch (error) {
console.error('Ошибка загрузки сообщений:', error);
}
}
// Отображение области чата
function renderChatArea(displayName, initial, messages) {
const chatAreaEl = document.getElementById('chatArea');
let messagesHtml = '';
let lastDate = null;
messages.forEach(msg => {
const msgDate = new Date(msg.created_at).toLocaleDateString('ru-RU');
if (msgDate !== lastDate) {
messagesHtml += `<div class="date-separator">${msgDate}</div>`;
lastDate = msgDate;
}
const time = new Date(msg.created_at).toLocaleTimeString('ru-RU', {
hour: '2-digit',
minute: '2-digit'
});
const role = msg.role || 'user';
messagesHtml += `
<div class="message ${role}">
<div class="message-bubble">
<div class="message-content">${escapeHtml(msg.content)}</div>
<div class="message-time">${time}</div>
</div>
</div>
`;
});
const colorIndex = getUserColorIndex(currentUserId);
const colors = AVATAR_COLORS[colorIndex];
const gradient = `linear-gradient(135deg, ${colors[0]} 0%, ${colors[1]} 100%)`;
chatAreaEl.innerHTML = `
<div class="chat-header">
<div class="chat-header-avatar" style="background: ${gradient}">${initial}</div>
<div class="chat-header-info">
<h2>${displayName}</h2>
<p>ID: ${currentUserId}</p>
</div>
</div>
<div class="messages-container" id="messagesContainer">
${messagesHtml}
</div>
<div class="input-area">
<textarea
class="message-input"
id="messageInput"
placeholder="Write a message..."
rows="1"
onkeydown="handleInputKeydown(event)"
></textarea>
<button class="send-button" onclick="sendMessage()" id="sendButton">
<svg width="34" height="34" viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M122.5 84.5C133.563 83.4735 144.23 84.9735 154.5 89C408.469 216.651 662.469 344.318 916.5 472C941.146 489.082 945.979 510.582 931 536.5C928.78 539.021 926.28 541.188 923.5 543C664.833 673 406.167 803 147.5 933C127.128 940.528 109.628 936.362 95 920.5C86.0882 906.847 84.0882 892.181 89 876.5C124.227 781.715 159.727 687.049 195.5 592.5C355.8 565.45 516.134 538.617 676.5 512C516.332 484.416 355.998 457.249 195.5 430.5C158.708 332.959 122.208 235.292 86 137.5C82.7755 109.294 94.9421 91.6268 122.5 84.5Z" fill="#40a7e3"/>
</svg>
</button>
</div>
`;
// Прокрутка к последнему сообщению
const container = document.getElementById('messagesContainer');
container.scrollTop = container.scrollHeight;
// Автоматическое изменение высоты textarea
const input = document.getElementById('messageInput');
input.addEventListener('input', function() {
this.style.height = 'auto';
this.style.height = Math.min(this.scrollHeight, 120) + 'px';
});
}
// Обработка нажатия клавиш в поле ввода
function handleInputKeydown(event) {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
sendMessage();
}
}
// Отправка сообщения
async function sendMessage() {
const input = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');
const content = input.value.trim();
if (!content || !currentUserId) {
return;
}
sendButton.disabled = true;
input.disabled = true;
try {
// Отправка через Telegram Bot API
const telegramResponse = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
chat_id: currentUserId,
text: content
})
});
if (!telegramResponse.ok) {
throw new Error('Telegram API ERROR');
}
// Сохранение в базу данных
const chat = chats.find(c => c.user_id === currentUserId);
const { error } = await supabase
.from('chat_logs')
.insert([{
user_id: currentUserId,
username: chat.username,
first_name: chat.first_name,
session_id: 'user_'+currentUserId, // или генерировать ID
role: 'assistant',
content: content,
created_at: new Date().toISOString()
}]);
if (error) {
throw error;
}
// Очистка поля ввода
input.value = '';
input.style.height = 'auto';
} catch (error) {
console.error('Ошибка отправки сообщения:', error);
alert('Failed to send message. Check your bot token.');
} finally {
sendButton.disabled = false;
input.disabled = false;
input.focus();
}
}
// Подписка на real-time обновления
function subscribeToRealtime() {
realtimeChannel = supabase
.channel('chat_logs_changes')
.on('system', {}, (payload) => {
console.log('Realtime system event:', payload);
})
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'chat_logs'
},
handleNewMessage
)
.subscribe();
}
// Обработка нового сообщения из real-time
function handleNewMessage(payload) {
/// Уведомление от сообщений человека
if(payload.new.role=='user') {
/// Звуковое
if(soundEnabled) {
notify.play().catch(e => console.log('Звук заблокирован:', e));
}
/// Всплывающее
showToast(payload.new.first_name, payload.new.user_id, payload.new.content);
}
const newMsg = payload.new;
// Обновление списка чатов
const chatIndex = chats.findIndex(c => c.user_id === newMsg.user_id);
if (chatIndex >= 0) {
chats[chatIndex].last_message = newMsg.content;
chats[chatIndex].last_time = newMsg.created_at;
chats.sort((a, b) => new Date(b.last_time) - new Date(a.last_time));
} else {
chats.unshift({
user_id: newMsg.user_id,
first_name: newMsg.first_name,
username: newMsg.username,
last_message: newMsg.content,
last_time: newMsg.created_at
});
}
renderChatList();
// Обновление активного чата
if (newMsg.user_id === currentUserId) {
const container = document.getElementById('messagesContainer');
const time = new Date(newMsg.created_at).toLocaleTimeString('ru-RU', {
hour: '2-digit',
minute: '2-digit'
});
const role = newMsg.role || 'user';
const messageEl = document.createElement('div');
messageEl.className = `message ${role}`;
messageEl.innerHTML = `
<div class="message-bubble">
<div class="message-content">${escapeHtml(newMsg.content)}</div>
<div class="message-time">${time}</div>
</div>
`;
container.appendChild(messageEl);
container.scrollTop = container.scrollHeight;
}