首页 > 解决方案 > Python 和 Discord 机器人 - Websocket 问题

问题描述

我正在尝试创建一个不和谐机器人来检查一个不和谐频道上的每条消息,并根据第一个频道上打印的消息在另一个私人频道上打印一些内容。一切都很好,所以这不是我的问题。

我的问题是关于 websocket 的,我想让这个机器人每天工作而不关闭。

几个小时后,我收到这条消息:

File "/Users/Name/opt/anaconda3/envs/Algo/lib/python3.8/site-packages/websocket/_socket.py", line 86, in recv
    raise WebSocketConnectionClosedException("socket is already closed.")
websocket._exceptions.WebSocketConnectionClosedException: socket is already closed.

似乎我的 websocket 停止工作,我不知道为什么。你认为有办法避免这种情况吗?或者,当出现此错误时,可能会添加一条会再次启动机器人的行。

如果您想检查,这是完整的代码:

import websocket, json, threading, time, discord
import pandas as pd
from collections import Counter
from discord.embeds import Embed
from discord.ext import tasks

client = discord.Client()

def send_json_request(ws,request):
    ws.send(json.dumps(request))

def receive_json_response(ws):
    response = ws.recv()
    if response:
        return json.loads(response)

def heartbeat(interval,ws):
    print('Hearbeat begin')
    while True:
        time.sleep(interval)
        heartbeatJSON= {
            'op':1,
            'd': 'null'
        }
        send_json_request(ws,heartbeatJSON)
        print("Heartbeat sent")

ws = websocket.WebSocket()
ws.connect("wss://gateway.discord.gg/?v=6&encoding=json")
event = receive_json_response(ws)

heartbeat_interval = event["d"]["heartbeat_interval"] / 1000
threading._start_new_thread(heartbeat,(heartbeat_interval,ws))
token = "TOKEN"

payload = {
    "op":2,
    "d":{
        "token":token,
        "properties":{
            "$os":'windows',
            "$browser":'brave',
            "$device":"pc"
        }
    }
}

send_json_request(ws,payload)
count_apparition = []

@tasks.loop(seconds = 1)
async def test():
    channel = client.get_channel("CHAN TO SEND MESSAGE") 
    while True:
        event = receive_json_response(ws)
        try:
            if (event['d']['channel_id'] == "CHAN TO LOOK AT"): 
                content = event['d']['embeds'] 
                for i in content :
                    print(i['description'])
                    crypto = i['description'].split()[i['description'].split().index('to')-2].split("(")[0] 
                    print(crypto)
                    count_apparition.append(crypto)
                    print(count_apparition)
                    t = Counter(count_apparition)
                    DATA = tuple(t.most_common())
                    s = ['Tickers          Apparitions'] 
                    for data in DATA: 
                        s.append('        '.join([str(item).center(10, ' ') for item in data]))
                    d = '```'+'\n'.join(s) + '```'  
                    embed = discord.Embed(title = '** MY TITLE', description = d)  
                await channel.send(embed = embed)
                op_code = event('op')
                if op_code == 11:
                    print('heartbeat received')
        except:
            pass

@client.event
async def on_ready():
    print("Bot ready")
    test.start()

client.run('PRIVATE KEY')

标签: pythonexceptionwebsocketdiscord.pybots

解决方案


推荐阅读