英文:
How can I close a discord client connection without exception
问题
让我们假设我有一个简单的discord.Client
代码:
import os
import discord
from dotenv import load_dotenv
load_dotenv()
intents = discord.Intents.default()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client(intents=intents)
@client.event
async def on_ready():
guild = None
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to guild {guild.name} (id: {guild.id})'
)
client.run(TOKEN)
所以,当我停止代码时,我会得到这个异常:
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self close()
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Process finished with exit code 0
这不会以任何方式影响代码和功能,但看到它非常令人讨厌。
那么,我应该如何正确断开/关闭连接?
英文:
Let's say I have a simple discord.Client
code:
import os
import discord
from dotenv import load_dotenv
load_dotenv()
intents = discord.Intents.default()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client(intents=intents)
@client.event
async def on_ready():
guild = None
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to guild {guild.name} (id: {guild.id})'
)
client.run(TOKEN)
So, when I stop the code, I get this exception:
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Process finished with exit code 0
It does not affect the code and functionality in any way, but it is very annoying to see.
How would I disconnect/close connection properly then?
答案1
得分: 0
@client.event
async def close():
print(f"{client.user} disconnected")
英文:
So, after a bit of searching, I found that the
@client.event
async def close():
print(f"{client.user} disconnected")
works just fine.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论