使用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)
[]
答案 0 :(得分:2)
从粗略的检查来看,似乎您的问题是您只是调用了一次。您的方法 my_background_task
不会每三秒钟调用一次。每三秒钟调用一次send_message
方法。对于预期的行为,请将print语句放入while循环内。
答案 1 :(得分:0)