首页 > 解决方案 > 为什么discord.py-rewrite bot.loop.create_task(my_background_task()) 执行一次但不重复

问题描述

使用 Discord.py-rewrite,我们如何诊断my_background_task以找到其打印语句不是每 3 秒打印一次的原因?

详细信息: 我观察到的问题是“ print('inside loop')”在我的日志中打印一次,而不是预期的“每三秒”打印一次。会不会有一个我没有发现的异常?

注意:我确实print(f'Logged in as {bot.user.name} - {bot.user.id}')在日志中看到所以on_ready似乎有效,所以不能怪这种方法。

我尝试遵循以下示例:https ://github.com/Rapptz/discord.py/blob/async/examples/background_task.py 但是我没有使用它的client = discord.Client()声明,因为我认为我可以使用类似于如此处所述https://stackoverflow.com/a/53136140/6200445

import asyncio
import discord
from discord.ext import commands

token = open("token.txt", "r").read()


def get_prefix(client, message):

    prefixes = ['=', '==']    

    if not message.guild:
        prefixes = ['==']   # Only allow '==' as a prefix when in DMs, this is optional

    # Allow users to @mention the bot instead of using a prefix when using a command. Also optional
    # Do `return prefixes` if u don't want to allow mentions instead of prefix.
    return commands.when_mentioned_or(*prefixes)(client, message)


bot = commands.Bot(                         # Create a new bot
    command_prefix=get_prefix,              # Set the prefix
    description='A bot for doing cool things. Commands list:',  # description for the bot
    case_insensitive=True                   # Make the commands case insensitive
)

# case_insensitive=True is used as the commands are case sensitive by default

cogs = ['cogs.basic','cogs.embed']


@bot.event
async def on_ready():                                       # Do this when the bot is logged in
    print(f'Logged in as {bot.user.name} - {bot.user.id}')  # Print the name and ID of the bot logged in.
    for cog in cogs:
        bot.load_extension(cog)
    return


async def my_background_task():
    await bot.wait_until_ready()
    print('inside loop') # This prints one time. How to make it print every 3 seconds?
    counter = 0
    while not bot.is_closed:
        counter += 1
        await bot.send_message(channel, counter)
        await channel.send(counter)
        await asyncio.sleep(3) # task runs every 3 seconds

bot.loop.create_task(my_background_task())
bot.run(token)
[]

标签: discord.py-rewrite

解决方案


从粗略的检查来看,您的问题似乎是您调用了一次。您的方法 my_background_task不是每三秒调用一次。相反,您的send_message方法每三秒调用一次。对于预期的行为,将 print 语句放在您的 while 循环中。


推荐阅读