discord.py-rewrite - 为什么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)
[]
解决方案
从粗略的检查来看,您的问题似乎是您只调用了一次。您的方法 my_background_task
不是每三秒调用一次。相反,您的send_message
方法每三秒调用一次。对于预期的行为,将 print 语句放在您的 while 循环中。
推荐阅读
- javascript - 如何为网络图自定义颜色?
- sql - 列出系列中两个表之间的不同变体
- java - 每当我先输入更大的数字时,它都不会打印出任何东西
- c# - 在 C# 中,使用脚本将命令添加到 PowerShell InitialSessionState 并使其可从 C# 中发现
- python - 为什么这个结果比等效函数的另一个结果更准确
- html - 图像上的空白过多
- python - 检查数据框的值是否存在于另一个中,并以特定方式设置值以考虑重复项
- port - Mosquitto - 无法通过默认端口以外的网络连接
- r - 使用 R 将行写入 CSV
- php - 如何更改通过电子邮件发送的重置密码 VIEW?