【问题标题】:sending a message in a loop only once discord.py只在循环中发送一条消息 discord.py
【发布时间】:2019-04-14 08:31:27
【问题描述】:

正如标题所示,我正在尝试在 while 循环内发送一条消息(仅一次)。这是到目前为止的代码:

while hour >= 11 and hour < 12:
   msg = await bot.wait_for_message(timeout=1, author=message.author)
   if msg:
      pass
   hour = int(time.strftime("%H"))
   minute = int(time.strftime("%M"))
   if hour == 11 and minute == 22:
      await bot.send_message(message.channel, "<@258621320898543616> you have 5 min of break left. Finish up whatever your doing quickly tatsu san!")

代码现在在 11:22 时多次发送消息。我尝试将 if 语句放在循环之外,但它根本没有发送消息。我还尝试将asyncio.sleep(60) 放在 if 语句中,但这也不起作用。不知道如何解决这个问题。请帮忙?

【问题讨论】:

  • 你试过用 time.sleep() 代替 asyncio.sleep() 吗?但这会在睡眠期间停止整个 while 循环的执行。
  • 我当时就这样做了。以为它工作了一秒钟,但它只是停止了整个程序的运行。换句话说,它会在我在 time.sleep() 中输入的指定时间结束后关闭机器人

标签: python bots discord.py


【解决方案1】:

经过一番研究,我找到了一种方法。我创建了一个名为“秒”的变量,它存储(显然)秒。这是我的新代码:

while hour >= 11 and hour < 12:
   msg = await bot.wait_for_message(timeout=1, author=message.author)
   if msg:
      pass
   hour = int(time.strftime("%H"))
   minute = int(time.strftime("%M"))
   seconds = int(time.strftime("%S"))
   if hour == 11 and minute == 22 and seconds == 0:
      await bot.send_message(message.channel, "<@258621320898543616> you have 5 min of break left. Finish up whatever your doing quickly tatsu san!")

这成功了。该语句也只发送一次

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-01
    • 2021-04-04
    • 1970-01-01
    • 2021-07-08
    • 2021-06-08
    • 2020-04-21
    • 2021-10-15
    • 1970-01-01
    相关资源
    最近更新 更多