【问题标题】:discord py while loop breaks with no reasondiscord py while循环无故中断
【发布时间】:2021-04-30 11:55:04
【问题描述】:

我制作了一个不和谐的机器人,它应该每天 22:00 UTC 时间从文本文件中发送报价。虽然它确实工作了一次,但似乎第一天之后 while 循环就中断了。

import discord
import random
import datetime

client = discord.Client()
text_channel = None

@client.event
async def on_message(message):

    global text channel

    if message.author == client.user:
        return

    cntnt = message.content

    if cntnt == '!add_channel':
        text_channel = message.channel
        print("Assigned ", text_channel, " as channel.")        
        await message.delete()

    if cntnt == '!start_quote':
        if text_channel != None:
            await message.delete()
            while True:
                current_time = datetime.datetime.now()
                print(current_time)
                await asyncio.sleep(1)
                time1 = current_time.hour
                time2 = current_time.minute
                if time1 == 22 and time2 == 0:
                    with open('quotes.txt', 'r', encoding='utf8') as file:
                        quotes = file.readlines()
                    index = random.randint(0, len(quotes))
                    answer = str(quotes[index + 1])
                    await text_channel.send("Today's quote: " + answer)
                    await asyncio.sleep(60)
        else:
            print("No channel assigned.")
            await message.delete()


client.run("TOKEN")

【问题讨论】:

  • 修复代码的缩进。照原样给出语法错误。
  • 我怀疑机器人应该在 on_message() 中这么久。
  • 我认为是这样的,因为一切都指向message.content 或一般message。但似乎代码的某些部分丢失了,例如 cntnt 从未声明过。 @ThomasWeller
  • 这是我复制粘贴时犯的一个错误,我现在修复了它

标签: python python-3.x discord discord.py


【解决方案1】:

while 循环可能实际上并未中断,但您的机器人正在超载。您将这个无限期运行的 while 循环放在 on_message 处理程序中。这意味着每次有人发送消息时都会开始一个新循环。

一个更好的方法是使用discord.ext.tasks。这是一个例子:

from discord.ext import tasks

@tasks.loop(hours=24)
async def send_quote():
   # send the quote here, no while loop needed

send_quote.start()  # don't forget, you always have to call the start() method

[编辑] 如果您需要在每天的某个时间发送消息,那么您可以这样做:

import datetime

last_send = None
send_at = datetime.time(hours=12)  # send at the twelf hour every day

# wait at least 2 hours before allowing a second quote.
# this prevents sending twice at the same time.
min_difference = datetime.timedelta(hours=2)

@tasks.loop(minutes=1)
async def send_quote():
   # First, check if the time is right.
   now = datetime.datetime.now()

   # check that it's been at least 10 minutes since the last send
   # to prevent sending twice at the same time.
   if last_send is None or (now - last_send < min_difference):
       # this will check if the hour is correct
       if send_at.hour - now.hour == 0:
           # send the quote here
           last_send = now  # update last_send

我无法对此进行测试,所以我不能保证它会立即工作。

【讨论】:

  • 我试过这个,但这样我就必须在 22:00 UTC 时间启动机器人,这对我来说是凌晨 3 点,对吧?因为它只是每 24 小时执行一次任务,而不是在某个时间。或者我可以让@tasks.loop(minutes=1) 每 1 分钟检查一次是否是 22:00?
  • 谢谢这个工作,但我认为它是send_at.hour - now.hour == 0
【解决方案2】:

我建议的第一件事不是使用if cntnt,而是移至discord.ext 包。

例子:

@bot.command()
async def test(ctx):
    await ctx.send("Hello")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-31
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2017-11-14
    • 2019-05-05
    • 2021-10-28
    • 1970-01-01
    相关资源
    最近更新 更多