working TG YT TW

This commit is contained in:
sShemet
2026-01-07 02:22:34 +05:00
parent 62263b713a
commit 7561e6f411
7 changed files with 592 additions and 534 deletions

246
script.js
View File

@@ -1,131 +1,147 @@
let messages = [
"I wondered why the baseball was getting bigger. Then it hit me.",
"Police were called to a day care, where a three-year-old was resisting a rest.",
"Did you hear about the guy whose whole left side was cut off? Hes all right now.",
"The roundest knight at King Arthurs round table was Sir Cumference.",
"To write with a broken pencil is pointless.",
"When fish are in schools they sometimes take debate.",
"The short fortune teller who escaped from prison was a small medium at large.",
"A thief who stole a calendar… got twelve months.",
"A thief fell and broke his leg in wet cement. He became a hardened criminal.",
"Thieves who steal corn from a garden could be charged with stalking.",
"When the smog lifts in Los Angeles , U. C. L. A.",
"The math professor went crazy with the blackboard. He did a number on it.",
"The professor discovered that his theory of earthquakes was on shaky ground.",
"The dead batteries were given out free of charge.",
"If you take a laptop computer for a run you could jog your memory.",
"A dentist and a manicurist fought tooth and nail.",
"A bicycle cant stand alone; it is two tired.",
"A will is a dead giveaway.",
"Time flies like an arrow; fruit flies like a banana.",
"A backward poet writes inverse.",
"In a democracy its your vote that counts; in feudalism, its your Count that votes.",
"A chicken crossing the road: poultry in motion.",
"If you dont pay your exorcist you can get repossessed.",
"With her marriage she got a new name and a dress.",
"Show me a piano falling down a mine shaft and Ill show you A-flat miner.",
"When a clock is hungry it goes back four seconds.",
"The guy who fell onto an upholstery machine was fully recovered.",
"A grenade fell onto a kitchen floor in France and resulted in Linoleum Blownapart.",
"You are stuck with your debt if you cant budge it.",
"Local Area Network in Australia : The LAN down under.",
"He broke into song because he couldnt find the key.",
"A calendars days are numbered."
];
let nicks = [
"Edvard Force",
"Диванный Воин",
"Yoshka's Cat",
"XAOSHammer",
"Kino Konformist" ];
const chatwin = document.getElementById("chatwin");
const anchor = document.getElementById("anchor");
function randomMessage() {
return messages[(Math.random() * messages.length) | 0];
// Массив ключевых слов для выделения (без учета регистра)
const specialKeywords = ['sergshemet', 'sergeyshemet', 'sshemet', 'сергей', 'серёга', 'админ'];
// Функция для проверки содержит ли сообщение ключевые слова
function containsSpecialKeywords(text) {
const lowerText = text.toLowerCase();
return specialKeywords.some(keyword => lowerText.includes(keyword.toLowerCase()));
}
function randomNick() {
return nicks[(Math.random() * nicks.length) | 0];
}
function randomChat() {
return Math.random() > 0.5 ? "tg" : "yt";
// Создание новой строки чата из JSON данных
function createNewLine(json) {
// Сортируем сообщения по дате (самые старые первыми)
json.sort((a, b) => new Date(a.date) - new Date(b.date));
json.forEach(element => {
// Проверяем, существует ли уже элемент с таким ID
let existingMsg = document.getElementById(element["id"]);
if (existingMsg) {
// Обновляем текст существующего сообщения
existingMsg.innerHTML = element["msg"];
// Проверяем на ключевые слова для подсветки
if (containsSpecialKeywords(element["msg"])) {
existingMsg.classList.add("highlight-message");
} else {
existingMsg.classList.remove("highlight-message");
}
return;
}
// Создаем блок имени
const nameBlock = document.createElement("div");
nameBlock.className = "nameline " + element["type"];
// Для донатов добавляем сумму
if (element["type"] == "donate") {
nameBlock.innerHTML = element["sendr"] + '<br><p style="color: red">' + element['amount'] + "</p>";
} else {
nameBlock.innerHTML = element["sendr"];
}
// Создаем блок сообщения
const msgBlock = document.createElement("div");
msgBlock.className = "msgline";
msgBlock.innerHTML = element["msg"];
msgBlock.id = element["id"];
// Добавляем подсветку если есть ключевые слова
if (containsSpecialKeywords(element["msg"])) {
msgBlock.classList.add("highlight-message");
}
// Стиль для донатов
if (element["type"] == "donate") {
msgBlock.style.backgroundColor = "#0000FF20";
}
// Создаем строку чата
const row = document.createElement("div");
row.className = "chatRow";
row.setAttribute("name", element["id"]);
row.appendChild(nameBlock);
row.appendChild(msgBlock);
// ВСЕГДА вставляем новое сообщение перед якорем (внизу)
chatwin.insertBefore(row, anchor);
// Прокручиваем сразу к новому сообщению
scrollToBottom();
});
// Ограничиваем количество сообщений (200)
removeOldMessages(200);
}
// Функция прокрутки в самый низ
function scrollToBottom() {
chatwin.scrollTop = chatwin.scrollHeight;
// Используем setTimeout чтобы прокрутка происходила после добавления DOM элемента
setTimeout(() => {
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
}, 10);
}
function removeOldMessages() {
const children = Array.from(chatwin.children);
while (children.length > 15) {
chatwin.removeChild(children[0]);
// Удаление старых сообщений
function removeOldMessages(maxMessages = 200) {
const messageRows = document.getElementsByClassName("chatRow");
const rowsToRemove = messageRows.length - maxMessages;
if (rowsToRemove > 0) {
for (let i = 0; i < rowsToRemove; i++) {
if (messageRows[0]) {
messageRows[0].remove();
}
}
}
}
function createChatLine() {
const nm = document.createElement("div");
nm.className = "nameline " + randomChat();
nm.textContent = randomNick();
const msg = document.createElement("div");
msg.className = "msgline";
msg.textContent = randomMessage();
const rw = document.createElement("div");
rw.className = "chatRow";
rw.appendChild(nm);
rw.appendChild(msg);
chatwin.appendChild(rw);
scrollToBottom();
removeOldMessages();
}
function createNewLine(json) {
json.forEach(element => {
const existing = document.getElementById(element.id);
if (existing) {
existing.querySelector('.msgline').textContent = element.msg;
return;
}
const nm = document.createElement("div");
nm.className = "nameline " + element.type;
nm.textContent = element.sendr;
if (element.type === "donate") {
nm.innerHTML += `<br><p style="color: red">${element.amount}</p>`;
}
const msg = document.createElement("div");
msg.className = "msgline";
msg.textContent = element.msg;
msg.id = element.id;
if (element.type === "donate") {
msg.style.backgroundColor = "#0000FF20";
}
const rw = document.createElement("div");
rw.className = "chatRow";
rw.appendChild(nm);
rw.appendChild(msg);
chatwin.appendChild(rw);
scrollToBottom();
removeOldMessages();
});
}
// Запрос новых сообщений с сервера
function requestNewLines() {
fetch("http://localhost:8008/")
.then(response => response.json())
.then(data => createNewLine(data))
.catch(error => console.error('Ошибка:', error));
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
createNewLine(data);
})
.catch(error => {
console.error('Error fetching chat messages:', error);
// Показываем сообщение об ошибке только если его нет
const errorRow = document.getElementById("error-message");
if (!errorRow) {
const errorDiv = document.createElement("div");
errorDiv.id = "error-message";
errorDiv.className = "chatRow error";
errorDiv.innerHTML = '<div class="nameline hello">Ошибка</div><div class="msgline">Не удалось подключиться к серверу чата</div>';
chatwin.insertBefore(errorDiv, anchor);
scrollToBottom();
}
});
}
setInterval(requestNewLines, 1000);
// setInterval(createChatLine, 3000);
// Инициализация чата
function initChat() {
// Прокручиваем сразу вниз при загрузке
scrollToBottom();
// Запрашиваем сообщения сразу при загрузке
requestNewLines();
// Запускаем периодический опрос
setInterval(requestNewLines, 1000);
}
// Запускаем чат когда DOM загружен
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initChat);
} else {
initChat();
}