0

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

5
  • Try not caling loop.close Commented Mar 20, 2020 at 22:21
  • @JoshuaNixon didn't mention it, but i tried that too. the error is the same as the latter. Commented Mar 20, 2020 at 22:54
  • For scheduling stuff in asyncio I used phoolish-philomath.com/… as a starting point Commented Mar 20, 2020 at 22:59
  • @JoshuaNixon I cannot follow the same pattern because things are slightly different, though no result. Commented Mar 21, 2020 at 9:38
  • 1
    See here: stackoverflow.com/questions/54495679/… Commented Mar 21, 2020 at 9:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.