I am building a Discord bot and most of it is event based. Once the bot is ready, I want to have a thread that, while the bot is alive, sometimes writes "hi" in chat and then sleeps for 2 minutes. Code:
async def on_ready(self):
t = threading.Thread(target=self.say_hi)
t.start()
async def say_hi(self):
while True:
chance = random.randint(0, 101)
if chance <= 25:
await self.channel.send('hi')
time.sleep(60 * 2)
Problem is that I get different errors. RuntimeWarning: Enable tracemalloc to get the object allocation traceback
in this case. I tried following this somewhat related answer editing the code in this way:
def say_hi(self):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self.say_hi_aux())
loop.close()
async def say_hi_aux(self):
while True:
chance = random.randint(0, 101)
if chance <= 25:
await self.channel.send('hi')
await asyncio.sleep(60 * 2)
But the resulting error is RuntimeError: Timeout context manager should be used inside a task
on loop.run_until_complete()
method.
I don't know what's wrong with either solution