我想运行一个websocket与我的discord.py Bot并发。
我希望有人能帮我解决这个问题。提前谢谢。 client.py的代码(测试websocket):import asyncio
import websockets
uri = 'ws://localhost:8000'
async def send_message():
async with websockets.connect(uri) as websocket:
message = "msg"
await websocket.send(message)
print(f"[ws client] message > {message}")
#answer = await websocket.recv()
#print(f"[ws client] answer < {answer}")
asyncio.run(send_message())
main.py代码(Websocket/机器人):# --- websockets ----
async def response(websocket, path):
message = await websocket.recv()
print(f"[ws server] message < {message}")
# --- start ---
async def serve():
print('running websockets ws://localhost:8000')
server = await websockets.serve(response, 'localhost', 8000)
await server.wait_closed()
# - discord -
client = Client()
if __name__ == "__main__":
info_logger.info(f"starting Discord Bot!")
asyncio.run(serve())
client.run(os.getenv("BOTTOKEN"))
由于大多数人都在使用它,我之前尝试的是:
asyncio.get_event_loop().run_until_complete()
然而,这不再工作了,因为我得到一个弃用警告…
在阅读了几篇文章之后,我只能运行其中一个,而不是在一个循环中运行两个。
线程也不能工作,因为它们都是异步的,并且会抛出一个错误,认为它们不能在线程中运行。
使用asyncio.create_task
在后台运行一个协程"。
# --- websockets ----
async def response(websocket, path):
message = await websocket.recv()
print(f"[ws server] message < {message}")
# --- start ---
async def serve():
print('running websockets ws://localhost:8000')
server = await websockets.serve(response, 'localhost', 8000)
await server.wait_closed()
# - discord -
client = Client()
if __name__ == "__main__":
info_logger.info(f"starting Discord Bot!")
asyncio.create_task(serve()) # <-- instead of asyncio.run
client.run(os.getenv("BOTTOKEN"))