【问题标题】:discord.py: function wait until a specific date and timediscord.py:函数等到特定的日期和时间
【发布时间】:2021-03-03 09:47:03
【问题描述】:

我又有问题了:) 我计划了一个机器人,它会在用户告诉机器人何时向频道输出消息。 我会给你看代码,然后我会告诉你我的问题:

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)

问题是,我只需要 time_check() 用 endtime/enddate 检查当前时间的每一分钟。 如果达到了结束时间和结束日期,time_check() 可以停止工作并返回到 on_message() 继续工作。

我完全不知道如何集成这个 check_time() 函数。 我希望你们中的某个人可以帮助我。

谢谢你们。

【问题讨论】:

  • 而不是每分钟检查是否已达到结束时间,只需计算当前时间和结束时间之间的秒数并等待该秒数,这样效率会更高并大大减少代码长度。

标签: python datetime discord bots


【解决方案1】:

这些是您需要更改的功能,而不是每分钟检查是否达到结束时间,我只是计算了从当前时间到结束时间需要等待的总秒数。我还添加了一个检查 end time is in the past 是否非常重要。总的来说,我相信这是实现您想要的结果的最佳方式。

@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 :).")

【讨论】:

  • 谢谢 Raz Kissos。这解决了我的问题。顺便说一句,我已经删除了 async def time_check(message_obj, secs_to_wait: float) 并将以下内容添加到 on_message 中:time_to_wait = endtime_obj - currtime_obj , secs_to_wait = time_to_wait.total_seconds() , await asyncio.sleep(secs_to_wait)。这工作也很棒。感谢您的大力帮助。
  • Raz Kissos,我还有一个小问题。 :) 我如何检查用户是否使用了正确的输入格式 DD.MM.YYYY ? 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
  • @loser09 您必须检查字符串长度是否正好是 10 个字符长并且包含 2 个点,一个在第 2 个索引中,一个在第 5 个索引中。然后检查所有其他字符是否都是数字,如果日期不正确,我确定 datetime 会抛出错误
  • 非常感谢您的帮助。周末愉快。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-08
  • 1970-01-01
  • 2014-04-20
  • 2010-10-13
  • 2021-09-15
  • 1970-01-01
  • 2012-05-27
相关资源
最近更新 更多