how to fix loop in a code Python (Pyrogram) - reportpeer

189 Views Asked by At

question, I am building a module for reporting fake news and propaganda, using many accounts (cients - connections). I can't fix the loop to go through the list for each channel TypeError: required asyncio.Future, coprogram or awaitable or something like this. waiting for an audition, or I'm doing something wrong

from config import connections
from rich import print
from rich.console import Console
from threading import Thread
import asyncio
from typing import List, Union, Tuple
import random
import time
from pyrogram.errors.exceptions.bad_request_400 import UsernameInvalid
from pyrogram.raw.functions.account import ReportPeer
from pyrogram.raw.base import InputPeer, ReportReason
from pyrogram.raw.types import (
    InputPeerChannel, 
    
    InputReportReasonViolence, 
    InputReportReasonOther
)


console = Console()
reason_types = [
    InputReportReasonOther,
    InputReportReasonViolence,
]
reasons_msg = [
    "Propaganda of the war in Ukraine. Propaganda of the murder of Ukrainians and Ukrainian soldiers.",
    "The channel undermines the integrity of the Ukrainian state. Spreading fake news, misleading people. Block it as soon as possible!",
]

def report_attack():
    _ = 1
    time.sleep(0)
    for connection in connections:
        app = connection
        print(f"[bold green]{_} | acc run")
        _ += 1

        def to_peer(client: connection, link: str) -> Union[InputPeer, None]:
            try:
                return client.resolve_peer(link)
            except (KeyError, UsernameInvalid):
                return None

        def get_working_peer_list(app: connection) -> List[Tuple[str, InputPeer]]:
            filepath = console.input("[bold red]Enter file path to report\n>>> ")
            with open(filepath, 'r', encoding="UTF-8") as _links:
                links = [link.strip() for link in _links]
    
            working = []
            for l in links:
                peer = to_peer(app, l)
                if peer:
                    working.append((l, peer))
                else:
                    print(f"Skipping '{l}'...")
    
                return working

        def send_report(app: connection, peer: InputPeerChannel) -> bool:
            report_reason_type: ReportReason = random.choice(reason_types)()
            report_reason_message = random.choice(reasons_msg)
            rp = ReportPeer(
            peer=peer, 
            reason=report_reason_type, 
            message=report_reason_message)
            result = app.send(rp)
            return result

        def attack():     
            links =  get_working_peer_list(app)
            while True:
                try:
                    for link in links:
                        report = Thread(target = send_report, args=(app, link[1])).run
                        print(f"[bold green]Successfully sent report to {link[0]}!") if True else print(f"[bold red]!!Failed to send report to {link[0]}.")
                        sleep_interval = random.randint(1, 9999)/3333
                        print('[bold yellow]sleep for {}s before the next batch of 10'.format(sleep_interval))
                        time.sleep(sleep_interval)
                            #print('sleep for 20s')
                            #time.sleep(20)
                        return report
                             #asyncio.run(report)
                except Exception as exc:
                    print(f"[bold red]{links,report} | ERROR | {exc}")
                    continue
            
                
    asyncio.get_event_loop().run_until_complete(attack())

It was possible to fix partially, but now the list is not read all, and only the first element

import platform
from config import connections
from rich import print
from rich.console import Console
from threading import Thread
import asyncio
from typing import List, Union, Tuple
import random
import time
from pyrogram.errors.exceptions.bad_request_400 import UsernameInvalid
from pyrogram.raw.functions.account import ReportPeer
from pyrogram.raw.base import InputPeer, ReportReason
from pyrogram.raw.types import (
    InputPeerChannel, 
    
    InputReportReasonViolence, 
    InputReportReasonOther
)


console = Console()
reason_types = [
    InputReportReasonOther,
    InputReportReasonViolence,
]
reasons_msg = [
    "Propaganda of the war in Ukraine. Propaganda of the murder of Ukrainians and Ukrainian soldiers.",
    "The channel undermines the integrity of the Ukrainian state. Spreading fake news, misleading people. Block it as soon as possible!",
]

def report_attack():
    _ = 1
    for connection in connections:
        print(f"[bold green]{_} | acc run")
        app = connection
        _ += 1
        
        async def to_peer(client: connection, link: str) -> Union[InputPeer, None]:
            try:
                return await client.resolve_peer(link)
            except (KeyError, UsernameInvalid):
                return None

        async def get_working_peer_list(app: connection) -> List[Tuple[str, InputPeer]]:
            filepath = "links.txt"
            with open(filepath, 'r', encoding="UTF-8") as _links:
                links = [link.strip() for link in _links]
    
            working = []
            for l in links:
                peer = await to_peer(app, l)
                if peer:
                    working.append((l, peer))
                else:
                    print(f"Skipping '{l}'...")
    
                return working

        async def send_report(app: connection, peer: InputPeerChannel) -> bool:
            report_reason_type: ReportReason = random.choice(reason_types)()
            report_reason_message = random.choice(reasons_msg)
            rp = ReportPeer(
            peer=peer, 
            reason=report_reason_type, 
            message=report_reason_message)
            result = await app.send(rp)
            return result

        async def attack():
            links = await get_working_peer_list(app)
            while True:
                try:
                    for link in links:
                        report = await send_report(app, link[1])
                        print(f"[bold green]Successfully sent report to {link[0]}!") if True else print(f"[bold red]!!Failed to send report to {link[0]}.")
                        sleep_interval = random.randint(1, 9999)/3333
                        print('[bold yellow]sleep for {}s before the next batch of 10'.format(sleep_interval))
                        await asyncio.sleep(sleep_interval)
                        return report
                except Exception as exc:
                    print(f"[bold red]{links} | ERROR | {exc}")
                    continue
            
                await asyncio.sleep(1)        
        asyncio.get_event_loop().run_until_complete(attack())
if __name__ == "__main__":
    if platform.system() == 'Windows':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
0

There are 0 best solutions below