Вопрос Discord SelfBot (питухон)

expenis 3.1 paster
Пользователь
Статус
Оффлайн
Регистрация
20 Апр 2021
Сообщения
1,468
Реакции[?]
34
Поинты[?]
46K
собственно вкратце, когда бота запускаю через несколько десятков секунд он вылетает из-за Connection to remote host was lost.
видел проблему на stackoverflow но мне не помогло
писал бота вместе с чатом, потому что плохо знаю питухон
Python:
import requests as req
from time import sleep
from datetime import datetime
from websocket import create_connection
import json
import threading

VIRUSTOTAL_API_KEY = "" # VT
DISCORD_TOKEN = "" # DS

def check_file_on_virustotal(file_url):
    response = req.get(file_url)
    if response.status_code != 200:
        return f"Ошибка при скачивании файла: {response.status_code}"

    files = {'file': response.content}
    headers = {'x-apikey': VIRUSTOTAL_API_KEY}
    vt_response = req.post("https://www.virustotal.com/api/v3/files", headers=headers, files=files)

    if vt_response.status_code != 200:
        return f"Ошибка при отправке файла на VirusTotal: {vt_response.status_code} - {vt_response.text}"

    vt_data = vt_response.json()
    file_id = vt_data["data"]["id"]
    return get_virustotal_report(file_id)

def get_virustotal_report(file_id):
    url = f"https://www.virustotal.com/api/v3/analyses/{file_id}"
    headers = {'x-apikey': VIRUSTOTAL_API_KEY}
    response = req.get(url, headers=headers)
    
    if response.status_code != 200:
        return f"Ошибка при получении отчета с VirusTotal: {response.status_code} - {response.text}"

    report_data = response.json()
    stats = report_data['data']['attributes']['stats']
    detections = stats['malicious']
    harmless = stats['harmless']
    suspicious = stats['suspicious']
    
    engines = report_data['data']['attributes']['results']
    detected_engines = [
        f"{engine}: {result['category']}"
        for engine, result in engines.items()
        if result['category'] == "malicious"
    ]
    
    detected_engines_text = "\n".join(detected_engines)
    return (f"Результаты проверки на VirusTotal:\n"
            f"Обнаружено детектов: {detections}\n"
            f"Безопасных: {harmless}\n"
            f"Подозрительных: {suspicious}\n\n"
            f"Антивирусы с детекциями:\n{detected_engines_text}")

def listen_for_messages(token, guild_id):
    while True:
        try:
            ws = create_connection("wss://gateway.discord.gg/")
            payload = {
                "op": 2,
                "d": {
                    "token": token,
                    "properties": {
                        "$os": "linux",
                        "$browser": "ubuntu",
                        "$device": "ubuntu"
                    }
                }
            }
            ws.send(json.dumps(payload))

            while True:
                response = ws.recv()
                try:
                    data = json.loads(response)
                except json.JSONDecodeError:
                    continue

                if 't' in data and data['t'] == 'MESSAGE_CREATE':
                    message = data['d']
                    
                    if message.get('guild_id') == guild_id and message['content'].startswith(".vtcheck"):
                        attachment_url = None
                        if message['attachments']:
                            attachment_url = message['attachments'][0]['url']
                        elif 'referenced_message' in message and message['referenced_message'].get('attachments'):
                            attachment_url = message['referenced_message']['attachments'][0]['url']

                        if attachment_url:
                            result = check_file_on_virustotal(attachment_url)
                        else:
                            result = "Ошибка: файл для проверки не найден."

                        send_message(message['channel_id'], result)

        except Exception as e:
            print(f"Ошибка соединения: {e}")
            print("Переподключение...")
            sleep(1)

def send_message(channel_id, content):
    url = f"https://discord.com/api/v9/channels/{channel_id}/messages"
    headers = {
        'authorization': DISCORD_TOKEN,
        'Content-Type': 'application/json'
    }
    payload = {
        'content': content
    }
    req.post(url, headers=headers, json=payload)

def start_listener():
    guild_id = ""
    thread = threading.Thread(target=listen_for_messages, args=(DISCORD_TOKEN, guild_id))
    thread.start()

start_listener()
 
Сверху Снизу