如何使用Discord.py循环功能 [英] How to loop a function using Discord.py
本文介绍了如何使用Discord.py循环功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目标是切换在嵌齿轮内部调用函数时的循环。我希望函数采用文件名的参数。该函数将打印从txt文件读取的行。我希望这个循环直到我调用另一个取消它的函数为止。
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使用异步,我只是不知道如何在一个函数内操作循环。
Discord py uses async, I just do not know how to operate a loop within a function.
示例:
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
推荐答案
您可以使用任务,由discord.py API提供。
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))
由于我目前无法进行测试,因此上面可能存在一些错误,但是循环很麻烦就是这样。
这篇关于如何使用Discord.py循环功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文