如何在 discord.py 中循环执行任务

How to loop a task in discord.py

我正在尝试制作我自己的小 discord 机器人,它可以从 Twitch 获取信息,但我对如何使机器人循环并检查条件感到困惑。

我希望机器人每隔几秒循环一段代码,检查指定的 twitch 频道是否在线。


代码

import discord
from discord.ext import commands, tasks
from twitch import TwitchClient
from pprint import pformat


client = TwitchClient(client_id='<twitch token>')

bot = commands.Bot(command_prefix='$')

@bot.event
async def on_ready():
    print('We have logged in as {0.user}'.format(bot))

@bot.command()
async def info(ctx, username):
    response = await ctx.send("Querying twitch database...")
    try:
        users = client.users.translate_usernames_to_ids(username)
        for user in users:
            print(user.id)
            userid = user.id
        twitchinfo = client.users.get_by_id(userid)
        status = client.streams.get_stream_by_user(userid)
        if status == None:
            print("Not live")
            livestat = twitchinfo.display_name + "is not live"
        else:
            livestat = twitchinfo.display_name + " is " + status.stream_type
        responsemsg = pformat(twitchinfo) + "\n" + livestat
        await response.edit(content=responsemsg)
    except:
        await response.edit(content="Invalid username")

bot.run("<discord token>")

我希望机器人每 10 秒 运行 以下代码,例如:

status = client.streams.get_stream_by_user(<channel id>)
if status == None:
     print("Not live")
     livestat = twitchinfo.display_name + "is not live"
else:
     livestat = twitchinfo.display_name + " is " + status.stream_type

我试过使用 @tasks.loop(seconds=10) 来尝试自定义 async def 每 10 秒重复一次,但它似乎没有用。

有什么想法吗?

可以这样做:

async def my_task(ctx, username):
    while True:
        # do something
        await asyncio.sleep(10)

@client.command()
async def info(ctx, username):
    client.loop.create_task(my_task(ctx, username))

参考文献:

较新版本的 discord.py 不支持 client.command()

为了实现同样的效果,我使用了以下代码片段

import discord
from discord.ext import tasks
client = discord.Client()
@tasks.loop(seconds = 10) # repeat after every 10 seconds
async def myLoop():
    # work


myLoop.start()

client.run('<your token>')

这是执行后台任务最合适的方法。

from discord.ext import commands, tasks

bot = commands.Bot(...)

@bot.listen()
async def on_ready():
    task_loop.start() # important to start the loop

@tasks.loop(seconds=10)
async def task_loop():
    ... # this code will be executed every 10 seconds after the bot is ready

查看this了解更多信息