0

I have defined a function which is set to send a message to a Discord channel every hour. This would be run alongside your typical on_message() commands, so I thought of putting the reccuring function inside a thread using threading.

I tried to async/await the thread as you do, but it didn't work. How do I make it possible so I could have a message repeat every hour along with typical commands?

My code is as follows

async def reccur_func():
    while 1:
        await reccurship()
        time.sleep(30)

client = discord.Client()

threading.Thread(target = reccur_func).start()   #I tried putting await and async at the beginning of this line

@client.event
async def on_message(ctx):

    ......

client.run('....')

Thank you all

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
Ben
  • 89
  • 8
  • as a trivial note, 'recurrence' might be the word you were looking for :p (and 'recur' only has one C) – Personman Dec 19 '19 at 18:19
  • 1
    What is the coroutine `reccurship` that you are waiting on? Also, `reccur_func()` doesn't look like it does anything. It simply waits for another routine and then sleeps. – Aroic Dec 19 '19 at 18:22
  • @Personman thank you very much. My spelling/grammar is the best :) – Ben Dec 19 '19 at 21:29

3 Answers3

0

It seems like you might be mixing up AsyncIO with threading.

If you want to use AsyncIO, you will need to add a task for reccur_func() to the event loop. This other question will provide some more details.

If you want to use threading, remove the await from reccur_func():

def reccur_func():
    while 1:
        # Do something
        time.sleep(30)

You can find some more info about threading in this question.

  • The problem is I need to use await as otherwise I am not able to send a message with discord. – Ben Dec 19 '19 at 21:42
0

Not really an answer to the exact question but it worked in my case.

In discord I used client.loop.create_task(reccur_func()) and it executed that funcion (Which repeat itself) while continuing to run everything else.

Ben
  • 89
  • 8
0

The way to do this is to use the discord.ext.tasks extension to turn reccurship into a task

from discord.ext import tasks, commands

bot = commands.Bot("!")

@bot.event
async def on_message(message):
    ...

@tasks.loop(hours=1)
async def reccurship():
    ...

@reccurship.before_loop
async def before_reccurship():
    await bot.wait_until_ready()

recurrship.start()

bot.run("token")
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • I used a different method but it was practically the same as your one. I used `client.loop.create_task(reccur_func())`. – Ben Dec 22 '19 at 21:31