【问题标题】:Receiving a runtime error at client.run('token') when running my discord.py bot运行我的 discord.py 机器人时在 client.run('token') 收到运行时错误
【发布时间】:2020-05-10 07:19:47
【问题描述】:

我正在尝试用 Python 制作一个 Discord 机器人,它根据您所在的班级(在我的学校)为您提供 Discord 服务器上的角色。我刚刚开始,但每当我尝试运行它时都会收到错误消息(我在 Python 3 Notebook 中的 Google Colab 中运行它)。这是我的代码:

from datetime import date
import time
import discord

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

client.run('my token (not shown for obvious reasons)')

starttime=time.time()
while True:
  currentTime = time.strftime("%H:%M")
  print("new minute")
  if 0 <= date(int(time.strftime("%Y")), int(time.strftime("%m")), int(time.strftime("%d"))).weekday() <= 4:
    if currentTime == "13:41":
      print("First hour has started!")
    elif currentTime == "13:45":
      print("First hour has started! (hs)")
    elif currentTime == "14:30":
      print("First hour has ended at high school.")
  time.sleep(60.0 - ((time.time() - starttime) % 60.0))

当我运行它时,它会提示我这个错误:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-5-d40f2b4200ae> in <module>()
      9     print('We have logged in as {0.user}'.format(client))
     10 
---> 11 client.run('my token')
     12 
     13 starttime=time.time()

2 frames
/usr/local/lib/python3.6/dist-packages/discord/client.py in run(self, *args, **kwargs)
    570 
    571         try:
--> 572             loop.add_signal_handler(signal.SIGINT, lambda: loop.stop())
    573             loop.add_signal_handler(signal.SIGTERM, lambda: loop.stop())
    574         except NotImplementedError:

/usr/lib/python3.6/asyncio/unix_events.py in add_signal_handler(self, sig, callback, *args)
     92                             "with add_signal_handler()")
     93         self._check_signal(sig)
---> 94         self._check_closed()
     95         try:
     96             # set_wakeup_fd() raises ValueError if this is not the

/usr/lib/python3.6/asyncio/base_events.py in _check_closed(self)
    375     def _check_closed(self):
    376         if self._closed:
--> 377             raise RuntimeError('Event loop is closed')
    378 
    379     def _asyncgen_finalizer_hook(self, agen):

RuntimeError: Event loop is closed

如果我将client.run 命令放在底部,程序永远不会到达它,因为循环会阻止它到达命令。

我错过了什么吗?我不知道问题出在哪里。非常感谢帮助。

【问题讨论】:

    标签: python google-colaboratory discord.py


    【解决方案1】:

    Jupyter 笔记本是 Google Colab 所基于和使用的,有自己的事件循环。
    Client.run 使用当前事件循环(如果未指定),并在完成运行后关闭它。
    您应该能够在事件循环关闭之前运行它一次,并且连续尝试再次运行它会告诉您同样多的信息。如果您想在同一个笔记本中多次运行它,您需要使用 Client.start 并自己处理事件循环。

    【讨论】:

    • 当我启动机器人 /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:11: RuntimeWarning: coroutine 'Client.start' was never awaited # This is added back by InteractiveShellApp.init_path() 并且机器人不响应不和谐的命令时,使用客户端运行会返回此内容,但循环开始进行。
    • 据记载,Client.start 是一个协程。您需要使用事件循环来运行它。
    【解决方案2】:

    基本上,如果您想在 google colab 上运行不和谐机器人,则需要执行各种 hack。这里我使用 discord.ext python 库,执行这个,但是会阻塞,并阻止你执行任何其他单元格。

    !pip install discord.py
    import nest_asyncio
    nest_asyncio.apply()
     
    import asyncio
    await = lambda x: asyncio.get_event_loop().run_until_complete(x)
    async def init(what, token):
        await what(token)
    import discord
    from discord.ext import commands
    bot = commands.Bot(command_prefix="")
    async def start():
        await bot.wait_until_ready()
        print("ready")
        await bot.get_channel(channelID).send("hi")
    
    bot.loop.create_task(start())
    
    TOKEN = ""   #@param {type: "string"}
    
    

    【讨论】:

      猜你喜欢
      • 2022-12-08
      • 1970-01-01
      • 2018-05-11
      • 2022-06-13
      • 2021-05-24
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      相关资源
      最近更新 更多