Pyrogram - проблема смены сессии при использовании break

Пишу спаммер + джойнер со сменой сессий, столкнулся с проблемой: в случае получения флуда если время войта больше 5 минут должен смениться аккаунт, у меня должен выйти с цикла, но когда я прописываю break, то прилетают socket errorы из-за смены аккаунта без отключения старого, а как прописываю app.stop() выдет ошибки что сессия уже завершена. В коде пометил где помочь

from pyrogram import Client
from pyrogram.errors import FloodWait, BadRequest, NotAcceptable, Forbidden
from time import sleep
import tgcrypto
from colorama import init, Fore, Back, Style
import dbm
import glob
import os
import pretty_errors

def dbm_base():
    file = dbm.open( 'api.dbm' ,'c')
    try:
        file['api_id']
    except:
        file['api_id'] = input('Введите api_id:')
        file['api_hash'] = input('Введите api_hash:')
    file.close()
    return dbm.open( 'api.dbm' ,'r')
file = dbm_base()
api_id = int(file['api_id'].decode())
api_hash = file['api_hash'].decode()

dbm_base()

session = 1
count = len(glob.glob1(os.getcwd(),"*.session"))
i = 0
msg_id = 3
msg_chat = 'https://t.me/+rzBqQIU9m1E3NDcy'

while i != count:
    sleep(1)
    with Client(str(session), api_id, api_hash) as app:
        print(Fore.MAGENTA + f'\nЗапускаю сессию... ({session}/{count})\n')
        with open('links.txt', "r") as links:
            for link in links:
                try:
                    chat = app.get_chat(link)
                    sleep(3)
                except FloodWait as e:
                    if e.value < 301:
                        print(Fore.RED + f'Аккаунт словил флуд, сплю {e.value} секунд')
                        sleep(e.value)
                    else:
                        print(f'Аккаунт словил флуд, меняю аккаунт')
                        break #И тут
                except NotAcceptable as private:
                    if '406 CHANNEL_PRIVATE' in f'{private}':
                        continue
                    else:
                        print(private)
                        continue
                except KeyError as chaterr:
                    if "Username not found" in f'{chaterr}' or 'Username not found' in f'{chaterr}':
                        print(Fore.RED + f'Чата больше не существует, пропускаю')
                        with open('dead_links.txt', 'a') as dead:
                            dead.write(link)
                        continue
                except BadRequest as occ:
                    if '400 USERNAME_NOT_OCCUPIED' in f'{occ}':
                        continue
                chat_id = chat.id
                name = chat.title
                ctype = chat.type
                cdesc = chat.description
                if f'{ctype}' != 'ChatType.SUPERGROUP':
                    print(Fore.RED + f'{name} не чат, пропускаю')
                    continue
                if 'smm' not in link  or 'market' not in link or 'dark' not in link or 'piar' not in link:
                    if 'пиар' not in f'{name.lower()}' or 'реклама' not in f'{name.lower()}' or 'smm' not in f'{name.lower()}' or 'раскрутка' not in f'{name.lower()}' or 'продвижение' not in f'{name.lower()}' or 'market' not in f'{name.lower()}' or 'dark' not in f'{name.lower()}' or 'piar' not in f'{name.lower()}':
                        if cdesc != None:
                            if 'пиар' not in f'{cdesc.lower()}' or 'реклама' not in f'{cdesc.lower()}' or 'smm' not in f'{cdesc.lower()}' or 'раскрутка' not in f'{cdesc.lower()}' or 'продвижение' not in f'{cdesc.lower()}' or 'market' not in f'{cdesc.lower()}' or 'dark' not in f'{cdesc.lower()}' or 'piar' not in f'{cdesc.lower()}':
                                with open('dead_links.txt', 'a') as dead:
                                    dead.write(link)
                                continue
                        else:
                            with open('dead_links.txt', 'a') as dead:
                                dead.write(link)
                            continue
                try:
                    try:
                        app.copy_message(chat_id, -1001653608610, msg_id)
                        print(Fore.GREEN + f'Сообщение отправлено в {name}')
                    except FloodWait as e:  
                        if e.value < 301:
                            print(Fore.RED + f'Аккаунт словил флуд, сплю {e.value} секунд')
                            sleep(e.value)
                        else:
                            print(f'Аккаунт словил флуд, меняю аккаунт')
                            break #Тут исправить
                    except Forbidden as netdos:
                        if '403 CHAT_WRITE_FORBIDDEN' in f'{netdos}':
                            print(Fore.RED + f'Чат не позволяет отправлять медиа, пропускаю')
                            with open('dead_links.txt', 'a') as dead:
                                dead.write(link)
                            continue
                    except BadRequest as mmmmm:
                        if '400 USER_ALREADY_PARTICIPANT' in f'{mmmmm}':
                            continue
                    except:
                        app.join_chat(msg_chat)
                        sleep(1)
                        app.copy_message(chat_id, -1001653608610, msg_id)
                        print(Fore.GREEN + f'Сообщение отправлено в {name}')
                    sleep(10)
                except Exception as error:
                    app.join_chat(f"{link}")
                    sleep(1)
                    try:
                        app.copy_message(chat_id, -1001653608610, msg_id)
                        print(Fore.GREEN + f'Сообщение отправлено в {name}')
                    except:
                        app.join_chat(msg_chat)
                        sleep(1)
                        app.copy_message(chat_id, -1001653608610, msg_id)
                        print(Fore.GREEN + f'Сообщение отправлено в {name}')
                    sleep(10)
        app.stop()
        session += 1
    i += 1

Ответы (0 шт):