Хотелось бы сразу готовый код так как я сильно тупой и слишком рано в это залез. Код: import os import logging import time import random import string from telegram import Update, InputFile, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import ( Application, CommandHandler, MessageHandler, filters, ConversationHandler, ContextTypes ) from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from smsactivateru import Sms, SmsTypes, SmsService, GetNumber # Конфигурация API_KEY = "ВАШ_TELEGRAM_BOT_TOKEN" SMS_API_KEY = "B317824e2c973175432B97B40e6c0556" PASSWORD = "st0705" BIRTH_DATE = {"day": "7", "month": "5", "year": "2007"} IMAGE_FILE = "arglogo.jpg" SMS_PRICE_URL = "https://sms-activate.guru/ru/buy" PROFILES_DIR = "/storage/emulated/0/AutoReg Google Account/browser_profiles" GECKODRIVER_PATH = "/storage/emulated/0/AutoReg Google Account/Drivers/geckodriver" # Состояния диалога PASSWORD, QUANTITY = range(2) # Настройка логирования logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) def create_browser_instance(profile_id): """Создает изолированный экземпляр браузера""" try: options = webdriver.FirefoxOptions() profile_path = os.path.join(PROFILES_DIR, f"profile_{profile_id}") options.profile = profile_path return webdriver.Firefox( executable_path=GECKODRIVER_PATH, options=options ) except Exception as e: logger.error(f"Ошибка инициализации браузера: {str(e)}") raise def generate_credentials(): """Генерирует случайные данные для аккаунта""" return { "first_name": ''.join(random.choices(string.ascii_lowercase, k=6)), "last_name": ''.join(random.choices(string.ascii_lowercase, k=8)), "username": ''.join(random.choices(string.ascii_lowercase, k=12)), "password": "Passwww1222" } async def register_account(driver, credentials, phone, code): """Выполняет процесс регистрации аккаунта""" try: driver.get('https://accounts.google.com/signup') time.sleep(2) # Заполнение основной формы driver.find_element(By.ID, 'firstName').send_keys(credentials['first_name']) driver.find_element(By.ID, 'lastName').send_keys(credentials['last_name']) driver.find_element(By.ID, 'username').send_keys(credentials['username']) driver.find_element(By.NAME, 'Passwd').send_keys(credentials['password']) driver.find_element(By.NAME, 'ConfirmPasswd').send_keys(credentials['password']) driver.find_element(By.ID, 'accountDetailsNext').click() time.sleep(3) # Ввод телефона и кода driver.find_element(By.ID, 'phoneNumberId').send_keys(f'+{phone}') driver.find_element(By.XPATH, '//button[.="Далее"]').click() time.sleep(3) driver.find_element(By.ID, 'code').send_keys(code) driver.find_element(By.XPATH, '//button[.="Подтвердить"]').click() time.sleep(3) # Ввод даты рождения Select(driver.find_element(By.ID, 'month')).select_by_value(BIRTH_DATE['month']) driver.find_element(By.ID, 'day').send_keys(BIRTH_DATE['day']) driver.find_element(By.ID, 'year').send_keys(BIRTH_DATE['year']) Select(driver.find_element(By.ID, 'gender')).select_by_value('2') driver.find_element(By.XPATH, '//button[.="Далее"]').click() time.sleep(3) return True except Exception as e: logger.error(f"Ошибка регистрации: {str(e)}") return False async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: try: await update.message.reply_photo( photo=InputFile(IMAGE_FILE), caption=" Введите пароль для начала работы" ) return PASSWORD except Exception as e: logger.error(f"Ошибка запуска: {str(e)}") await update.message.reply_text("❌ Ошибка инициализации") return ConversationHandler.END async def process_password(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: if update.message.text != PASSWORD: await update.message.reply_text("❌ Неверный пароль! Попробуйте снова.") return PASSWORD await update.message.reply_text(" Введите количество аккаунтов для создания") return QUANTITY async def process_quantity(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: try: quantity = int(update.message.text) if quantity <= 0: raise ValueError # Проверка баланса wrapper = Sms(SMS_API_KEY) balance = wrapper.get_balance() price = wrapper.get_price(SmsService().Google, SmsTypes.Country.RO) if balance < price * quantity: keyboard = [[InlineKeyboardButton(" Пополнить баланс", url=SMS_PRICE_URL)]] await update.message.reply_text( f"❌ Недостаточно средств. Требуется: {price*quantity} RUB", reply_markup=InlineKeyboardMarkup(keyboard) ) return ConversationHandler.END await update.message.reply_text("⏳ Начинаю создание аккаунтов...") success_count = 0 results = [] for i in range(quantity): try: profile_id = int(time.time()) + i os.makedirs(os.path.join(PROFILES_DIR, f"profile_{profile_id}"), exist_ok=True) with create_browser_instance(profile_id) as driver: # Получение номера activation = GetNumber( service=SmsService().Google, country=SmsTypes.Country.RO ).request(wrapper) # Обработка SMS activation.was_sent() code = activation.wait_code(wrapper=wrapper, timeout=300) # Регистрация credentials = generate_credentials() if await register_account(driver, credentials, activation.phone_number, code): results.append(f"{credentials['username']}@gmail.com:{credentials['password']}") success_count += 1 with open('accounts.txt', 'a') as f: f.write(f"{credentials['username']}@gmail.com:{credentials['password']}\n") except Exception as e: logger.error(f"Ошибка при создании аккаунта {i+1}: {str(e)}") continue await update.message.reply_text( f"✅ Успешно создано: {success_count}/{quantity}\n" + "\n".join(results) + "\n\nДля просмотра полного списка используйте /list" ) except ValueError: await update.message.reply_text("⚠ Пожалуйста, введите целое число больше нуля") return QUANTITY except Exception as e: logger.error(f"Критическая ошибка: {str(e)}") await update.message.reply_text("❌ Произошла критическая ошибка") return ConversationHandler.END async def send_email_file(update: Update, context: ContextTypes.DEFAULT_TYPE): try: await update.message.reply_document( document=InputFile('accounts.txt'), caption=" Полный список созданных аккаунтов" ) except FileNotFoundError: await update.message.reply_text("❌ Файл с аккаунтами не найден") async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: await update.message.reply_text('❌ Операция отменена') return ConversationHandler.END def main() -> None: # Создание необходимых директорий os.makedirs(PROFILES_DIR, exist_ok=True) # Инициализация бота application = Application.builder().token(API_KEY).build() # Регистрация обработчиков conv_handler = ConversationHandler( entry_points=[CommandHandler("start", start)], states={ PASSWORD: [MessageHandler(filters.TEXT & ~filters.COMMAND, process_password)], QUANTITY: [MessageHandler(filters.TEXT & ~filters.COMMAND, process_quantity)] }, fallbacks=[CommandHandler("cancel", cancel)] ) application.add_handler(conv_handler) application.add_handler(CommandHandler("list", send_email_file)) application.run_polling() if __name__ == '__main__': main() Ошибка: Traceback (most recent call last): File "/data/data/com.termux/files/home/downloads/arg.py", line 7, in <module> from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler, CallbackContext ImportError: cannot import name 'Filters' from 'telegram.ext' (/data/data/com.termux/files/usr/lib/python3.12/site-packages/telegram/ext/__init__.py). Did you mean: 'filters'? Да,я запускал в Termux. Как это можно решить или может быть есть какие-то способы улучшить это дерьмо?
замени from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler, CallbackContext Код from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler, CallbackContext на from telegram.ext import Application, CommandHandler, MessageHandler, filters, ConversationHandler, ContextTypes Код from telegram.ext import Application, CommandHandler, MessageHandler, filters, ConversationHandler, ContextTypes
попробуй import os import logging import time import random import string from telegram import Update, InputFile, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import ( Application, CommandHandler, MessageHandler, filters, ConversationHandler, ContextTypes ) from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from smsactivateru import Sms, SmsTypes, SmsService, GetNumber # Конфигурация API_KEY = "ВАШ_TELEGRAM_BOT_TOKEN" SMS_API_KEY = "B317824e2c973175432B97B40e6c0556" PASSWORD = "st0705" BIRTH_DATE = {"day": "7", "month": "5", "year": "2007"} IMAGE_FILE = "arglogo.jpg" SMS_PRICE_URL = "https://sms-activate.guru/ru/buy" PROFILES_DIR = "/storage/emulated/0/AutoReg Google Account/browser_profiles" GECKODRIVER_PATH = "/storage/emulated/0/AutoReg Google Account/Drivers/geckodriver" # Состояния диалога PASSWORD, QUANTITY = range(2) # Настройка логирования logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) def create_browser_instance(profile_id): """Создает изолированный экземпляр браузера""" try: options = webdriver.FirefoxOptions() profile_path = os.path.join(PROFILES_DIR, f"profile_{profile_id}") options.profile = profile_path return webdriver.Firefox( executable_path=GECKODRIVER_PATH, options=options ) except Exception as e: logger.error(f"Ошибка инициализации браузера: {str(e)}") raise def generate_credentials(): """Генерирует случайные данные для аккаунта""" return { "first_name": ''.join(random.choices(string.ascii_lowercase, k=6)), "last_name": ''.join(random.choices(string.ascii_lowercase, k=8)), "username": ''.join(random.choices(string.ascii_lowercase, k=12)), "password": "Passwww1222" } async def register_account(driver, credentials, phone, code): """Выполняет процесс регистрации аккаунта""" try: driver.get('https://accounts.google.com/signup') time.sleep(2) # Заполнение основной формы driver.find_element(By.ID, 'firstName').send_keys(credentials['first_name']) driver.find_element(By.ID, 'lastName').send_keys(credentials['last_name']) driver.find_element(By.ID, 'username').send_keys(credentials['username']) driver.find_element(By.NAME, 'Passwd').send_keys(credentials['password']) driver.find_element(By.NAME, 'ConfirmPasswd').send_keys(credentials['password']) driver.find_element(By.ID, 'accountDetailsNext').click() time.sleep(3) # Ввод телефона и кода driver.find_element(By.ID, 'phoneNumberId').send_keys(f'+{phone}') driver.find_element(By.XPATH, '//button[.="Далее"]').click() time.sleep(3) driver.find_element(By.ID, 'code').send_keys(code) driver.find_element(By.XPATH, '//button[.="Подтвердить"]').click() time.sleep(3) # Ввод даты рождения Select(driver.find_element(By.ID, 'month')).select_by_value(BIRTH_DATE['month']) driver.find_element(By.ID, 'day').send_keys(BIRTH_DATE['day']) driver.find_element(By.ID, 'year').send_keys(BIRTH_DATE['year']) Select(driver.find_element(By.ID, 'gender')).select_by_value('2') driver.find_element(By.XPATH, '//button[.="Далее"]').click() time.sleep(3) return True except Exception as e: logger.error(f"Ошибка регистрации: {str(e)}") return False async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: try: await update.message.reply_photo( photo=InputFile(IMAGE_FILE), caption="Введите пароль для начала работы" ) return PASSWORD except Exception as e: logger.error(f"Ошибка запуска: {str(e)}") await update.message.reply_text("❌ Ошибка инициализации") return ConversationHandler.END async def process_password(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: if update.message.text != PASSWORD: await update.message.reply_text("❌ Неверный пароль! Попробуйте снова.") return PASSWORD await update.message.reply_text("Введите количество аккаунтов для создания") return QUANTITY async def process_quantity(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: try: quantity = int(update.message.text) if quantity <= 0: raise ValueError # Проверка баланса wrapper = Sms(SMS_API_KEY) balance = wrapper.get_balance() price = wrapper.get_price(SmsService().Google, SmsTypes.Country.RO) if balance < price * quantity: keyboard = [[InlineKeyboardButton("Пополнить баланс", url=SMS_PRICE_URL)]] await update.message.reply_text( f"❌ Недостаточно средств. Требуется: {price*quantity} RUB", reply_markup=InlineKeyboardMarkup(keyboard) ) return ConversationHandler.END await update.message.reply_text("⏳ Начинаю создание аккаунтов...") success_count = 0 results = [] for i in range(quantity): try: profile_id = int(time.time()) + i os.makedirs(os.path.join(PROFILES_DIR, f"profile_{profile_id}"), exist_ok=True) with create_browser_instance(profile_id) as driver: # Получение номера activation = GetNumber( service=SmsService().Google, country=SmsTypes.Country.RO ).request(wrapper) # Обработка SMS activation.was_sent() code = activation.wait_code(wrapper=wrapper, timeout=300) # Регистрация credentials = generate_credentials() if await register_account(driver, credentials, activation.phone_number, code): results.append(f"{credentials['username']}@gmail.com:{credentials['password']}") success_count += 1 with open('accounts.txt', 'a') as f: f.write(f"{credentials['username']}@gmail.com:{credentials['password']}\n") except Exception as e: logger.error(f"Ошибка при создании аккаунта {i+1}: {str(e)}") continue await update.message.reply_text( f"✅ Успешно создано: {success_count}/{quantity}\n" + "\n".join(results) + "\n\nДля просмотра полного списка используйте /list" ) except ValueError: await update.message.reply_text("⚠ Пожалуйста, введите целое число больше нуля") return QUANTITY except Exception as e: logger.error(f"Критическая ошибка: {str(e)}") await update.message.reply_text("❌ Произошла критическая ошибка") return ConversationHandler.END async def send_email_file(update: Update, context: ContextTypes.DEFAULT_TYPE): try: await update.message.reply_document( document=InputFile('accounts.txt'), caption="Полный список созданных аккаунтов" ) except FileNotFoundError: await update.message.reply_text("❌ Файл с аккаунтами не найден") async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: await update.message.reply_text('❌ Операция отменена') return ConversationHandler.END def main() -> None: # Создание необходимых директорий os.makedirs(PROFILES_DIR, exist_ok=True) # Инициализация бота application = Application.builder().token(API_KEY).build() # Регистрация обработчиков conv_handler = ConversationHandler( entry_points=[CommandHandler("start", start)], states={ PASSWORD: [MessageHandler(filters.TEXT & ~filters.COMMAND, process_password)], QUANTITY: [MessageHandler(filters.TEXT & ~filters.COMMAND, process_quantity)] }, fallbacks=[CommandHandler("cancel", cancel)] ) application.add_handler(conv_handler) application.add_handler(CommandHandler("list", send_email_file)) application.run_polling() if __name__ == '__main__': main() Python import os import logging import time import random import string from telegram import Update, InputFile, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import ( Application, CommandHandler, MessageHandler, filters, ConversationHandler, ContextTypes ) from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from smsactivateru import Sms, SmsTypes, SmsService, GetNumber # Конфигурация API_KEY = "ВАШ_TELEGRAM_BOT_TOKEN" SMS_API_KEY = "B317824e2c973175432B97B40e6c0556" PASSWORD = "st0705" BIRTH_DATE = {"day": "7", "month": "5", "year": "2007"} IMAGE_FILE = "arglogo.jpg" SMS_PRICE_URL = "https://sms-activate.guru/ru/buy" PROFILES_DIR = "/storage/emulated/0/AutoReg Google Account/browser_profiles" GECKODRIVER_PATH = "/storage/emulated/0/AutoReg Google Account/Drivers/geckodriver" # Состояния диалога PASSWORD, QUANTITY = range(2) # Настройка логирования logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) def create_browser_instance(profile_id): """Создает изолированный экземпляр браузера""" try: options = webdriver.FirefoxOptions() profile_path = os.path.join(PROFILES_DIR, f"profile_{profile_id}") options.profile = profile_path return webdriver.Firefox( executable_path=GECKODRIVER_PATH, options=options ) except Exception as e: logger.error(f"Ошибка инициализации браузера: {str(e)}") raise def generate_credentials(): """Генерирует случайные данные для аккаунта""" return { "first_name": ''.join(random.choices(string.ascii_lowercase, k=6)), "last_name": ''.join(random.choices(string.ascii_lowercase, k=8)), "username": ''.join(random.choices(string.ascii_lowercase, k=12)), "password": "Passwww1222" } async def register_account(driver, credentials, phone, code): """Выполняет процесс регистрации аккаунта""" try: driver.get('https://accounts.google.com/signup') time.sleep(2) # Заполнение основной формы driver.find_element(By.ID, 'firstName').send_keys(credentials['first_name']) driver.find_element(By.ID, 'lastName').send_keys(credentials['last_name']) driver.find_element(By.ID, 'username').send_keys(credentials['username']) driver.find_element(By.NAME, 'Passwd').send_keys(credentials['password']) driver.find_element(By.NAME, 'ConfirmPasswd').send_keys(credentials['password']) driver.find_element(By.ID, 'accountDetailsNext').click() time.sleep(3) # Ввод телефона и кода driver.find_element(By.ID, 'phoneNumberId').send_keys(f'+{phone}') driver.find_element(By.XPATH, '//button[.="Далее"]').click() time.sleep(3) driver.find_element(By.ID, 'code').send_keys(code) driver.find_element(By.XPATH, '//button[.="Подтвердить"]').click() time.sleep(3) # Ввод даты рождения Select(driver.find_element(By.ID, 'month')).select_by_value(BIRTH_DATE['month']) driver.find_element(By.ID, 'day').send_keys(BIRTH_DATE['day']) driver.find_element(By.ID, 'year').send_keys(BIRTH_DATE['year']) Select(driver.find_element(By.ID, 'gender')).select_by_value('2') driver.find_element(By.XPATH, '//button[.="Далее"]').click() time.sleep(3) return True except Exception as e: logger.error(f"Ошибка регистрации: {str(e)}") return False async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: try: await update.message.reply_photo( photo=InputFile(IMAGE_FILE), caption="Введите пароль для начала работы" ) return PASSWORD except Exception as e: logger.error(f"Ошибка запуска: {str(e)}") await update.message.reply_text("❌ Ошибка инициализации") return ConversationHandler.END async def process_password(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: if update.message.text != PASSWORD: await update.message.reply_text("❌ Неверный пароль! Попробуйте снова.") return PASSWORD await update.message.reply_text("Введите количество аккаунтов для создания") return QUANTITY async def process_quantity(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: try: quantity = int(update.message.text) if quantity <= 0: raise ValueError # Проверка баланса wrapper = Sms(SMS_API_KEY) balance = wrapper.get_balance() price = wrapper.get_price(SmsService().Google, SmsTypes.Country.RO) if balance < price * quantity: keyboard = [[InlineKeyboardButton("Пополнить баланс", url=SMS_PRICE_URL)]] await update.message.reply_text( f"❌ Недостаточно средств. Требуется: {price*quantity} RUB", reply_markup=InlineKeyboardMarkup(keyboard) ) return ConversationHandler.END await update.message.reply_text("⏳ Начинаю создание аккаунтов...") success_count = 0 results = [] for i in range(quantity): try: profile_id = int(time.time()) + i os.makedirs(os.path.join(PROFILES_DIR, f"profile_{profile_id}"), exist_ok=True) with create_browser_instance(profile_id) as driver: # Получение номера activation = GetNumber( service=SmsService().Google, country=SmsTypes.Country.RO ).request(wrapper) # Обработка SMS activation.was_sent() code = activation.wait_code(wrapper=wrapper, timeout=300) # Регистрация credentials = generate_credentials() if await register_account(driver, credentials, activation.phone_number, code): results.append(f"{credentials['username']}@gmail.com:{credentials['password']}") success_count += 1 with open('accounts.txt', 'a') as f: f.write(f"{credentials['username']}@gmail.com:{credentials['password']}\n") except Exception as e: logger.error(f"Ошибка при создании аккаунта {i+1}: {str(e)}") continue await update.message.reply_text( f"✅ Успешно создано: {success_count}/{quantity}\n" + "\n".join(results) + "\n\nДля просмотра полного списка используйте /list" ) except ValueError: await update.message.reply_text("⚠ Пожалуйста, введите целое число больше нуля") return QUANTITY except Exception as e: logger.error(f"Критическая ошибка: {str(e)}") await update.message.reply_text("❌ Произошла критическая ошибка") return ConversationHandler.END async def send_email_file(update: Update, context: ContextTypes.DEFAULT_TYPE): try: await update.message.reply_document( document=InputFile('accounts.txt'), caption="Полный список созданных аккаунтов" ) except FileNotFoundError: await update.message.reply_text("❌ Файл с аккаунтами не найден") async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: await update.message.reply_text('❌ Операция отменена') return ConversationHandler.END def main() -> None: # Создание необходимых директорий os.makedirs(PROFILES_DIR, exist_ok=True) # Инициализация бота application = Application.builder().token(API_KEY).build() # Регистрация обработчиков conv_handler = ConversationHandler( entry_points=[CommandHandler("start", start)], states={ PASSWORD: [MessageHandler(filters.TEXT & ~filters.COMMAND, process_password)], QUANTITY: [MessageHandler(filters.TEXT & ~filters.COMMAND, process_quantity)] }, fallbacks=[CommandHandler("cancel", cancel)] ) application.add_handler(conv_handler) application.add_handler(CommandHandler("list", send_email_file)) application.run_polling() if __name__ == '__main__': main()