简体   繁体   中英

run a function concurrently with client.run() in discord

so i have a discord bot and also another function that i want to run, but i want them to run concurrently but i couldn't make them run without one of them blocking the other, here's an example code ps: disnake is a fork of dicord.py so it works the same mostly

import disnake
import time

bot = commands.Bot()

async on_message(message):
    if message.content == "hello bot":
        await message.channel.send("hey user")

x=0
def counting():
   while True:
      x += 1 
      print(x)
      time.sleep(1)

#here is the issue mostly
bot.run(token)
counting()

i want the bot to run normally, while the other function is running and counting "1" "2" on my terminal, but i can't get to make them both work

Disnake is an async-await library, which means that you should use non-blocking functions. Moreover, the fonctions you want to make concurrent should be async and contain await suspension points in order to let other concurrent routines an opportunity to execute.

The issue is that the documentation mentions explicitly that Bot.run() is a blocking call. Moreover your counting() function is not async and does not contain any await . Thus, the two functions cannot run concurrently. Also, you should not use time.sleep() with AsyncIO as it is a blocking operation, you should use asyncio.sleep() .

You should use something like this:

import asyncio
import disnake

async on_message(message):
    if message.content == "hello bot":
        await message.channel.send("hey user")

async def count():
  count = 0
  while True:
    await asyncio.sleep(1.0)
    count += 1
    print(count)

async def main():
  bot = commands.Bot()
   
  await asyncio.gather(
    count(),
    bot.start()
  )
 
  await bot.close()

if __name__ == "__main__":
    asyncio.run(main())

If you want to support Ctrl+C cancellation cleanly then have at the Bot.start() API reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM