Бот для капчи в чатах
Roman Sergienko
11 hours ago d9c4c369924d1874e68b19ed93aa1aefa439b0cd
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
{% extends "base.html" %}
{% block title %}Сообщения - {{ chat.title or chat.chat_id }}{% endblock %}
{% block header %}Сообщения{% endblock %}
{% block content %}
 
<div class="flex items-center justify-between gap-3">
    <a href="/chats/{{ chat.chat_id }}" class="inline-flex items-center gap-1 text-sm text-brand-600 hover:underline dark:text-brand-400">
        ← Назад к чату
    </a>
    <span class="truncate text-xs text-gray-500">{{ chat.title or chat.chat_id }} · id {{ chat.chat_id }}</span>
</div>
 
<section class="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900">
    <div id="msg-list" class="flex max-h-[58vh] flex-col gap-2 overflow-y-auto p-3 md:max-h-[62vh]">
        {% for m in msgs %}
        {% set is_bot = m.name and m.name.startswith('Amadeus') %}
        <div class="msg flex {{ 'justify-end' if is_bot else 'justify-start' }}"
             data-id="{{ m.id }}" data-tg="{{ m.tg_msg_id or 0 }}" data-name="{{ m.name }}">
            <div class="max-w-[82%] rounded-2xl px-3 py-2 text-sm shadow-sm
                {% if is_bot %}bg-brand-600 text-white{% else %}bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100{% endif %}">
                <div class="mb-0.5 text-xs font-semibold {% if is_bot %}text-white/80{% else %}text-brand-600 dark:text-brand-400{% endif %}">{{ m.name }}</div>
                {% if m.reply_to_tg %}
                <div class="mb-1 rounded-lg border-l-2 px-2 py-1 text-[11px]
                    {% if is_bot %}border-white/50 bg-white/10 text-white/80{% else %}border-brand-400 bg-black/5 text-gray-600 dark:bg-white/5 dark:text-gray-300{% endif %}">
                    <div class="font-medium">↪ {{ m.reply_to_name or "сообщение" }}</div>
                    {% if m.reply_to_text %}<div class="truncate">{{ m.reply_to_text }}</div>{% endif %}
                </div>
                {% endif %}
                {% if m.media_type %}
                <img src="/media/{{ m.id }}" alt="{{ m.media_type }}" loading="lazy"
                     class="mb-1 max-h-60 rounded-lg" onerror="this.style.display='none'">
                {% endif %}
                {% if m.text %}<div class="whitespace-pre-wrap break-words">{{ m.text }}</div>{% endif %}
                <div class="mt-1 flex items-center justify-end gap-2 text-[10px] {% if is_bot %}text-white/70{% else %}text-gray-400{% endif %}">
                    <span>{{ fmt_dt(m.created_at) }}</span>
                    <button type="button" class="reply-btn hover:underline">ответить</button>
                </div>
            </div>
        </div>
        {% else %}
        <div id="empty" class="px-4 py-8 text-center text-gray-500">Сообщений пока нет.</div>
        {% endfor %}
    </div>
</section>
 
<section class="rounded-xl border border-gray-200 bg-white p-3 shadow-sm dark:border-gray-800 dark:bg-gray-900 md:p-4">
    <div id="reply-bar" class="mb-2 hidden items-center justify-between rounded-lg bg-gray-100 px-3 py-2 text-xs dark:bg-gray-800">
        <span class="truncate">Ответ: <span id="reply-to-name" class="font-medium"></span></span>
        <button type="button" id="reply-cancel" class="shrink-0 text-gray-500 hover:text-red-500">отмена</button>
    </div>
    <form id="say-form">
        <input type="hidden" name="chat_id" value="{{ chat.chat_id }}">
        <input type="hidden" name="reply_to" id="reply-to" value="0">
        <textarea id="say-text" rows="2" placeholder="Сообщение от имени Амадеуса..."
                  class="w-full resize-none rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm dark:border-gray-700"></textarea>
        <div class="mt-2 flex items-center justify-between gap-2">
            <span id="say-status" class="text-xs text-gray-500"></span>
            <button class="rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700">Отправить</button>
        </div>
        <p class="mt-1 text-[11px] text-gray-400">Enter — отправить, Ctrl+Enter (или Shift+Enter) — новая строка. Сообщение уйдёт с пометкой «От &lt;ваше имя&gt;».</p>
    </form>
</section>
 
