启动任务,然后重新启动Python,discordbot



我在python中创建了一个twitter监视器,我想用discord bot来实现它,这样就可以通过命令从discord添加要监视的用户。

操作如下:

从discordput,.addUser(@diego(,它进入记事本,监视器从中提取新用户输入的用户,为此,我需要停止监视器任务并重新启动它,以便更新监视器并捕获新用户。问题是,我不知道如何取消任务并重新启动它,还说监视器使用几个线程,每个用户一个,任务是用所有线程重新启动整个程序。


bot = commands.Bot(command_prefix='.')
async def monitoring():
monitorTwitterHilos.main()

@bot.event
async def on_ready(): #Enciende el bot
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
#taskMonitoring=bot.loop.create_task(monitoring()) 
#taskMonitoring.cancel
#taskM=bot.loop.create_task(monitoring())
#monitoring.start()
task1 = asyncio.create_task(monitoring())
print('------------ TASK RUNNING ------------')

@bot.command()
async def addUser(message, user):


task1.cancel() #not working
with open("usuarios.txt", 'a') as f:
f.write(str(user)+"n") 

#monitoring.restart

task1.start()  #not working

await message.send("_Usuario: **"+ str(user)+"** añadido con exito_")

bot.run(TOKEN)

您可以使用不协调任务来完成此任务:

from discord.ext import tasks
@tasks.loop(60) #Add this decorator to declare that it is a task
async def monitoring():
monitorTwitterHilos.main()
@bot.event
async def on_ready(): #Enciende el bot
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
#taskMonitoring=bot.loop.create_task(monitoring()) 
#taskMonitoring.cancel
#taskM=bot.loop.create_task(monitoring())
#monitoring.start()
bot.monitoring().start() #Change this line
print('------------ TASK RUNNING ------------')
@bot.command()
async def addUser(message, user):
with open("usuarios.txt", 'a') as f:
f.write(str(user)+"n") 

bot.monitoring().restart() 

await message.send("_Usuario: **"+ str(user)+"** añadido con exito_")

最新更新