Python 3.x Discord.py时间表
有没有比我在代码中使用的更好的方法在python中创建闹钟?这是工作良好,但我想知道是否有更好的东西,我也想分开这段代码,使它在一个齿轮Python 3.x Discord.py时间表,python-3.x,discord.py,Python 3.x,Discord.py,有没有比我在代码中使用的更好的方法在python中创建闹钟?这是工作良好,但我想知道是否有更好的东西,我也想分开这段代码,使它在一个齿轮 import asyncio from datetime import datetime from discord.ext import commands TOKEN = 'XXX' client = commands.Bot(command_prefix='.') alarm_time = '23:33'#24hrs channel_id = '515
import asyncio
from datetime import datetime
from discord.ext import commands
TOKEN = 'XXX'
client = commands.Bot(command_prefix='.')
alarm_time = '23:33'#24hrs
channel_id = '51599XXXXX5036697'
@client.event
async def on_ready():
print('Bot Online.')
async def time_check():
await client.wait_until_ready()
while not client.is_closed:
now = datetime.strftime(datetime.now(), '%H:%M')
channel = client.get_channel(channel_id)
messages = ('Test')
if now == alarm_time:
await client.send_message(channel, messages)
time = 90
else:
time = 1
await asyncio.sleep(time)
client.loop.create_task(time_check())
client.run(TOKEN)
您可以使用,例如:
import time
import sched
s = sched.scheduler(time.perf_counter, time.sleep)
s.enter(60, 1, action_function, (args))
s.run()
上面的代码将调度程序启动为s
,它使用time.perf\u couter
获取当前时间,并使用time.sleep
进行延迟
使用调度程序时,需要至少传递3个参数,第一个参数是daly时间(以秒为单位),第二个参数是它的优先级(优先级最高的调度事件首先执行,第三个参数是延迟后要执行的函数)
可以有两个以上的可选参数,即参数的元组或关键字参数的dict,这两个参数都将传递给延迟后将执行的函数
我使用了这个库来实现IRC机器人中的定时禁止,所以它也应该适用于您的Discord机器人
下面是一个应该可以使用您的代码的示例(我不使用discord等,所以不能真正测试整个代码,只测试代码片段):
import asyncio
from datetime import datetime, timedelta
from discord.ext import commands
import time
import sched
TOKEN = 'XXX'
client = commands.Bot(command_prefix='.')
alarm_time = '23:33'#24hrs
channel_id = '51599XXXXX5036697'
@client.event
async def on_ready():
print('Bot Online.')
async def time_check():
await client.wait_until_ready()
while not client.is_closed:
channel = client.get_channel(channel_id)
messages = ('Test')
f = '%H:%M'
now = datetime.strftime(datetime.now(), f)
# get the difference between the alarm time and now
diff = (datetime.strptime(alarm_time, f) - datetime.strptime(now, f)).total_seconds()
# create a scheduler
s = sched.scheduler(time.perf_counter, time.sleep)
# arguments being passed to the function being called in s.enter
args = (client.send_message(channel, message), )
# enter the command and arguments into the scheduler
s.enter(seconds, 1, client.loop.create_task, args)
s.run() # run the scheduler, will block the event loop
client.loop.create_task(time_check())
client.run(TOKEN)
你能告诉我如何在我的代码中应用它吗,如果没有太多要求的话。我是新来的。我用一个例子编辑了这篇文章,使用了你的代码,它应该可以工作,它只会创建一个报警事件,那时会执行,如果你想开始更多,你需要做更多的编辑。我确实尝试了你给我的代码,我做了一些修改也要搜索。在f='%M:%M'上,它应该是f='%H:%M',对吗?这样我可以得到秒数。另外,在创建计划程序的部分之后,它得到的stuckTask异常从未联机检索到。AttributeError:模块“asyncio”没有属性“create\u task”