Disable discord.py command at certain times of day

南笙酒味 提交于 2021-01-29 06:44:52

问题


I have a tts bot that I want to either toggle on and off with a command, or be automatically turned of from 11pm - 7am when i'm sleeping. Is this possible?

TTS Code:

@client.command()
async def tts(ctx, *, msg):
    print('{0} : {1}'.format(ctx.author, msg))
    print('TTS started {}'.format(msg))
    os.system('flite -t "{}"'.format(msg))
    await ctx.send('TTS done.')

回答1:


You can make a loop, that iterates every 24 hours that will change the enabled_tts variable to False, in the command, check if the variable is set to True

import asyncio
from datetime import datetime, timedelta
from discord.ext import tasks

enabled_tts = True

def delta(hour, minute):
    """Returns in how many seconds is 
    going to be the specified hour"""
    now = datetime.now()
    future = datetime(now.year, now.month, now.day, hour, minute)

    if now.hour >= hour and now.minute > minute:
        future += timedelta(days=1)

    return (future - now).seconds


@tasks.loop(hours=24)
async def disable_command():
    """Disables TTS every 24 hours"""
    global enabled_tts
    enabled_tts = False
    print('TTS disabled')
    

@disable_command.before_loop
async def before_disable_command():
    """This basically delays the `disable_command` loop to start at
    the defined hour"""
    hour, minute = 23, 00
    
    seconds = delta(hour, minute)

    await asyncio.sleep(seconds)

# Also make sure to start the loop on the `on_ready` event
@client.event
async def on_ready():
    await client.wait_until_ready()
    print(f'Logged in as {client.user}')
    disable_command.start()

Here's an example on how to set the variable to False at 11pm, try to figure out how to set it to True at 7am.

Reference:

  • tasks.loop


来源:https://stackoverflow.com/questions/65001832/disable-discord-py-command-at-certain-times-of-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!