【发布时间】:2021-01-12 20:02:00
【问题描述】:
我正在尝试运行我的 discord 机器人,从中运行 exit() 或 logout(),运行一些其他 python 代码,然后重新登录。我没有使用异步函数的经验,所以我不知道错误消息是什么意思。
import discord
dToken = "xxxxx"
client = discord.Client()
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
guilds = client.guilds
for i in range(len(guilds)):
if str(guilds[i]) == server:
gld = guilds[i]
for channel in gld.text_channels:
if str(channel) == "channelname":
print(str(message)+" sent to channel id "+str(channel.id))
await client.get_channel(channel.id).send(message)
await client.logout()
#run bot
client.run(dToken)
#change message and server name depending on extra code I put here
message = "hello!"
server = "servername"
#run bot again with changes
client.run(dToken)
我必须 logout() 因为这是我发现可以使额外代码运行的唯一方法。但是我的代码给出了以下错误:
Traceback (most recent call last):
File "C:/Users/mmh/PycharmProjects/pythonProject/test.py", line 21, in <module>
client.run(dToken)
File "C:\Users\mmh\PycharmProjects\pythonProject\venv\lib\site-packages\discord\client.py", line 665, in run
future = asyncio.ensure_future(runner(), loop=loop)
File "C:\Users\mmh\AppData\Local\Programs\Python\Python37\lib\asyncio\tasks.py", line 608, in ensure_future
task = loop.create_task(coro_or_future)
File "C:\Users\mmh\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 402, in create_task
self._check_closed()
File "C:\Users\mmh\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 479, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
sys:1: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited
Process finished with exit code 1
有人知道我应该做什么吗?
【问题讨论】:
-
await client.run(dToken)? -
@JacobIRR "await" 仅在 def on_ready() 函数内有效
标签: python discord bots python-asyncio