Home > Software design >  How to run two functions at once in python?
How to run two functions at once in python?

Time:10-06

I made a discord bot. It check when the message contains words 'kdaj' and 'zoom'. When it does, it will send a message to a server. I am wondering how could I make this program also check if the time is 12:00 then sending another message. Any Ideas? Program:

import discord

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

my_secret = 'Here's my key'

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(msg):
    print(msg)
    msg_words1 = msg.content.split(' ')
    msg_words = []
    for i in msg_words1:
        msg_words.append(i.lower())


    if msg.author == client.user:
        return

    if ('zoom' in msg_words and 'kdaj' in msg_words) or ('zoom' in msg_words and 'kdaj?' in msg_words) or ('zoom?' in msg_words and 'kdaj' in msg_words):
        await msg.channel.send('Zoom imamo vsak torek od 16:00 do 17:30')

client.run(my_secret)

CodePudding user response:

Sidenote

First thing I noticed is the syntax colorization in your question is a little strange. Upon further inspection I noticed that on line 8 you have an apostrophe within your string. This is fine if you use double quotes like this:

my_secret = "Here's my key"

Or an escape character like this:

my_secret = 'Here\'s my key'

But in the current setup, Python will think your string ends after "Here" and so it will throw an error.

Actual answer

On to your actual question, there are a few approaches you can take, I am not familiar with the Discord API and so I will give you another potential solution.

You can write a separate function to run at that given time concurrently and have it send its own message.

This post describes how to run a function at a given time

Here is an example of a setup that will cause a function (printing hello world) to be run every day at 12pm adapted from the above link. NOTE: This is a quick and dirty approach, there are definitely better approaches

from datetime import datetime
from threading import Timer

def hello_world():
    print("hello world")
    # 86400 seconds in a day
    Timer(86400, hello_world).start()


if __name__ == "__main__":
    currentDateTime = datetime.today()
    desiredTime = currentDateTime.replace(hour=12, minute=0, second=0, microsecond=0)
    dt = desiredTime - currentDateTime

    secs = dt.total_seconds()

    t = Timer(secs, hello_world)
    t.start()

This function can be adapted to send a message through your Discord bot and that should accomplish your goal. Let me know if that works for you.

  • Related