【问题标题】:How to loop a function using Discord.py如何使用 Discord.py 循环函数
【发布时间】:2020-08-07 04:27:57
【问题描述】:

我的目标是在 cog 内部调用函数时“切换”一个循环。我希望该函数采用文件名的参数。该函数将打印它从 txt 文件中读取的行。我希望它循环,直到我调用另一个取消它的函数。

Discord py 使用异步,我只是不知道如何在函数内操作循环。

示例:

class Looptest:

   def __init__(self, client):

        self.client = client

    #This is responsible for playing the loop.
   async def play_loop(self, filename):

        filename = (path_to_txtfile)
        
        #loop the following code
        with open(filename, 'r') as f:
            line = f.readlines()
             print(line)

async def stop_loop(self):
    #stop the loop
    

【问题讨论】:

    标签: python python-3.x discord.py


    【解决方案1】:

    您可以使用由 discord.py API 提供的task。

    from discord.ext import commands, tasks
    
    class LoopCog(commands.Cog):
        def __init__(self, bot):
            self.bot = bot
            # whatever else you want to do
    
        @tasks.loop(seconds=1)
        async def test_loop(self, filename):
            # do your file thingy here
    
        @commands.command(name="start_loop"):
        async def start_loop(self,*, filename: str):
            # check that the file exists
            self.test_loop.start(filename)
        @commands.command(name="stop_loop"):
        async def stop_loop(self):
            self.test_loop()
    
    def setup(bot):
        bot.add_cog(LoopCog(bot))
    

    我没有测试它,因为我现在不能,上面可能有一些错误,但循环是这样工作的。

    【讨论】:

    • 您好,感谢您的帮助。你让我走上了正确的道路,但仍然遇到了麻烦。循环启动,但打印不执行。有机会可以帮我试试吗?
    猜你喜欢
    • 1970-01-01
    • 2021-08-05
    • 2019-01-12
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2020-09-07
    • 2023-01-26
    • 2021-04-20
    相关资源
    最近更新 更多