问题
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