Загрузка...

Script I wrote a simple script for sending messages on the chat of the usay a bit of the GPT.

Thread in Python created by SkizmikLolz Jul 29, 2025 at 1:14 AM. 67 views

  1. SkizmikLolz
    SkizmikLolz Topic starter Jul 29, 2025 at 1:14 AM 1 Apr 21, 2024
    Пишу как хочу дитенаху

    Python
    import os
    import time
    import configparser
    from telethon.sync import TelegramClient
    from telethon.tl.functions.messages import SendMessageRequest
    from telethon.tl.types import InputPeerUser, InputPeerChat, InputPeerChannel
    from datetime import datetime
    import colorama
    from colorama import Fore, Style
    import threading
    import signal
    import sys
    import ast

    colorama.init()

    class Extez:
    def __init__(self):
    self.running = True
    self.config = configparser.ConfigParser()
    self.load_config()
    self.setup_client()
    self.chats = self.load_chats()
    self.auto_replies_enabled = self.config.getboolean('Settings', 'auto_replies')
    self.auto_join_enabled = self.config.getboolean('Settings', 'auto_join')
    self.message_delay = self.config.getint('Settings', 'message_delay')
    self.mode = self.config['Settings'].get('mode', 'single')
    self.broadcast_message = self.config['Messages'].get('broadcast_message', '')
    self.auto_reply_message = self.config['Messages'].get('auto_reply_message', '')
    signal.signal(signal.SIGINT, self.signal_handler)

    def load_config(self):
    if not os.path.exists('config.ini'):
    self.create_config()
    self.config.read('config.ini')

    def create_config(self):
    self.config['Telegram'] = {
    'api_id': input("Введите API ID: "),
    'api_hash': input("Введите API Hash: "),
    'phone': input("Введите номер телефона: "),
    'session': 'extez_session'
    }
    self.config['Settings'] = {
    'auto_replies': 'False',
    'auto_join': 'False',
    'message_delay': '5',
    'mode': 'single'
    }
    self.config['Messages'] = {
    'broadcast_message': '',
    'auto_reply_message': ''
    }
    self.config['Chats'] = {}
    with open('config.ini', 'w') as configfile:
    self.config.write(configfile)

    def load_chats(self):
    chats = []
    for key in self.config['Chats']:
    try:
    entity = self.client.get_entity(int(key) if key.isdigit() else key)
    chats.append(entity)
    except Exception as e:
    print(Fore.RED + f"Ошибка загрузки чата {key}: {e}" + Style.RESET_ALL)
    return chats

    def save_chats(self):
    self.config['Chats'] = {}
    for chat in self.chats:
    if hasattr(chat, 'username') and chat.username:
    self.config['Chats'][chat.username] = str(chat.id)
    else:
    self.config['Chats'][str(chat.id)] = str(chat.id)
    with open('config.ini', 'w') as configfile:
    self.config.write(configfile)

    def save_messages(self):
    self.config['Messages']['broadcast_message'] = self.broadcast_message
    self.config['Messages']['auto_reply_message'] = self.auto_reply_message
    with open('config.ini', 'w') as configfile:
    self.config.write(configfile)

    def setup_client(self):
    api_id = int(self.config['Telegram']['api_id'])
    api_hash = self.config['Telegram']['api_hash']
    phone = self.config['Telegram']['phone']
    session_name = self.config['Telegram']['session']

    if not os.path.exists('sessions'):
    os.makedirs('sessions')

    self.client = TelegramClient(f'sessions/{session_name}', api_id, api_hash)
    self.client.connect()

    if not self.client.is_user_authorized():
    self.client.send_code_request(phone)
    self.client.sign_in(phone, input('Введите код подтверждения: '))

    def print_header(self):
    os.system('cls' if os.name == 'nt' else 'clear')
    print(Style.BRIGHT + Fore.CYAN + "Extez".center(30))
    print(Style.RESET_ALL + "="*30 + Style.RESET_ALL)
    print("1. Управление чатами")
    print("2. Управление сообщениями")
    print("3. Настройки")
    print("4. Начать рассылку")
    print("5. Выход")
    print("="*30)

    def chats_menu(self):
    while True:
    os.system('cls' if os.name == 'nt' else 'clear')
    print("Управление чатами".center(30))
    print("="*30)
    print("1. Добавить чат")
    print("2. Удалить чат")
    print("3. Просмотр списка чатов")
    print("4. Назад")
    print("="*30)

    choice = input("Выберите опцию: ")
    if choice == '1':
    self.add_chat()
    elif choice == '2':
    self.remove_chat()
    elif choice == '3':
    self.view_chats()
    elif choice == '4':
    break

    def add_chat(self):
    chat_identifier = input("Введите username или ID чата: ")
    try:
    entity = self.client.get_entity(chat_identifier)
    self.chats.append(entity)
    self.save_chats()
    print(Fore.GREEN + f"Чат {chat_identifier} добавлен" + Style.RESET_ALL)
    except Exception as e:
    print(Fore.RED + f"Ошибка: {e}" + Style.RESET_ALL)
    time.sleep(1.5)

    def remove_chat(self):
    if not self.chats:
    print(Fore.RED + "Список чатов пуст" + Style.RESET_ALL)
    time.sleep(1.5)
    return

    print("Список чатов:")
    for i, chat in enumerate(self.chats, 1):
    print(f"{i}. {chat.title if hasattr(chat, 'title') else chat.username}")

    try:
    choice = int(input("Введите номер чата для удаления: "))
    if 1 <= choice <= len(self.chats):
    removed = self.chats.pop(choice - 1)
    self.save_chats()
    print(Fore.GREEN + f"Чат {removed.title if hasattr(removed, 'title') else removed.username} удален" + Style.RESET_ALL)
    else:
    print(Fore.RED + "Неверный номер" + Style.RESET_ALL)
    except ValueError:
    print(Fore.RED + "Неверный ввод" + Style.RESET_ALL)
    time.sleep(1.5)

    def view_chats(self):
    if not self.chats:
    print(Fore.YELLOW + "Список чатов пуст" + Style.RESET_ALL)
    else:
    print("Текущие чаты:")
    for i, chat in enumerate(self.chats, 1):
    print(f"{i}. {chat.title if hasattr(chat, 'title') else chat.username}")
    input("Выйти...")

    def messages_menu(self):
    while True:
    os.system('cls' if os.name == 'nt' else 'clear')
    print("Управление сообщениями".center(30))
    print("="*30)
    print(f"1. Сообщение для рассылки: {'Установлено' if self.broadcast_message else 'Не установлено'}")
    print(f"2. Сообщение автоответа: {'Установлено' if self.auto_reply_message else 'Не установлено'}")
    print("3. Назад")
    print("="*30)

    choice = input("Выберите опцию: ")
    if choice == '1':
    self.set_broadcast_message()
    elif choice == '2':
    self.set_auto_reply()
    elif choice == '3':
    break

    def set_broadcast_message(self):
    print(f"Текущее сообщение: {self.broadcast_message}")
    self.broadcast_message = input("Введите новое сообщение для рассылки: ") or self.broadcast_message
    self.save_messages()
    print(Fore.GREEN + "Сообщение для рассылки сохранено" + Style.RESET_ALL)
    time.sleep(1.5)

    def set_auto_reply(self):
    print(f"Текущий автоответ: {self.auto_reply_message}")
    self.auto_reply_message = input("Введите новое сообщение для автоответа (оставьте пустым чтобы не менять): ") or self.auto_reply_message
    self.save_messages()
    print(Fore.GREEN + "Сообщение автоответа сохранено" + Style.RESET_ALL)
    time.sleep(1.5)

    def settings_menu(self):
    while True:
    os.system('cls' if os.name == 'nt' else 'clear')
    print("Настройки".center(30))
    print("="*30)
    print(f"1. Автоответы: {'Включены' if self.auto_replies_enabled else 'Выключены'}")
    print(f"2. Автозаход: {'Включен' if self.auto_join_enabled else 'Выключен'}")
    print(f"3. Задержка между сообщениями: {self.message_delay} сек")
    print(f"4. Режим работы: {self.mode}")
    print("5. Назад")
    print("="*30)

    choice = input("Выберите опцию: ")
    if choice == '1':
    self.auto_replies_enabled = not self.auto_replies_enabled
    self.config['Settings']['auto_replies'] = str(self.auto_replies_enabled)
    with open('config.ini', 'w') as configfile:
    self.config.write(configfile)
    elif choice == '2':
    self.auto_join_enabled = not self.auto_join_enabled
    self.config['Settings']['auto_join'] = str(self.auto_join_enabled)
    with open('config.ini', 'w') as configfile:
    self.config.write(configfile)
    elif choice == '3':
    try:
    self.message_delay = int(input("Введите задержку в секундах: "))
    self.config['Settings']['message_delay'] = str(self.message_delay)
    with open('config.ini', 'w') as configfile:
    self.config.write(configfile)
    except ValueError:
    print(Fore.RED + "Неверное значение" + Style.RESET_ALL)
    time.sleep(1.5)
    elif choice == '4':
    self.mode = "multi" if self.mode == "single" else "single"
    self.config['Settings']['mode'] = self.mode
    with open('config.ini', 'w') as configfile:
    self.config.write(configfile)
    elif choice == '5':
    break

    def log_message(self, message, success=True):
    timestamp = Fore.CYAN + datetime.now().strftime("[%H:%M:%S]") + Style.RESET_ALL
    if success:
    print(f"{timestamp} {Fore.GREEN}{message}{Style.RESET_ALL}")
    else:
    print(f"{timestamp} {Fore.RED}{message}{Style.RESET_ALL}")

    def send_message(self, chat, message):
    try:
    self.client(SendMessageRequest(
    peer=chat,
    message=message,
    no_webpage=True
    ))
    self.log_message(f"Отправлено сообщение в чат - {chat.title if hasattr(chat, 'title') else chat.username}")
    return True
    except Exception as e:
    self.log_message(f"Не удалось отправить сообщение в чат - {chat.title if hasattr(chat, 'title') else chat.username} [Error]", False)
    return False

    def broadcast_messages(self):
    if not self.chats:
    print(Fore.RED + "Добавьте хотя бы один чат для рассылки" + Style.RESET_ALL)
    time.sleep(1.5)
    return

    if not self.broadcast_message:
    print(Fore.RED + "Установите сообщение для рассылки" + Style.RESET_ALL)
    time.sleep(1.5)
    return

    self.running = True
    print(Fore.YELLOW + "Для остановки рассылки нажмите Ctrl+C" + Style.RESET_ALL)

    def signal_handler(sig, frame):
    self.running = False
    print(Fore.YELLOW + "\nРассылка остановлена" + Style.RESET_ALL)

    signal.signal(signal.SIGINT, signal_handler)

    while self.running:
    if self.mode == "multi":
    for chat in self.chats:
    if not self.running:
    break
    self.send_message(chat, self.broadcast_message)
    time.sleep(self.message_delay)
    else:
    for chat in self.chats:
    if not self.running:
    break
    if self.send_message(chat, self.broadcast_message):
    time.sleep(self.message_delay)

    def start(self):
    while True:
    self.print_header()
    choice = input("Выберите опцию: ")

    if choice == '1':
    self.chats_menu()
    elif choice == '2':
    self.messages_menu()
    elif choice == '3':
    self.settings_menu()
    elif choice == '4':
    self.broadcast_messages()
    input("Подтвердите действие...")
    elif choice == '5':
    break

    def signal_handler(self, sig, frame):
    self.running = False
    print(Fore.YELLOW + "\nЗавершение работы..." + Style.RESET_ALL)
    sys.exit(0.5)

    if __name__ == "__main__":
    app = Extez()
    app.start()
     
  2. SkizmikLolz
    SkizmikLolz Topic starter Jul 29, 2025 at 1:14 AM 1 Apr 21, 2024
    Я босс гпт
     
  3. farzen
    farzen Jul 29, 2025 at 1:15 AM На нинтендо снич - (510/22000) 724 Jul 15, 2019
    Ну юзать нейронки для программирования уже как будто по госту
     
    1. SkizmikLolz Topic starter
      farzen, в вс коде нейронку юзал
Loading...
Top