0

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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey, thanks for your help. You put me on the right path, still having trouble though. The loop initiates but the print doesn't execute. Would you be able to try for me when you get a chance?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.