简体   繁体   中英

discord.py: function wait until a specific date and time

i have a question again :) i plan a bot that will give a message output to a channel after a user has tell the bot when. i will show you the code and then i will tell you my problem:

import discord
import datetime
import time
import asyncio
import random
from discord.ext import commands
from discord import Embed

TOKEN = 'mytoken'

intents = discord.Intents().all()
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(client.user.name)
    print(client.user.id)

@client.event
async def on_message(message):
    def check(m):
       return m.channel == message.channel and m.author != client.user
    if message.author == client.user:
       return
    if message.content.startswith("!start"):
           await message.channel.send('Please type in the Enddate (TT.MM.JJ):')
           enddateinput = await client.wait_for('message', check=check, timeout=30)
           enddate = enddateinput.content
           await message.channel.send('Please type in the Endtime (HH:MM):')
           endtimeinput = await client.wait_for('message', check=check, timeout=30)
           endtime = endtimeinput.content

# *********************************************
# I dont know how to check the time with the subfunction time_check :(
# The optimal result is the function wait at this point until datetime.now(now) = enddate & endtime.
# and then i want the function to continue working.       
# *********************************************

           await message.channel.send('Enddate & Endtime reached.')
           await message.channel.send('Go on with the rest of the code :).')



async def time_check():
    await client.wait_until_ready()
    while not client.is_closed():
        nowdate = datetime.strftime(datetime.now(), '%d.%m.%y')
        nowtime = datetime.strftime(datetime.now(), '%H:%M')       
        if (nowdate == enddate) and (nowtime == endtime):
           await asyncio.sleep(1)
# *********************************************
#           BACK TO FUNKTION
# *********************************************
        else:
           await asyncio.sleep(60)


client.run(TOKEN)

The problem is, i need time_check() only to check every minute the current time with endtime/enddate. If the endtime and enddate reached, time_check() can stop working and go back to on_message() to continue working the funktion.

I absolutely don't know how to integrate this check_time () function. I hope someone of you can help me.

Thank you guys.

These are the functions you need to change, instead of checking every minute to see if the end time is reached I simply calculated the total seconds it will take to wait from the current time to the end time. I also added a check to see if the end time is in the past which is very important. In general I believe this is the best way to implement youre desired outcome.

@client.event
async def on_message(message):
    def check(m):
        return m.channel == message.channel and m.author != client.user

    if message.author == client.user:
        return
    if message.content.startswith("!start"):
        # Get end date.
        await message.channel.send("Please type in the Enddate (DD.MM.YYYY):")
        enddateinput = await client.wait_for("message", check=check, timeout=30)
        enddate = enddateinput.content
        # Get end time.
        await message.channel.send("Please type in the Endtime (HH:MM):")
        endtimeinput = await client.wait_for("message", check=check, timeout=30)
        endtime = endtimeinput.content

        # Get the two datetime objects, current and endtime.
        endtime_obj = datetime.datetime.strptime(
            ".".join([enddate, endtime]), "%d.%m.%Y.%H:%M"
        )
        currtime_obj = datetime.datetime.now()

        if not (endtime_obj > currtime_obj):  # Check if end time is in the past.
            await message.channel.send("End time can not be in the past!")

        # Send the seconds to wait into the time check function
        time_to_wait = endtime_obj - currtime_obj  # The time delta (difference).
        await time_check(message, time_to_wait.total_seconds())


async def time_check(message_obj, secs_to_wait: float):
    await client.wait_until_ready()

    await asyncio.sleep(secs_to_wait)

    await message_obj.channel.send("Enddate & Endtime reached.")
    await message_obj.channel.send("Go on with the rest of the code :).")

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