如何在discord.py中循环任务

sha*_*312 5 python-3.x twitch discord twitch-api

我正在尝试制作我自己的小不和谐机器人,它可以从 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>")
Run Code Online (Sandbox Code Playgroud)

我希望机器人每 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
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗?

小智 8

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

为了达到同样的目的,我使用了以下代码段

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


myLoop.start()

client.run('<your token>')
Run Code Online (Sandbox Code Playgroud)

  • 对于 myLoop.start() 行,我收到错误:`RuntimeError:没有正在运行的事件循环``sys:1:RuntimeWarning:从未等待协程'Loop._loop'` (5认同)
  • @Brendon这是因为所有等待都需要在异步函数内发生。将“myLoop.start()”放入异步“on_ready”函数中,它就会起作用。 (2认同)

小智 6

这是实现后台任务的最正确的方式。

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
Run Code Online (Sandbox Code Playgroud)

检查以获取更多信息


Dig*_*gy. 5

这可以像这样完成:

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))
Run Code Online (Sandbox Code Playgroud)

参考: