【发布时间】: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