首页 > 解决方案 > 冷却命令和某天运行命令

问题描述

所以我为这个机器人写了代码,我希望它做两件事:

  1. 有 15 分钟的冷却时间
  2. 有一个只在星期五有效的命令。

我是编码新手,所以不和谐文档没有帮助。

我的进口

import discord, asyncio, time, discord.guild, random, os, youtube_dl
import os
import asyncio
import math
import random
import youtube_dl
import datetime
import json
from discord.ext import commands, tasks
from discord.ext.commands import Bot, guild_only
from itertools import cycle

15分钟冷却的代码

@client.command()
async def beg(ctx):
    await open_account(ctx.author)

    users = await get_bank_data()
    
    user = ctx.author

    earn = random.randrange(6900)

    await ctx.send(f'Someone gave you {earn} coins!')


    users[str(user.id)]["wallet"] += earn

    with open('main code\economy.json', 'w') as f:
            json.dump(users,f)

仅在星期五有效的命令代码


@client.command()
async def friday(ctx):
    vid = '<URL>'
    
    await ctx.send(vid)

标签: pythonpython-3.xdiscorddiscord.pydiscord.py-rewrite

解决方案


15分钟冷却时间

使用@commands.cooldown()

@client.command()
@commands.cooldown(1, 900, commands.BucketType.user)  # 15 minutes is 900 seconds
async def command_with_cooldown(ctx):
    ...  # code

@command_with_cooldown.error
async def cooldown_error_handler(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send("You can only use this command once every 15 minutes!")

仅限周五

使用datetime.datetime.today().weekday()

import datetime

@client.command()
async def friday_command(ctx):
    if datetime.datetime.today().weekday() == 4:  # 0 is monday, 6 is sunday
        ...  # code
    else:
        await ctx.send("You can only use this command on fridays!")

推荐阅读