G

Untitled

public
Guest Mar 08, 2025 Never 35
Clone
Plaintext paste1.txt 198 lines (172 loc) | 9.01 KB
1
#!/usr/bin/env python3
2
import asyncio
3
import logging
4
import hashlib
5
import random
6
import time
7
from telegram import Update
8
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
9
from telegram.constants import ChatAction
10
from telegram.error import TelegramError
11
import signal
12
import sys
13
import os
14
15
# Настройка логирования
16
logging.basicConfig(
17
format='%(asctime)s - %(levelname)s - %(message)s',
18
level=logging.INFO,
19
handlers=[logging.StreamHandler()]
20
)
21
logger = logging.getLogger(__name__)
22
23
# Данные в памяти
24
invisible_users = set()
25
active_chats = set()
26
running = True
27
28
# Список индикаторов активности
29
ACTION_LIST = [
30
ChatAction.TYPING,
31
ChatAction.UPLOAD_PHOTO,
32
ChatAction.UPLOAD_VIDEO,
33
ChatAction.UPLOAD_DOCUMENT,
34
]
35
36
# Расширенный список эмодзи
37
EMOJI_LIST = [
38
"🐱", "🐶", "🐻", "🦁", "🐰", "🦊", "🐼", "🐸", "🐙", "🦄", "🐦", "🦋", "🐞", "🐢", "🦀",
39
"🐳", "🐬", "🐠", "🦎", "🦍", "🐘", "🦒", "🐫", "🦓", "🐷", "🐮", "🐴", "🐑", "🐐", "🦌",
40
"🐭", "🐹", "🐰", "🦇", "🐺", "🦉", "🦅", "🦜", "🦚", "🦩", "🐍", "🦂", "🕷️", "🦗", "🐜",
41
"🐝", "🦋", "🌸", "🌹", "🌻", "🌼", "🍀", "🍁", "🍂", "🍃", "🌴", "🌵", "⭐", "🌟", "✨",
42
"⚡", "☄️", "🌙", "☀️", "⛄", "☁️", "🌧️", "⛈️", "🌈", "🍎", "🍊", "🍋", "🍉", "🍇",
43
"🍓", "🍒", "🍍", "🥝", "🥑", "🍔", "🍕", "🍟", "🍦", "🍭", "🍫", "☕", "🍵", "🍺",
44
"🎮", "🎸", "🎹", "🎤", "🎧", "🎥", "📷", "📱", "💻", "⌚", "💡", "🔧", "🔨", "⚙️", "🛠️"
45
]
46
47
# Вариации символов в стиле cmd
48
CMD_STYLES = ["_", ">", "-", ">>", "_", ">"]
49
50
# Хэширование user_id
51
def hash_user_id(user_id: int) -> str:
52
return hashlib.sha256(str(user_id).encode()).hexdigest()
53
54
# Получение случайного эмодзи
55
def get_random_emoji() -> str:
56
return random.choice(EMOJI_LIST)
57
58
# Генерация имени бота с эмодзи
59
def generate_bot_name():
60
base = "FREENAPASS420"
61
style = random.choice(CMD_STYLES)
62
emoji = get_random_emoji() # Добавляем случайный эмодзи
63
return f"{base}{style}{emoji}"
64
65
# Команда /toggle
66
async def toggle(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
67
if not update.message or update.message.chat.type not in ('group', 'supergroup'):
68
return
69
user_id, chat_id = update.message.from_user.id, update.message.chat_id
70
hashed_id = hash_user_id(user_id)
71
emoji = get_random_emoji()
72
try:
73
await context.bot.delete_message(chat_id, update.message.message_id)
74
await asyncio.sleep(random.uniform(0.3, 1.5))
75
if hashed_id in invisible_users:
76
invisible_users.remove(hashed_id)
77
await context.bot.send_message(chat_id, f"{emoji} Режим анонимности выключен")
78
else:
79
invisible_users.add(hashed_id)
80
await context.bot.send_message(chat_id, f"{emoji} Режим анонимности включен")
81
active_chats.add(chat_id)
82
logger.info(f"Текущие активные чаты: {active_chats}")
83
except TelegramError as e:
84
logger.warning(f"Ошибка в toggle: {e}")
85
86
# Обработка сообщений
87
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
88
message = update.message
89
if not message or message.chat.type not in ('group', 'supergroup') or hash_user_id(message.from_user.id) not in invisible_users:
90
return
91
92
chat_id = message.chat_id
93
active_chats.add(chat_id)
94
emoji = get_random_emoji()
95
reply_to_message_id = message.reply_to_message.message_id if message.reply_to_message else None
96
97
try:
98
await context.bot.delete_message(chat_id, message.message_id)
99
100
async def send_content(send_func, **kwargs):
101
await asyncio.sleep(random.uniform(0.3, 1.5))
102
await send_func(chat_id, **kwargs, reply_to_message_id=reply_to_message_id)
103
104
# Пересылка сообщений
105
if message.forward_origin:
106
text = message.text or message.caption or "Пересланное сообщение"
107
await send_content(context.bot.send_message, text=f"{emoji} {text}")
108
if message.photo:
109
await send_content(context.bot.send_photo, photo=message.photo[-1].file_id, caption=f"{emoji}")
110
elif message.video:
111
await send_content(context.bot.send_video, video=message.video.file_id, caption=f"{emoji}")
112
elif message.document:
113
await send_content(context.bot.send_document, document=message.document.file_id, caption=f"{emoji}")
114
return
115
116
# Обработка разных типов контента
117
content_handlers = [
118
('text', context.bot.send_message, {'text': f"{emoji} {message.text}"}),
119
('photo', context.bot.send_photo, {'photo': message.photo[-1].file_id if message.photo else None, 'caption': f"{emoji}"}),
120
('video', context.bot.send_video, {'video': message.video.file_id if message.video else None, 'caption': f"{emoji}"}),
121
('video_note', context.bot.send_video_note, {'video_note': message.video_note.file_id if message.video_note else None}),
122
('animation', context.bot.send_animation, {'animation': message.animation.file_id if message.animation else None, 'caption': f"{emoji}"}),
123
('sticker', context.bot.send_sticker, {'sticker': message.sticker.file_id if message.sticker else None}),
124
('voice', context.bot.send_voice, {'voice': message.voice.file_id if message.voice else None, 'caption': f"{emoji}"}),
125
('audio', context.bot.send_audio, {'audio': message.audio.file_id if message.audio else None, 'caption': f"{emoji}"}),
126
('document', context.bot.send_document, {'document': message.document.file_id if message.document else None, 'caption': f"{emoji}"}),
127
]
128
129
for content_type, send_func, kwargs in content_handlers:
130
if getattr(message, content_type, None):
131
if 'photo' in content_type and message.photo:
132
kwargs['photo'] = message.photo[-1].file_id
133
await send_content(send_func, **kwargs)
134
return
135
136
await send_content(context.bot.send_message, text=f"{emoji} Сообщение обработано в чате {chat_id}")
137
138
except TelegramError as e:
139
logger.warning(f"Ошибка в handle_message: {e}")
140
141
# Функция имитации тайпинга
142
async def fake_typing(app):
143
while running:
144
try:
145
if not active_chats:
146
logger.info("Нет активных чатов для тайпинга")
147
await asyncio.sleep(1)
148
continue
149
150
chat_id = random.choice(list(active_chats))
151
action = random.choice(ACTION_LIST)
152
logger.info(f"Отправка действия {action} в чат {chat_id}")
153
await app.bot.send_chat_action(chat_id, action)
154
await asyncio.sleep(random.uniform(0.5, 2))
155
except TelegramError as e:
156
logger.warning(f"Ошибка в fake_typing: {e}")
157
await asyncio.sleep(1)
158
159
# Функция смены имени бота
160
async def change_bot_name(app):
161
while running:
162
try:
163
new_name = generate_bot_name()
164
await app.bot.set_my_name(new_name)
165
logger.info(f"Имя бота изменено на {new_name}")
166
await asyncio.sleep(random.uniform(900, 1200)) # 15–20 минут
167
except TelegramError as e:
168
logger.warning(f"Ошибка смены имени: {e}")
169
await asyncio.sleep(60)
170
171
# Запуск бота
172
def run_bot():
173
token = os.getenv('BOT_TOKEN', '8064940173:AAGPuAPKMwkPbEKE7B7SSr6XlgLhWGYYQHU')
174
app = Application.builder().token(token).build()
175
app.add_handlers([
176
CommandHandler("toggle", toggle),
177
MessageHandler(filters.ALL & ~filters.COMMAND, handle_message),
178
])
179
180
app.job_queue.run_repeating(lambda context: asyncio.create_task(fake_typing(app)), interval=1)
181
app.job_queue.run_repeating(lambda context: asyncio.create_task(change_bot_name(app)), interval=900)
182
logger.info("Бот запущен")
183
app.run_polling(allowed_updates=["message"], drop_pending_updates=True, timeout=20)
184
185
# Обработка сигналов
186
def signal_handler(signum, frame):
187
global running
188
logger.info("Останавливаем бота...")
189
running = False
190
sys.exit(0)
191
192
def main():
193
signal.signal(signal.SIGINT, signal_handler)
194
signal.signal(signal.SIGTERM, signal_handler)
195
run_bot()
196
197
if __name__ == "__main__":
198
main()