0

我的机器人中有提醒功能。它每 10 秒检查一次提醒是否现在,如果是,它会发送一条消息。

async def reminder():
    global reminderDone
    if datetime.now().replace(second = 0, microsecond=0) == datetime(2021, 1, 29, 19) and not reminderDone:
        reminderDone = True
        cnl = bot.get_channel([channel id goes here])
        await cnl.send("@everyone Reminder time")
    await asyncio.sleep(10)
    await reminder()

它首先用await reminder()in调用on_ready()。大约 3 小时后,我收到此错误:

File "/app/.heroku/python/lib/python3.6/site-packages/discord/client.py", line 333, in _run_event
  await coro(*args, **kwargs)
File "bot.py", line 21, in on_ready
  await reminder()
File "bot.py", line 36, in reminder
  await reminder()
File "bot.py", line 36, in reminder
  await reminder()
File "bot.py", line 36, in reminder
  await reminder()
[Previous line repeated 976 more times]
File "bot.py", line 35, in reminder
  await asyncio.sleep(10)
File "/app/.heroku/python/lib/python3.6/asyncio/tasks.py", line 480, in sleep
  future, result)
File "/app/.heroku/python/lib/python3.6/asyncio/base_events.py", line 564, in call_later
  timer = self.call_at(self.time() + delay, callback, *args)
File "/app/.heroku/python/lib/python3.6/asyncio/base_events.py", line 578, in call_at
  timer = events.TimerHandle(when, callback, args, self)
File "/app/.heroku/python/lib/python3.6/asyncio/events.py", line 167, in __init__
  super().__init__(callback, args, loop)
File "/app/.heroku/python/lib/python3.6/asyncio/events.py", line 110, in __init__
  if self._loop.get_debug():
RecursionError: maximum recursion depth exceeded

我认为这是因为函数调用自身而引起的,但是因为它正在使用await它等待函数停止执行,它永远不会因为它一直在调用自身。我不能只删除await它,因为我需要它来发送await cnl.send()作为协程的消息()。如何在不出现递归错误的情况下永久运行循环以检查提醒?

4

3 回答 3

2

如果您无限循环,那么您需要一个while循环:

async def reminder():
    while True:
        global reminderDone
        if datetime.now().replace(second = 0, microsecond=0) == datetime(2021, 1, 29, 19) and not reminderDone:
            reminderDone = True
            cnl = bot.get_channel([channel id goes here])
            await cnl.send("@everyone Reminder time")
        await asyncio.sleep(10)
于 2021-01-29T19:40:55.790 回答
1

您可以简单地创建一个循环,而不是一次又一次地调用相同的函数......

from discord.ext import tasks

@tasks.loop(seconds=10)
async def reminder():
    global reminderDone
    if datetime.now().replace(second = 0, microsecond=0) == datetime(2021, 1, 29, 19) and not reminderDone:
        reminderDone = True
        cnl = bot.get_channel([channel id goes here])
        await cnl.send("@everyone Reminder time")


reminder.start()

参考:

于 2021-01-29T19:47:20.693 回答
0

编辑 2:不要使用我的答案,使用 quamrana 一个,它简单并修复您的代码。

很简单,你reminder从自身调用函数,(递归)但没有停止,然后,为了防止解释器无限重复,当你调用函数太多时,Python 会抛出这个错误。

解决这个问题

只需在if您的代码中添加一个,例如:

if foo==True:
   reminder()

编辑:不要使用stop()!它只是停止循环

于 2021-01-29T19:27:46.583 回答