How to loop a function using Discord.py

不打扰是莪最后的温柔 提交于 2020-08-10 20:13:24

问题


My goal is to "toggle" a loop when a function is called inside of a cog. I want the function to take the argument of a filename. The function will print the line it has read from a txt file. I want this to loop until I call another function that cancels it.

Discord py uses async, I just do not know how to operate a loop within a function.

Example:

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
    

回答1:


You can use a task, provided by the discord.py API.

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

I didn't test it as I cannot right now, there might be some errors above, but the loop thingy works that way.



来源:https://stackoverflow.com/questions/63295211/how-to-loop-a-function-using-discord-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!