简体   繁体   中英

How can I make a command that can only be triggered once?

I've made a command that the bot will ask some questions and once you are done answering it the bot will message your answers to a channel..

My problem is that you can trigger the command over and over. Is there a way to make it run only once by a user and can be run again by that user once all of the question is asked?

@commands.command(name='test')
@cooldown(1, 60)
async def test(self, ctx):
    if not ctx.guild:
        return
    test = []
    q1 = ['test', 'test']
    channel = self.client.get_channel(733649176373755945)
    dm = await ctx.author.create_dm()

    def check(author):
        def inner_check(message):
            if message.author != author:
                return False
            try:
                str(message.content)
                return True
            except ValueError:
                return False

        return inner_check

    for question in q1:
        await dm.send(question)
        msg = await self.client.wait_for('message', check=check(ctx.author))
        test.append(msg.content)

    answers = "\n".join(f'{a}. {b}' for a, b in enumerate(test, 1))
    submit = f'\n{answers}'
    await channel.send(submit)

Here's my version of your code, which does what you want. I use self.test.reset_cooldown(ctx) to reset the cooldown:

from discord.ext import commands
from discord_util import message_check

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    @commands.command()
    @commands.cooldown(1, 100, commands.BucketType.user)
    @commands.dm_only()
    async def test(self, ctx):
        answers = []
        questions = ["test1", "test2"]
        for question in questions:
            dm = await ctx.author.send(question)
            msg = await self.bot.wait_for('message', check=message_check(channel=dm.channel, author=ctx.author))
            answers.append(msg.content)
        answer_str = "\n".join(f'{a}. {b}' for a, b in enumerate(answers, 1))
        await ctx.send(f"\n{answer_str}")
        self.test.reset_cooldown(ctx)

You can find my message_check code here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM