Download utils.py from testbota/der: direct link, hf CLI and curl.
- Browser
- Download file 5.67 kB
-
https://huggingface.co/spaces/testbota/der/resolve/main/utils.py
- Command line
-
hf download hf://spaces/testbota/der/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/testbota/der/resolve/main/utils.py
5.67 kB
| import re | |
| import asyncio | |
| from datetime import datetime, timedelta | |
| from config import DANGEROUS_PATTERNS, SUSPICIOUS_KEYWORDS, MESSAGE_LENGTH_LIMIT | |
| from telegram import ChatMember | |
| # Прогресс-бар с эмодзи | |
| async def create_progress_bar(current, total, message=None, context=None): | |
| """ | |
| Создаёт и обновляет прогресс-бар в сообщении | |
| """ | |
| filled = min(int(5 * current / total), 5) if total > 0 else 0 | |
| empty = 5 - filled | |
| progress_emoji = '🟩' * filled + '⬜' * empty | |
| percentage = int(100 * current / total) if total > 0 else 0 | |
| text = f"{progress_emoji} {percentage}% | {current}/{total}" | |
| if message and context: | |
| try: | |
| await message.edit_text(text) | |
| except: | |
| pass | |
| return text | |
| # Проверка на спам | |
| async def check_spam(user_id, user_messages, last_messages): | |
| """ | |
| Проверяет, спамит ли пользователь | |
| """ | |
| if len(last_messages) < 3: | |
| return False | |
| # Проверка на одинаковые сообщения | |
| text_count = {} | |
| for msg in last_messages[-5:]: | |
| text = msg.lower() | |
| text_count[text] = text_count.get(text, 0) + 1 | |
| if max(text_count.values(), default=0) >= 3: | |
| return True | |
| # Проверка на нечитаемый текст | |
| if any(last_messages): | |
| avg_length = sum(len(msg) for msg in last_messages) / len(last_messages) | |
| if avg_length > MESSAGE_LENGTH_LIMIT: | |
| return True | |
| return False | |
| # Проверка на вирусные ссылки | |
| def check_dangerous_links(text): | |
| """ | |
| Проверяет наличие опасных ссылок и паттернов | |
| """ | |
| text_lower = text.lower() | |
| for pattern in DANGEROUS_PATTERNS: | |
| if pattern in text_lower: | |
| return True | |
| for keyword in SUSPICIOUS_KEYWORDS: | |
| if keyword in text_lower: | |
| return True | |
| return False | |
| # Проверка на то, является ли пользователь ботом | |
| async def is_bot_account(user): | |
| """ | |
| Проверяет, является ли аккаунт ботом | |
| """ | |
| if user.is_bot: | |
| return True | |
| # Проверка на типичные названия ботов | |
| bot_keywords = ['bot', 'бот', 'автомат', 'system'] | |
| username = (user.username or '').lower() | |
| first_name = (user.first_name or '').lower() | |
| return any(keyword in username or keyword in first_name for keyword in bot_keywords) | |
| # Проверка активности пользователя | |
| async def check_user_activity(user, chat_member): | |
| """ | |
| Проверяет активность пользователя | |
| """ | |
| try: | |
| # Если пользователь - администратор или создатель, не удаляем | |
| if isinstance(chat_member, ChatMember): | |
| if chat_member.status in ['administrator', 'creator']: | |
| return True | |
| return False | |
| except: | |
| return True | |
| # Форматирование информации о пользователе | |
| def format_user_info(user, reason="Unknown"): | |
| """ | |
| Форматирует информацию о пользователе | |
| """ | |
| username = f"@{user.username}" if user.username else "No username" | |
| name = f"{user.first_name} {user.last_name or ''}".strip() | |
| info = f""" | |
| 👤 Пользователь: {name} | |
| 🆔 ID: {user.id} | |
| 📛 Username: {username} | |
| 🔴 Причина: {reason} | |
| ⏰ Время: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | |
| """ | |
| return info | |
| # Проверка прав бота | |
| async def check_bot_permissions(chat, bot_member): | |
| """ | |
| Проверяет права администратора бота | |
| """ | |
| if not bot_member or not isinstance(bot_member, ChatMember): | |
| return {} | |
| perms = { | |
| 'can_delete_messages': bot_member.can_delete_messages, | |
| 'can_restrict_members': bot_member.can_restrict_members, | |
| 'can_promote_members': bot_member.can_promote_members, | |
| 'can_manage_chat': bot_member.can_manage_chat, | |
| 'can_manage_video_chats': bot_member.can_manage_video_chats, | |
| } | |
| return perms | |
| # Форматирование сообщения о правах | |
| def format_permissions(perms): | |
| """ | |
| Форматирует информацию о правах | |
| """ | |
| status_emoji = {True: '✅', False: '❌'} | |
| message = "ПРАВА АДМИНИСТРАТОРА БОТА:\n\n" | |
| message += f"{status_emoji.get(perms.get('can_delete_messages'), '❓')} Удаление сообщений\n" | |
| message += f"{status_emoji.get(perms.get('can_restrict_members'), '❓')} Ограничение пользователей\n" | |
| message += f"{status_emoji.get(perms.get('can_promote_members'), '❓')} Повышение администраторов\n" | |
| message += f"{status_emoji.get(perms.get('can_manage_chat'), '❓')} Управление чатом\n" | |
| message += f"{status_emoji.get(perms.get('can_manage_video_chats'), '❓')} Управление видеочатами\n" | |
| all_granted = all(perms.values()) | |
| if all_granted: | |
| message += "\n🟩 Все права получены!" | |
| else: | |
| message += "\n🟥 Некоторые права отсутствуют!" | |
| return message | |