проект
This commit is contained in:
commit
ad9493323d
3 files changed
+296
No files matched your search
@@ -0,0 +1,289 @@
|
||||
import os
|
||||
import sys
|
||||
import asyncio
|
||||
import configparser
|
||||
import subprocess
|
||||
from telethon import TelegramClient, events, errors
|
||||
from prompt_toolkit import PromptSession
|
||||
from prompt_toolkit.patch_stdout import patch_stdout
|
||||
from prompt_toolkit.key_binding import KeyBindings
|
||||
import qrcode
|
||||
|
||||
# ==================== СИСТЕМНЫЕ ФУНКЦИИ ====================
|
||||
def clear_screen():
|
||||
os.system('cls' if os.name == 'nt' else 'clear')
|
||||
|
||||
def open_file(path):
|
||||
"""Открывает файл стандартными средствами системы (Windows/Mac/Linux)"""
|
||||
try:
|
||||
if sys.platform == 'win32':
|
||||
os.startfile(path)
|
||||
elif sys.platform == 'darwin':
|
||||
subprocess.call(['open', path])
|
||||
else:
|
||||
subprocess.call(['xdg-open', path])
|
||||
except Exception as e:
|
||||
print(f"⚠️ Ошибка открытия файла: {e}")
|
||||
|
||||
# ==================== ИНИЦИАЛИЗАЦИЯ И КОНФИГ ====================
|
||||
config_file = 'config.ini'
|
||||
config = configparser.ConfigParser()
|
||||
|
||||
def create_blank_config():
|
||||
config['API'] = {
|
||||
'id': '',
|
||||
'hash': ''
|
||||
}
|
||||
with open(config_file, 'w') as f:
|
||||
config.write(f)
|
||||
|
||||
if not os.path.exists(config_file):
|
||||
create_blank_config()
|
||||
clear_screen()
|
||||
print(f"⚠️ Файл '{config_file}' был создан в папке со скриптом.")
|
||||
print("Открой его любым текстовым редактором, впиши свои 'id' и 'hash', сохрани и запусти скрипт заново!")
|
||||
sys.exit()
|
||||
|
||||
config.read(config_file)
|
||||
|
||||
try:
|
||||
raw_id = config.get('API', 'id').strip()
|
||||
raw_hash = config.get('API', 'hash').strip()
|
||||
|
||||
if not raw_id or not raw_hash:
|
||||
clear_screen()
|
||||
print(f"❌ В файле '{config_file}' не указаны API ID или HASH!")
|
||||
print("Пожалуйста, заполни их и запусти скрипт заново.")
|
||||
sys.exit()
|
||||
|
||||
API_ID = int(raw_id)
|
||||
API_HASH = raw_hash
|
||||
except ValueError:
|
||||
clear_screen()
|
||||
print(f"❌ Ошибка в '{config_file}': API 'id' должен состоять только из цифр!")
|
||||
sys.exit()
|
||||
except (configparser.NoSectionError, configparser.NoOptionError):
|
||||
create_blank_config()
|
||||
clear_screen()
|
||||
print(f"❌ Файл '{config_file}' был поврежден и пересоздан заново. Пожалуйста, заполни его.")
|
||||
sys.exit()
|
||||
|
||||
client = TelegramClient("user_session", API_ID, API_HASH)
|
||||
os.makedirs("files", exist_ok=True)
|
||||
|
||||
# Глобальные переменные
|
||||
target_entity = None
|
||||
mute_enabled = False
|
||||
local_sent_ids = []
|
||||
last_media_path = None # Сохраняем путь к последнему полученному файлу
|
||||
|
||||
|
||||
# ==================== НАСТРОЙКА ИНТЕРФЕЙСА ====================
|
||||
bindings = KeyBindings()
|
||||
|
||||
@bindings.add('c-1')
|
||||
@bindings.add('c-t')
|
||||
def toggle_mute(event):
|
||||
global mute_enabled
|
||||
mute_enabled = not mute_enabled
|
||||
status = "ВКЛ🔴" if mute_enabled else "ВЫКЛ🟢"
|
||||
print(f"\n⚙️ Мут: {status}")
|
||||
|
||||
@bindings.add('c-o')
|
||||
@bindings.add('c-2')
|
||||
def open_last_media(event):
|
||||
"""Открываем последнее полученное медиа по нажатию Ctrl+O"""
|
||||
global last_media_path
|
||||
if last_media_path and os.path.exists(last_media_path):
|
||||
print(f"\n📂 Открываю: {last_media_path}")
|
||||
open_file(last_media_path)
|
||||
else:
|
||||
print("\n⚠️ Нет медиа для открытия!")
|
||||
|
||||
def bottom_toolbar():
|
||||
status = "ВКЛ🔴" if mute_enabled else "ВЫКЛ🟢"
|
||||
return f" [Ctrl+1] Мут: {status} | [Ctrl+O] Открыть медиа | [Ctrl+C] Выход "
|
||||
|
||||
|
||||
# ==================== ОБРАБОТЧИК СООБЩЕНИЙ ====================
|
||||
@client.on(events.NewMessage)
|
||||
async def message_handler(event):
|
||||
global target_entity, mute_enabled, last_media_path
|
||||
|
||||
if not target_entity or event.chat_id != target_entity.id:
|
||||
return
|
||||
|
||||
text = event.text or ""
|
||||
|
||||
# === ИСХОДЯЩИЕ (Твои сообщения) ===
|
||||
if event.out:
|
||||
if event.message.id in local_sent_ids:
|
||||
return
|
||||
|
||||
print(f"📱 [Я (с телефона)]: {text}")
|
||||
if event.media:
|
||||
print("📎 [Прикреплено медиа]")
|
||||
return
|
||||
|
||||
# === ВХОДЯЩИЕ (От таргета) ===
|
||||
if mute_enabled:
|
||||
try:
|
||||
await event.delete(revoke=True)
|
||||
print(f"🚫 [Удалено входящее от таргета]")
|
||||
except:
|
||||
pass
|
||||
return
|
||||
|
||||
# Если мут выключен — обрабатываем контент
|
||||
if event.media:
|
||||
# Скачиваем файл в фоне
|
||||
path = await event.download_media(file="files/")
|
||||
last_media_path = path # Запоминаем путь для кнопки открытия
|
||||
ext = path.lower().split('.')[-1] if '.' in path else ''
|
||||
|
||||
if ext in ['jpg', 'jpeg', 'png', 'mp4']:
|
||||
print(f"📩 [Таргет]: {text} 🖼 [Фото/Видео сохранено] ➔ Нажми Ctrl+O чтобы посмотреть")
|
||||
elif ext in ['ogg', 'mp3', 'wav', 'm4a']:
|
||||
print(f"📩 [Таргет]: {text} 🎤 [Голосовое сохранено] ➔ Нажми Ctrl+O чтобы послушать")
|
||||
else:
|
||||
print(f"📩 [Таргет]: {text} 📁 [Файл: {path}] ➔ Нажми Ctrl+O чтобы открыть")
|
||||
else:
|
||||
text = text or "[Пустое сообщение]"
|
||||
print(f"📩 [Таргет]: {text}")
|
||||
|
||||
|
||||
# ==================== ЦИКЛ ЧАТА ====================
|
||||
async def chat_loop():
|
||||
global last_media_path
|
||||
session = PromptSession(
|
||||
message="Вы ➔ ",
|
||||
key_bindings=bindings,
|
||||
bottom_toolbar=bottom_toolbar
|
||||
)
|
||||
|
||||
while True:
|
||||
with patch_stdout():
|
||||
try:
|
||||
text = await session.prompt_async()
|
||||
text = text.strip()
|
||||
|
||||
if text:
|
||||
# Команда ручного открытия (если горячие клавиши не нравятся)
|
||||
if text.lower() == "/open":
|
||||
if last_media_path and os.path.exists(last_media_path):
|
||||
print(f"📂 Открываю: {last_media_path}")
|
||||
open_file(last_media_path)
|
||||
else:
|
||||
print("⚠️ Нет медиа для открытия!")
|
||||
continue
|
||||
|
||||
# Отправка файла
|
||||
if text.startswith("/send "):
|
||||
filepath = text[6:].strip().strip('"').strip("'")
|
||||
|
||||
if os.path.exists(filepath):
|
||||
print("⏳ Отправка файла...")
|
||||
msg = await client.send_file(target_entity, filepath)
|
||||
local_sent_ids.append(msg.id)
|
||||
print("✅ Отправлено")
|
||||
else:
|
||||
print("❌ Файл не найден")
|
||||
|
||||
# Отправка обычного сообщения
|
||||
else:
|
||||
msg = await client.send_message(target_entity, text)
|
||||
local_sent_ids.append(msg.id)
|
||||
|
||||
if len(local_sent_ids) > 50:
|
||||
local_sent_ids.pop(0)
|
||||
|
||||
except (KeyboardInterrupt, EOFError):
|
||||
clear_screen()
|
||||
print("\n🛑 Выход...")
|
||||
await client.disconnect()
|
||||
break
|
||||
|
||||
|
||||
# ==================== ОСНОВНОЙ ЗАПУСК ====================
|
||||
async def main():
|
||||
clear_screen()
|
||||
print("🔄 Подключение к серверам...\n")
|
||||
await client.connect()
|
||||
|
||||
if not await client.is_user_authorized():
|
||||
def print_qr(url):
|
||||
qr = qrcode.QRCode(version=1, box_size=1, border=2)
|
||||
qr.add_data(url)
|
||||
qr.make(fit=True)
|
||||
qr.print_ascii(invert=True)
|
||||
|
||||
qr_login = await client.qr_login()
|
||||
|
||||
while True:
|
||||
clear_screen()
|
||||
print("⚠️ Требуется авторизация. Отсканируйте QR в Telegram:\n")
|
||||
print_qr(qr_login.url)
|
||||
print("\n⏳ Ожидание (обновится через 10 сек)...")
|
||||
|
||||
try:
|
||||
await qr_login.wait(10)
|
||||
break
|
||||
except asyncio.TimeoutError:
|
||||
try:
|
||||
await qr_login.recreate()
|
||||
except:
|
||||
qr_login = await client.qr_login()
|
||||
except errors.SessionPasswordNeededError:
|
||||
clear_screen()
|
||||
while True:
|
||||
pwd = input("🔒 Введите облачный пароль: ")
|
||||
try:
|
||||
await client.sign_in(password=pwd)
|
||||
break
|
||||
except:
|
||||
print("❌ Неверный пароль!")
|
||||
break
|
||||
except Exception:
|
||||
qr_login = await client.qr_login()
|
||||
|
||||
global target_entity
|
||||
clear_screen()
|
||||
|
||||
while True:
|
||||
try:
|
||||
print("✅ Вход выполнен!\n")
|
||||
target_input = input("👤 Введи ID, @username или номер собеседника: ").strip()
|
||||
if not target_input:
|
||||
clear_screen()
|
||||
continue
|
||||
|
||||
if target_input.lstrip('-').isdigit():
|
||||
target_input = int(target_input)
|
||||
|
||||
print("⏳ Поиск...")
|
||||
target_entity = await client.get_entity(target_input)
|
||||
target_name = getattr(target_entity, 'first_name', None) or getattr(target_entity, 'title', None) or "Пользователь"
|
||||
break
|
||||
|
||||
except Exception:
|
||||
clear_screen()
|
||||
print("❌ Не найдено. Попробуй еще раз.")
|
||||
|
||||
clear_screen()
|
||||
print("="*55)
|
||||
print(f"💬 ЧАТ: {target_name}")
|
||||
print("💡 /send <путь> - отправить файл/фото")
|
||||
print("💡 Ctrl+O (или команда /open) - открыть последнее фото/ГС")
|
||||
print("💡 Ctrl+1 - вкл/выкл автоудаление")
|
||||
print("💡 Ctrl+C - выход")
|
||||
print("="*55 + "\n")
|
||||
|
||||
await chat_loop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except (KeyboardInterrupt, SystemExit):
|
||||
clear_screen()
|
||||
print("Скрипт остановлен.")
|
||||
Reference in new issue
Block a user