【问题标题】:How to loop a task in discord.py如何在 discord.py 中循环任务
【发布时间】:2020-09-07 06:14:24
【问题描述】:

我正在尝试制作我自己的可以从 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 秒重复一次,但它似乎不起作用。

有什么想法吗?

【问题讨论】:

    标签: python-3.x discord twitch twitch-api


    【解决方案1】:

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

    为了达到同样的效果,我使用了以下 sn-p

    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>')
    

    【讨论】:

      【解决方案2】:

      可以这样做:

      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))
      

      参考资料:

      【讨论】:

      • 我将如何打破这个循环?
      • loop.stop() 可以解决问题。
      猜你喜欢
      • 2021-03-19
      • 2023-03-22
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多