D.sLyak
D.sLyak

Reputation: 13

How do I run multiple functions at a time in discord.py?

In my bot, I have a function that consistently adds to values in a dictionary once a second to represent "paying employees". I also have a @client.command function that shows the keys and values of the dictionary at the time that the command was sent. While the "paying" function is on though (always), the look-up function doesn't work, the on_message function does. How do I make it so the bot will detect @client.command function in parallel?

import discord
from discord.ext import commands
from discord.ext import tasks
import asyncio

client = commands.Bot(command_prefix='/')

payroll = []
data = {}


# /start will start operations and manage payroll for everyone on the server
# will make it on_ready
@client.event
async def on_ready():
    global data
    server = client.get_guild(670006903815929889)
    # starts balance for everyone on the server at the time of the command and adds them to the payroll
    for person in server.members:
        person = str(person)
        payroll.append(person)
        data[person] = int(0)
    print(data)

    await asyncio.sleep(1)

    # pays everyone at a steady BASE rate
    while True:
        for person in payroll:
            data[person] += 10
        print(data)
        await asyncio.sleep(60)


# on message
@client.event
async def on_message(ctx):
    global data
    balance = int(data[str(ctx.author)])
    data[str(ctx.author)] -= 5

    if balance <= 25 and ctx.author.id != 734119994761150585:
        await ctx.channel.send('Be careful {author}! Your balance is ${balance}.')

    if balance <= 0 and ctx.author.id != 734119994761150585:
        # delete message
        await ctx.channel.send('Oops! {author}, you have run out of money. As a consequence, you will be deducted $15.')
        data[str(ctx.author)] -= 15

    if message.startswith("/dm"):
        await message.author.send('Hello World!')

# look-up stats
@client.command()
async def dm(message):
    await message.author.send('stats go here')


client.run("token")

Upvotes: 0

Views: 3760

Answers (1)

Karan
Karan

Reputation: 498

The command function will not work as you are not processing the command. To do that, add the small line in your message function:

@client.event()
async def on_message(message):
    #YOUR CODE HERE
    await client.process_commands(message)

For running the function constantly or running multiple at a time: You can add the tasks in the function which will run constantly or at the given time difference. The in-depth document can be found in the discord.py document.

The snippet of a Code:

from discord.ext import tasks
@tasks.loop(seconds = 5)
async def test_function():
    #YOUR CODE 
    pass 

@client.event
async def on_ready():
    #TASK RUN
    test_function.start()

Upvotes: 2

Related Questions