admin管理员组

文章数量:1123272

My code:

REPORT_REASON_MAP = {
    "child_abuse": InputReportReasonChildAbuse(),
    "copyright": InputReportReasonCopyright(),
    "illegal_drugs": InputReportReasonIllegalDrugs(),
    "other": InputReportReasonOther(),
    "personal_details": InputReportReasonPersonalDetails(),
    "pornography": InputReportReasonPornography(),
    "spam": InputReportReasonSpam(),
    "violence": InputReportReasonViolence(),
}


async def report_message(link, reason) -> (int, int):
    message_link_pattern = repile(r'/(?P<username_or_chat>.+)/(?P<message_id>\d+)')
    chat_link_pattern = repile(r'/(?P<chat_id>\d+)/(?P<message_id>\d+)')

    # Проверка на приватный канал по ссылке
    if chat_link_pattern.match(link):
        print(f"Группа {link} является приватной. Жалоба не будет отправлена.")
        return 0, 0

    match = message_link_pattern.search(link)

    if not match:
        print("Неверная ссылка.")
        return 0, 0

    chat = match.group("username_or_chat")
    message_id = int(match.group("message_id"))

    now = datetime.now()
    last_report_time = last_report_times.get(chat)

    if last_report_time and now - last_report_time < timedelta(minutes=8):
        print(f"Жалобы на {chat} можно отправлять только раз в 8 минут. Попробуйте позже.")
        return 0, 0

    last_report_times[chat] = now

    path = './sessions/'
    files = os.listdir(path)
    sessions = [s for s in files if s.endswith(".session") and s != 'bot.session']

    successful_reports = 0
    failed_reports = 0

    report_reason = REPORT_REASON_MAP.get(reason)

    if not report_reason:
        print(f"Неверная причина: {reason}")
        return 0, 0

    for session in sessions:
        try:
            client = TelegramClient(f"{path}{session}", api_id, api_hash)

            await client.connect()

            if not await client.is_user_authorized():
                print(f"Сессия {session} не авторизована, пропуск.")
                failed_reports += 1
                await client.disconnect()
                continue

            try:
                entity = await client.get_entity(chat)

                if isinstance(entity, Channel):
                    if not chat_link_pattern.match(link):
                        print(f"Публичный канал {chat}, жалоба отправляется.")
                    else:
                        print(f"Приватный канал {chat}, жалоба не отправляется.")
                        failed_reports += 1
                        continue
                else:
                    print(f"Чат {chat} является приватным, жалоба не отправляется.")
                    failed_reports += 1
                    continue

                report_reasons = random.choice(REPORT_MESSAGES)

                await client.report(entity, message_id, report_reason, message=report_reasons)

                await client(ReportRequest(
                    peer=entity,
                    id=[message_id],
                    reason=InputReportReasonSpam(),
                    message=report_reason
                ))

                print(f"Жалоба отправлена через сессию {session}. Номер жалобы: {successful_reports}")
                successful_reports += 1

            except FloodWaitError as e:
                wait_time = e.seconds
                print(f"Flood wait error: необходимо подождать {wait_time} секунд.")
                await asyncio.sleep(wait_time)

            except Exception as e:
                print(f"Ошибка при отправке жалобы через сессию {session}: {e}")
                failed_reports += 1

            finally:
                await client.disconnect()

        except Exception as e:
            print(f"Ошибка при инициализации сессии {session}: {e}")
            failed_reports += 1

    return successful_reports, failed_reports

in await client.report(entity, message_id, report_reason, message=report_reasons) - There is no report method in client. I was told that it can be sent via ReportRequest, but after trying it, there is no argument to select the type of complaint, I don’t understand how I can implement sending a complaint to a message with the selected type of complaint.

My code:

REPORT_REASON_MAP = {
    "child_abuse": InputReportReasonChildAbuse(),
    "copyright": InputReportReasonCopyright(),
    "illegal_drugs": InputReportReasonIllegalDrugs(),
    "other": InputReportReasonOther(),
    "personal_details": InputReportReasonPersonalDetails(),
    "pornography": InputReportReasonPornography(),
    "spam": InputReportReasonSpam(),
    "violence": InputReportReasonViolence(),
}