<script>
(function () {
    const chatId = "{{ chat.chat_id }}";
    const list = document.getElementById("msg-list");
    const statusEl = document.getElementById("say-status");
    const replyBar = document.getElementById("reply-bar");
    const replyTo = document.getElementById("reply-to");
    const replyName = document.getElementById("reply-to-name");
    const text = document.getElementById("say-text");
    const form = document.getElementById("say-form");
    let lastId = {{ msgs[-1].id if msgs else 0 }};
 
    function esc(s) { const d = document.createElement("div"); d.textContent = s == null ? "" : s; return d.innerHTML; }
    function atBottom() { return list.scrollTop + list.clientHeight >= list.scrollHeight - 40; }
    function toBottom() { list.scrollTop = list.scrollHeight; }
 
    function bindReply(wrap) {
        const btn = wrap.querySelector(".reply-btn");
        if (!btn) return;
        btn.addEventListener("click", function () {
            replyTo.value = wrap.dataset.tg || 0;
            replyName.textContent = wrap.dataset.name || "";
            replyBar.classList.remove("hidden");
            replyBar.classList.add("flex");
            text.focus();
        });
    }
    document.querySelectorAll(".msg").forEach(bindReply);
 
    document.getElementById("reply-cancel").addEventListener("click", function () {
        replyTo.value = 0;
        replyBar.classList.add("hidden");
        replyBar.classList.remove("flex");
    });
 
    function bubble(m) {
        const isBot = (m.name || "").startsWith("Amadeus");
        const wrap = document.createElement("div");
        wrap.className = "msg flex " + (isBot ? "justify-end" : "justify-start");
        wrap.dataset.id = m.id;
        wrap.dataset.tg = m.tg_msg_id || 0;
        wrap.dataset.name = m.name || "";
        const box = document.createElement("div");
        box.className = "max-w-[82%] rounded-2xl px-3 py-2 text-sm shadow-sm " +
            (isBot ? "bg-brand-600 text-white" : "bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100");
        let html = '<div class="mb-0.5 text-xs font-semibold ' +
            (isBot ? "text-white/80" : "text-brand-600 dark:text-brand-400") + '">' + esc(m.name) + "</div>";
        if (m.reply_to_tg) {
            html += '<div class="mb-1 rounded-lg border-l-2 px-2 py-1 text-[11px] ' +
                (isBot ? "border-white/50 bg-white/10 text-white/80" : "border-brand-400 bg-black/5 text-gray-600 dark:bg-white/5 dark:text-gray-300") + '">' +
                '<div class="font-medium">↪ ' + esc(m.reply_to_name || "сообщение") + "</div>" +
                (m.reply_to_text ? '<div class="truncate">' + esc(m.reply_to_text) + "</div>" : "") + "</div>";
        }
        if (m.media_type && m.id) {
            html += '<img src="/media/' + m.id + '" class="mb-1 max-h-60 rounded-lg" loading="lazy" onerror="this.style.display=\'none\'">';
        }
        if (m.text) html += '<div class="whitespace-pre-wrap break-words">' + esc(m.text) + "</div>";
        html += '<div class="mt-1 flex items-center justify-end gap-2 text-[10px] ' +
            (isBot ? "text-white/70" : "text-gray-400") + '"><span>' + esc(m.time || "") +
            '</span><button type="button" class="reply-btn hover:underline">ответить</button></div>';
        box.innerHTML = html;
        wrap.appendChild(box);
        return wrap;
    }
 
    function addMsg(m, scroll) {
        const empty = document.getElementById("empty");
        if (empty) empty.remove();
        const wrap = bubble(m);
        list.appendChild(wrap);
        bindReply(wrap);
        if (scroll) toBottom();
    }
 
    // Enter — отправить; Ctrl/Shift/Alt+Enter — новая строка.
    text.addEventListener("keydown", function (e) {
        if (e.key === "Enter" && !e.ctrlKey && !e.shiftKey && !e.metaKey && !e.altKey) {
            e.preventDefault();
            form.requestSubmit();
        }
    });
 
    form.addEventListener("submit", async function (e) {
        e.preventDefault();
        const val = text.value.trim();
        if (!val) return;
        const body = new URLSearchParams({ chat_id: chatId, text: val, reply_to: replyTo.value });
        text.disabled = true;
        statusEl.textContent = "Отправка...";
        try {
            const r = await fetch("/api/say", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: body });
            const j = await r.json();
            if (j.ok) {
                text.value = "";
                replyTo.value = 0;
                replyBar.classList.add("hidden");
                replyBar.classList.remove("flex");
                statusEl.textContent = "";
                addMsg(j.message, true);
                lastId = j.message.id;
            } else {
                statusEl.textContent = j.msg || "Ошибка отправки.";
            }
        } catch (err) {
            statusEl.textContent = "Ошибка сети.";
        } finally {
            text.disabled = false;
            text.focus();
        }
    });
 
    async function poll() {
        try {
            const r = await fetch("/api/messages?chat_id=" + encodeURIComponent(chatId) + "&after=" + lastId);
            const j = await r.json();
            if (j.messages && j.messages.length) {
                const stick = atBottom();
                j.messages.forEach(function (m) { if (m.id > lastId) { addMsg(m, false); lastId = m.id; } });
                if (stick) toBottom();
            }
        } catch (err) { /* тихо */ }
    }
 
    toBottom();
    setInterval(poll, 3000);
    text.focus();
})();
</script>
 
{% endblock %}