0

I have created a twitter monitor in python, I want to implement it with a discord bot so that users to monitor can be added from discord through commands.

The operation is as follows:

from discord put, .addUser(@diego) and that it gets into the notepad from which the monitor extracts the users that new one entered, for this I need to stop the monitor task and start it again so that the monitor is updated and catch the new user. The thing is that I don't know how to cancel the task and restart it, also say that the monitor uses several threads, one for each user, the mission would be to restart the entire program with all its threads.


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)

  • Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – TheFungusAmongUs Aug 29 '22 at 15:40

1 Answers1

0

You can use a discord task in order to accomplish this:

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_")
Tony
  • 266
  • 1
  • 11
  • @task.loop(60), I dont want that loop every 60s, only restart when I add an user, other thing is that the code give me the error:```AttributeError: 'Bot' object has no attribute 'monitoring'``` – Chupitastiiks Sep 05 '22 at 20:21