async def report_message(link, reason) -> (int, int):
    message_link_pattern = re.compile(r'https://t.me/(?P<username_or_chat>.+)/(?P<message_id>\d+)')
    chat_link_pattern = re.compile(r'https://t.me/c/(?P<chat_id>\d+)/(?P<message_id>\d+)')

    # Проверка на приватный канал по ссылке
    if chat_link_pattern.match(link):
        print(f"Группа {link} является приватной. Жалоба не будет отправлена.")
        return 0, 0

    match = message_link_pattern.search(link)

    if not match:
        print("Неверная ссылка.")
        return 0, 0

    chat = match.group("username_or_chat")
    message_id = int(match.group("message_id"))

    now = datetime.now()
    last_report_time = last_report_times.get(chat)

    if last_report_time and now - last_report_time < timedelta(minutes=8):
        print(f"Жалобы на {chat} можно отправлять только раз в 8 минут. Попробуйте позже.")
        return 0, 0

    last_report_times[chat] = now

    path = './sessions/'
    files = os.listdir(path)
    sessions = [s for s in files if s.endswith(".session") and s != 'bot.session']

    successful_reports = 0
    failed_reports = 0

    report_reason = REPORT_REASON_MAP.get(reason)

    if not report_reason:
        print(f"Неверная причина: {reason}")
        return 0, 0

    for session in sessions:
        try:
            client = TelegramClient(f"{path}{session}", api_id, api_hash)

            await client.connect()

            if not await client.is_user_authorized():
                print(f"Сессия {session} не авторизована, пропуск.")
                failed_reports += 1
                await client.disconnect()
                continue

            try:
                entity = await client.get_entity(chat)

                if isinstance(entity, Channel):
                    if not chat_link_pattern.match(link):
                        print(f"Публичный канал {chat}, жалоба отправляется.")
                    else:
                        print(f"Приватный канал {chat}, жалоба не отправляется.")
                        failed_reports += 1
                        continue
                else:
                    print(f"Чат {chat} является приватным, жалоба не отправляется.")
                    failed_reports += 1
                    continue

                report_reasons = random.choice(REPORT_MESSAGES)

                await client.report(entity, message_id, report_reason, message=report_reasons)

                await client(ReportRequest(
                    peer=entity,
                    id=[message_id],
                    reason=InputReportReasonSpam(),
                    message=report_reason
                ))

                print(f"Жалоба отправлена через сессию {session}. Номер жалобы: {successful_reports}")
                successful_reports += 1

            except FloodWaitError as e:
                wait_time = e.seconds
                print(f"Flood wait error: необходимо подождать {wait_time} секунд.")
                await asyncio.sleep(wait_time)

            except Exception as e:
                print(f"Ошибка при отправке жалобы через сессию {session}: {e}")
                failed_reports += 1

            finally:
                await client.disconnect()

        except Exception as e:
            print(f"Ошибка при инициализации сессии {session}: {e}")
            failed_reports += 1

    return successful_reports, failed_reports

in await client.report(entity, message_id, report_reason, message=report_reasons) - There is no report method in client. I was told that it can be sent via ReportRequest, but after trying it, there is no argument to select the type of complaint, I don’t understand how I can implement sending a complaint to a message with the selected type of complaint.

Share Improve this question asked 9 hours ago Zoom ZerzZoom Zerz 1
Add a comment  | 

1 Answer 1

Reset to default 1

Telegram introduced dynamic report reasons that can change per-post being reported starting from Telethon version > 1.37. so either anchor to that version or read the latest api reference before attempting to use things: https://tl.telethon.dev/methods/messages/report.html

as you may notice, reason doesn't exist anymore. There is only option which takes Bytes

You make the first request with an empty byte:

reasons = await client(ReportRequest(
        peer=entity,
        id=[message_id],
        option=b'',
        message=''
    )
)

print(reasons.stringify())

Server must give you ReportResultChooseOption object

you pick one and make the next request with it:

first_choice = reasons.options[0].option

await client(ReportRequest(
        peer=entity,
        id=[message_id],
        option=first_choice,
        message=''
    )
)

本文标签: pythonHow to send a complaint to a message with the selected type of complaint telethonStack Overflow