G

Untitled

public
Guest Mar 08, 2025 Never 40
Clone
Plaintext paste1.txt 214 lines (186 loc) | 9.52 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
if message.forward_origin:
105
text = message.text or message.caption or "Пересланное сообщение"
106
await send_content(context.bot.send_message, text=f"{emoji} {text}")
107
if message.photo:
108
await send_content(context.bot.send_photo, photo=message.photo[-1].file_id, caption=f"{emoji}")
109
elif message.video:
110
await send_content(context.bot.send_video, video=message.video.file_id, caption=f"{emoji}")
111
elif message.document:
112
await send_content(context.bot.send_document, document=message.document.file_id, caption=f"{emoji}")
113
return
114
115
content_handlers = [
116
('text', context.bot.send_message, {'text': f"{emoji} {message.text}"}),
117
('photo', context.bot.send_photo, {'photo': message.photo[-1].file_id if message.photo else None, 'caption': f"{emoji}"}),
118
('video', context.bot.send_video, {'video': message.video.file_id if message.video else None, 'caption': f"{emoji}"}),
119
('video_note', context.bot.send_video_note, {'video_note': message.video_note.file_id if message.video_note else None}),
120
('animation', context.bot.send_animation, {'animation': message.animation.file_id if message.animation else None, 'caption': f"{emoji}"}),
121
('sticker', context.bot.send_sticker, {'sticker': message.sticker.file_id if message.sticker else None}),
122
('voice', context.bot.send_voice, {'voice': message.voice.file_id if message.voice else None, 'caption': f"{emoji}"}),
123
('audio', context.bot.send_audio, {'audio': message.audio.file_id if message.audio else None, 'caption': f"{emoji}"}),
124
('document', context.bot.send_document, {'document': message.document.file_id if message.document else None, 'caption': f"{emoji}"}),
125
]
126
127
for content_type, send_func, kwargs in content_handlers:
128
if getattr(message, content_type, None):
129
if 'photo' in content_type and message.photo:
130
kwargs['photo'] = message.photo[-1].file_id
131
await send_content(send_func, **kwargs)
132
return
133
134
await send_content(context.bot.send_message, text=f"{emoji} Сообщение обработано в чате {chat_id}")
135
136
except TelegramError as e:
137
logger.warning(f"Ошибка в handle_message: {e}")
138
139
# Функция имитации тайпинга
140
async def fake_typing(app):
141
while running:
142
try:
143
if not active_chats:
144
logger.info("Нет активных чатов для тайпинга")
145
await asyncio.sleep(1)
146
continue
147
chat_id = random.choice(list(active_chats))
148
action = random.choice(ACTION_LIST)
149
logger.info(f"Отправка действия {action} в чат {chat_id}")
150
await app.bot.send_chat_action(chat_id, action)
151
await asyncio.sleep(random.uniform(0.5, 2))
152
except TelegramError as e:
153
logger.warning(f"Ошибка в fake_typing: {e}")
154
await asyncio.sleep(1)
155
156
# Функция смены имени бота
157
async def change_bot_name(app):
158
while running:
159
try:
160
new_name = generate_bot_name()
161
await app.bot.set_my_name(new_name)
162
logger.info(f"Имя бота изменено на {new_name}")
163
await asyncio.sleep(random.uniform(900, 1200)) # 15–20 минут
164
except TelegramError as e:
165
logger.warning(f"Ошибка смены имени: {e}")
166
await asyncio.sleep(60)
167
168
# Запуск бота
169
async def run_bot_async():
170
token = os.getenv('BOT_TOKEN', '8064940173:AAGPuAPKMwkPbEKE7B7SSr6XlgLhWGYYQHU')
171
app = Application.builder().token(token).build()
172
app.add_handlers([
173
CommandHandler("toggle", toggle),
174
MessageHandler(filters.ALL & ~filters.COMMAND, handle_message),
175
])
176
177
# Проверяем, что job_queue доступен
178
if app.job_queue is None:
179
logger.error("JobQueue не инициализирован. Установите 'python-telegram-bot[job-queue]'")
180
sys.exit(1)
181
182
# Запускаем задачи через job_queue
183
app.job_queue.run_repeating(lambda context: asyncio.create_task(fake_typing(app)), interval=1)
184
app.job_queue.run_repeating(lambda context: asyncio.create_task(change_bot_name(app)), interval=900)
185
logger.info("Бот запущен")
186
187
# Запускаем polling
188
await app.run_polling(allowed_updates=["message"], drop_pending_updates=True, timeout=20)
189
190
def run_bot():
191
loop = asyncio.get_event_loop()
192
try:
193
loop.run_until_complete(run_bot_async())
194
except KeyboardInterrupt:
195
global running
196
running = False
197
logger.info("Остановка бота...")
198
finally:
199
loop.run_until_complete(loop.shutdown_asyncgens())
200
loop.close()
201
202
# Обработка сигналов
203
def signal_handler(signum, frame):
204
global running
205
logger.info("Получен сигнал остановки...")
206
running = False
207
208
def main():
209
signal.signal(signal.SIGINT, signal_handler)
210
signal.signal(signal.SIGTERM, signal_handler)
211
run_bot()
212
213
if __name__ == "__main__":
214
main()