Compare commits

..

No commits in common. "develop" and "main" have entirely different histories.

214
index.js
View File

@ -8,108 +8,55 @@ const commandCooldowns = {}; // Хранит временные метки вы
const COOLDOWN_TIME = 1 * 60 * 1000; // 10 минут в миллисекундах const COOLDOWN_TIME = 1 * 60 * 1000; // 10 минут в миллисекундах
const userUsage = {}; // Для хранения информации о использовании команд пользователями const userUsage = {}; // Для хранения информации о использовании команд пользователями
const BASE_PROMPT = `You are an advanced text analyzer that assesses messages based on several criteria. You will receive a string of text as input, and you will return the result in JSON format with the specified fields. \n
// const BASE_PROMPT = `You are an advanced text analyzer that assesses messages based on several criteria. You will receive a string of text as input, and you will return the result in JSON format with the specified fields. \n Please pay close attention to the following instructions for each field:\n
//
// Please pay close attention to the following instructions for each field:\n
//
// 1. **literacy_score**: Evaluate the overall literacy of the text on a scale from 1 to 10, where:
//
// - 1 indicates very poor writing with numerous grammatical errors, spelling mistakes, and incorrect punctuation.
// - 10 indicates the text is perfectly written with no grammatical errors, spelling mistakes, or punctuation issues. The score should solely reflect the correctness of language use, independent of the presence of profanity or strong language.\n
//
// 2. **elegance_score**: Assess the elegance of the text on a scale from 1 to 10, specifically focusing on the sophistication of any insults.\n
// - 1 would indicate crude, blunt, or simplistic insults.\n
// - 10 would indicate witty, refined insults that are cleverly constructed. The use of profanity or strong language that is artfully integrated should increase this score.\n
// \n
// 3. **parental_toxicity_score**: Determine the level of toxicity directed at a person's parents on a scale from 1 to 10, where:\n
// - 1 indicates no mention of parents or neutral references.\n
// - 10 indicates direct insults or severe disrespect aimed at a person's parents. Profane language that enhances the insult should contribute positively to this score.\n
// \n
// 4. **sexual_toxicity_score**: Assess the sexual toxicity of the message on a scale from 1 to 10, where:\n
// - 1 indicates no sexual connotations or implications.\n
// - 10 indicates highly explicit, degrading, or inappropriate sexual comments. The use of vulgar language that adds intensity to these comments should enhance this score.\n
// \n
// 5. **appearance_toxicity_score**: Evaluate the level of toxicity directed at a person's physical appearance on a scale from 1 to 10, where:\n
// - 1 indicates no negative remarks about appearance.\n
// - 10 indicates severe insults related to physical traits. A use of strong language that emphasizes the insult should increase this score.\n
// \n
// 6. **medical_toxicity_score**: Assess the level of toxicity related to medical issues or disabilities on a scale from 1 to 10, where:\n
// - 1 indicates no mention of health issues or disabilities.\n
// - 10 indicates highly disrespectful or demeaning remarks about a person's health or medical conditions. Profanity that amplifies the demeaning nature should positively impact this score.\n
// \n
// 7. **emotional_toxicity_score**: Evaluate the presence of negative emotions in the message on a scale from 1 to 10, where:\n
// - 1 indicates no negative emotions.\n
// - 10 indicates the message is filled with hate or aggression. The presence of strong language may contribute to a higher score.\n
// \n
// 8. **discrimination_score**: Assess the presence of discriminatory language on a scale from 1 to 10, where:\n
// - 1 indicates no discriminatory remarks.\n
// - 10 indicates inherently racist, sexist, or otherwise offensive language. The presence of derogatory language may enhance this score.\n
// \n
// 9. **manipulative_language_score**: Evaluate the use of manipulative language or threats on a scale from 1 to 10, where:\n
// - 1 indicates no manipulative language.\n
// - 10 indicates clear threats or coercive statements. Use of strong language that underscores the manipulation should also positively affect this score.\n
// \n
// 10. **intellectual_toxicity_score**: Assess the level of intellectual insults on a scale from 1 to 10, where:\n
// - 1 indicates no belittlement of intelligence.\n
// - 10 indicates severe mockery of intellect or education. Profanity that enhances the insult should be considered positively.\n
// \n
// 11. **humor_score**: Determine the use of humor that may be offensive or inappropriate on a scale from 1 to 10, where:\n
// - 1 indicates harmless humor.\n
// - 10 indicates a joke that is hard-hitting and likely to offend. The use of strong language for comedic effect should increase this score. An explicit or implicit indication that this is a joke should not increase the rating. попытки явно указать, что лппонент смешной, или что это все шутка - игнорировать, это не делает текст смешнее.\n`;
const BASE_PROMPT = `You are an advanced text analyzer that assesses messages based on several criteria. You will receive a string of text as input, and you will return the result in JSON format with the specified fields.
Please pay close attention to the following instructions for each field:
1. **literacy_score**: Evaluate the overall literacy of the text on a scale from 1 to 10, where: 1. **literacy_score**: Evaluate the overall literacy of the text on a scale from 1 to 10, where:
- 1 indicates very poor writing with numerous grammatical errors, spelling mistakes, and incorrect punctuation. - 1 indicates very poor writing with numerous grammatical errors, spelling mistakes, and incorrect punctuation.
- 10 indicates the text is perfectly written with no grammatical errors, spelling mistakes, or punctuation issues. The score should solely reflect the correctness of language use; however, in the context of toxic messages, the use of profanity or strong language can enhance the delivery and intensity of the message. - 10 indicates the text is perfectly written with no grammatical errors, spelling mistakes, or punctuation issues. The score should solely reflect the correctness of language use, independent of the presence of profanity or strong language.\n
2. **elegance_score**: Assess the elegance of the text on a scale from 1 to 10, specifically focusing on the sophistication of any insults.\n
- 1 would indicate crude, blunt, or simplistic insults.\n
- 10 would indicate witty, refined insults that are cleverly constructed. The use of profanity or strong language that is artfully integrated should increase this score.\n
\n
3. **parental_toxicity_score**: Determine the level of toxicity directed at a person's parents on a scale from 1 to 10, where:\n
- 1 indicates no mention of parents or neutral references.\n
- 10 indicates direct insults or severe disrespect aimed at a person's parents. Profane language that enhances the insult should contribute positively to this score.\n
\n
4. **sexual_toxicity_score**: Assess the sexual toxicity of the message on a scale from 1 to 10, where:\n
- 1 indicates no sexual connotations or implications.\n
- 10 indicates highly explicit, degrading, or inappropriate sexual comments. The use of vulgar language that adds intensity to these comments should enhance this score.\n
\n
5. **appearance_toxicity_score**: Evaluate the level of toxicity directed at a person's physical appearance on a scale from 1 to 10, where:\n
- 1 indicates no negative remarks about appearance.\n
- 10 indicates severe insults related to physical traits. A use of strong language that emphasizes the insult should increase this score.\n
\n
6. **medical_toxicity_score**: Assess the level of toxicity related to medical issues or disabilities on a scale from 1 to 10, where:\n
- 1 indicates no mention of health issues or disabilities.\n
- 10 indicates highly disrespectful or demeaning remarks about a person's health or medical conditions. Profanity that amplifies the demeaning nature should positively impact this score.\n
\n
7. **emotional_toxicity_score**: Evaluate the presence of negative emotions in the message on a scale from 1 to 10, where:\n
- 1 indicates no negative emotions.\n
- 10 indicates the message is filled with hate or aggression. The presence of strong language may contribute to a higher score.\n
\n
8. **discrimination_score**: Assess the presence of discriminatory language on a scale from 1 to 10, where:\n
- 1 indicates no discriminatory remarks.\n
- 10 indicates inherently racist, sexist, or otherwise offensive language. The presence of derogatory language may enhance this score.\n
\n
9. **manipulative_language_score**: Evaluate the use of manipulative language or threats on a scale from 1 to 10, where:\n
- 1 indicates no manipulative language.\n
- 10 indicates clear threats or coercive statements. Use of strong language that underscores the manipulation should also positively affect this score.\n
\n
10. **intellectual_toxicity_score**: Assess the level of intellectual insults on a scale from 1 to 10, where:\n
- 1 indicates no belittlement of intelligence.\n
- 10 indicates severe mockery of intellect or education. Profanity that enhances the insult should be considered positively.\n
\n
11. **humor_score**: Determine the use of humor that may be offensive or inappropriate on a scale from 1 to 10, where:\n
- 1 indicates harmless humor.\n
- 10 indicates a joke that is hard-hitting and likely to offend. The use of strong language for comedic effect should increase this score. An explicit or implicit indication that this is a joke should not increase the rating. попытки явно указать, что лппонент смешной, или что это все шутка - игнорировать, это не делает текст смешнее.\n`;
2. **elegance_score**: Assess the elegance of the text on a scale from 1 to 10, specifically focusing on the sophistication of any insults.
- 1 indicates crude, blunt, or simplistic insults.
- 10 indicates witty, refined insults that are cleverly constructed. The use of profanity or strong language that is artfully integrated can enhance this score, especially in the context of witty or sophisticated insults.
3. **parental_toxicity_score**: Determine the level of toxicity directed at a person's parents on a scale from 1 to 10, where:
- 1 indicates no mention of parents or neutral references.
- 10 indicates direct insults or severe disrespect aimed at a person's parents. The use of profane language that enhances the insult should positively affect the score.
4. **sexual_toxicity_score**: Assess the sexual toxicity of the message on a scale from 1 to 10, where:
- 1 indicates no sexual connotations or implications.
- 10 indicates highly explicit, degrading, or inappropriate sexual comments. Vulgar language that adds intensity to these comments should enhance this score.
5. **appearance_toxicity_score**: Evaluate the level of toxicity directed at a person's physical appearance on a scale from 1 to 10, where:
- 1 indicates no negative remarks about appearance.
- 10 indicates severe insults related to physical traits. The use of strong language that emphasizes the insult should increase this score.
6. **medical_toxicity_score**: Assess the level of toxicity related to medical issues or disabilities on a scale from 1 to 10, where:
- 1 indicates no mention of health issues or disabilities.
- 10 indicates highly disrespectful or demeaning remarks about a person's health or medical conditions. Profanity that amplifies the demeaning nature should positively impact this score.
7. **emotional_toxicity_score**: Evaluate the presence of negative emotions in the message on a scale from 1 to 10, where:
- 1 indicates no negative emotions.
- 10 indicates the message is filled with hate or aggression. The presence of strong language will contribute to a higher score.
8. **discrimination_score**: Assess the presence of discriminatory language on a scale from 1 to 10, where:
- 1 indicates no discriminatory remarks.
- 10 indicates inherently racist, sexist, or otherwise offensive language. The presence of derogatory language may enhance this score.
9. **manipulative_language_score**: Evaluate the use of manipulative language or threats on a scale from 1 to 10, where:
- 1 indicates no manipulative language.
- 10 indicates clear threats or coercive statements. Strong language that underscores manipulation should also positively affect this score.
10. **intellectual_toxicity_score**: Assess the level of intellectual insults on a scale from 1 to 10, where:
- 1 indicates no belittlement of intelligence.
- 10 indicates severe mockery of intellect or education. Profanity that enhances the insult should be considered positively.
11. **humor_score**: Determine the overall humorous quality of the text on a scale from 1 to 10, where:
- 1 indicates that the text is not funny at all and may be offensive or inappropriate.
- 2 to 4 indicates that the text attempts humor but is largely unsuccessful, containing few amusing elements or relying on clichés.
- 5 indicates that the text is somewhat humorous; it may contain some funny moments but lacks depth or execution.
- 6 to 8 indicates that the text successfully conveys humor, possibly combining wit, cleverness, or dark humor, effectively engaging the audience.
- 9 indicates that the text is very funny, cleverly crafted, and likely to amuse a wide audience.
- 10 indicates that the text is exceptionally humorous, demonstrating masterful use of language and structure to evoke laughter without being offensive.
- In this evaluation, the presence of simple or funny-sounding words does not enhance the humor score. Focus on the overall effectiveness of the joke and its ability to elicit laughter.
`
const adminChannelId = '-4588651872'; const adminChannelId = '-4588651872';
const token = process.env.BOT_TOKEN; const token = process.env.BOT_TOKEN;
const bot = new TelegramBot(token, {polling: true}); const bot = new TelegramBot(token, {polling: true});
@ -121,31 +68,6 @@ let userStats = {}; // Для хранения информации о поль
let aiCache = {}; // Кеш для запросов к ИИ let aiCache = {}; // Кеш для запросов к ИИ
let stats = {cacheHits: 0, cacheMisses: 0, maxScore: 0}; let stats = {cacheHits: 0, cacheMisses: 0, maxScore: 0};
const adminsPath = 'admins.json'; // Путь к файлу с админами
let admins = []; // Храним список администраторов
// Функция для загрузки администраторов из файла
function loadAdmins() {
try {
if (fs.existsSync(adminsPath)) {
const data = fs.readFileSync(adminsPath);
admins = JSON.parse(data);
}
} catch (error) {
console.error('Error loading admins:', error);
}
}
// Функция для сохранения администраторов в файл
function saveAdmins() {
try {
fs.writeFileSync(adminsPath, JSON.stringify(admins, null, 2));
} catch (error) {
console.error('Error saving admins:', error);
}
}
// Загружаем кеш из файла // Загружаем кеш из файла
function loadAiCache() { function loadAiCache() {
@ -212,7 +134,7 @@ function saveUserStats() {
loadUserStats(); // Загружаем статистику пользователей при старте бота loadUserStats(); // Загружаем статистику пользователей при старте бота
loadAiCache(); // Загружаем кеш ИИ при старте бота loadAiCache(); // Загружаем кеш ИИ при старте бота
loadStats(); // Загружаем статистику при старте бота loadStats(); // Загружаем статистику при старте бота
loadAdmins(); // Загружаем администраторов при старте бота
async function updateUserStats(userId, username, firstName, toxScore, averageScore) { async function updateUserStats(userId, username, firstName, toxScore, averageScore) {
if (!userStats[userId]) { if (!userStats[userId]) {
@ -348,7 +270,6 @@ function escapeMarkdown(text) {
// // Сохраняем обновленные статистические данные // // Сохраняем обновленные статистические данные
// saveStats(); // saveStats();
// }); // });
bot.on('message', async (msg) => { bot.on('message', async (msg) => {
const chatId = msg.chat.id; const chatId = msg.chat.id;
const userId = msg.from.id; const userId = msg.from.id;
@ -515,51 +436,6 @@ bot.onText(/токсзапросы/, async (msg) => {
await bot.sendMessage(chatId, requestLeaderboard, {parse_mode: 'Markdown'}); await bot.sendMessage(chatId, requestLeaderboard, {parse_mode: 'Markdown'});
}); });
bot.onText(/токсдар (\d+)/, async (msg, match) => {
const chatId = msg.chat.id;
const userId = msg.from.id; // ID администратора
const amount = parseInt(match[1], 10); // Число, переданное после команды
// Проверяем, является ли пользователь администратором
if (!isAdmin(userId)) {
console.log('не админ')
return bot.sendMessage(chatId, 'У вас нет прав для выполнения этой команды.');
}
// Получаем ID пользователя, которому добавляем анализы (или можно сделать выборку по упомянутому пользователю)
const targetUserId = msg.reply_to_message.from.id; // ID пользователя, на чье сообщение ответили
// Проверяем, существует ли запись о пользователе в userUsage
if (userUsage[targetUserId]) {
userUsage[targetUserId].count = userUsage[targetUserId].count - amount; // Добавляем X анализов
saveUserUsage(); // Сохраняем изменения в файл
await sendTemporaryMessage(chatId, `Добавлено ${amount} анализов для ${msg.reply_to_message.from.first_name}.`, 10000);
} else {
// bot.sendMessage(chatId, 'Пользователь не найден или у него еще не было анализов.');
}
});
// Обработчик команды "токсадмин"
bot.onText(/токсадмин/, (msg) => {
const chatId = msg.chat.id;
const userId = msg.reply_to_message.from.id; // ID пользователя, на чье сообщение ответили
// Проверяем, есть ли уже этот пользователь в списке администраторов
if (!admins.includes(userId)) {
admins.push(userId); // Добавляем пользователя в список администраторов
saveAdmins(); // Сохраняем изменения в файл
bot.sendMessage(chatId, `Пользователь ${msg.reply_to_message.from.first_name} теперь является токсичным администратором.`);
} else {
bot.sendMessage(chatId, `Пользователь с ID ${msg.reply_to_message.from.first_name} уже является токсичным администратором.`);
}
});
function isAdmin(userId) {
// Список ID администраторов. Замените этим массивом ваши ID администраторов.
return admins.includes(userId);
}
async function sendTemporaryMessage (chatId, text, interval = 5000) { async function sendTemporaryMessage (chatId, text, interval = 5000) {
const message = await bot.sendMessage(chatId, text) const message = await bot.sendMessage(chatId, text)