首页 > 解决方案 > 如何在 tasks.loop discord.py bot 中运行命令

问题描述

所以我试图让一个命令在我的 dsicrod.py 机器人上每 5 分钟运行一次,并且需要 ctx 来获取公会成员和某些类似的细节,所以我需要在 bot.command 中使用它,但我不能在没有任务的情况下正确地做到这一点.loop(minutes=5) 所以我试着让它用 tasks.loop 发送命令但它不起作用所以我去了 pythin discord 并得到帮助他们让我到了这一点

@bot.command(pass_context=True)
async def update_member_count(ctx): 
    await ctx.send(ctx.guild.member_count)
    channel = discord.utils.get(ctx.guild.channels, id=829355122122424330)
    await channel.edit(name = f'Member Count: {ctx.guild.member_count}')


@tasks.loop(minutes=5)
async def update_member_count2(ctx):
    await update_member_count(ctx)

并且它仍然给出错误,说 update_member_count2 中缺少 ctx arg。请帮忙

标签: pythondiscorddiscord.py

解决方案


您可以通过另一种方式创建您的loop-function。你的方法对我来说有点不清楚。

尝试以下方法:

async def update_member_count(ctx):
    while True:
        await ctx.send(ctx.guild.member_count)
        channel = discord.utils.get(ctx.guild.channels, id=YourID)
        await channel.edit(name=f'Member Count: {ctx.guild.member_count}')
        await asyncio.sleep(TimeInSeconds)


@bot.command()
async def updatem(ctx):
    bot.loop.create_task(update_member_count(ctx))  # Create loop/task
    await ctx.send("Loop started, changed member count.") # Optional

(或者你只是在你的on_ready事件中创建任务,取决于你)

我们做了什么?

  • 从函数中创建了一个循环 ( async def update_member_count(ctx):)
  • 执行updatem一次以激活循环
  • 将您的实际命令更改为“函数”

推荐阅读