向赠品命令discord.py添加计时器

问题描述 投票:0回答:1

我试图创建一个带有赠品命令的不和谐机器人,该命令每 1-2 分钟更新一次赠品嵌入中剩余的时间。我已经尝试了 3 天,但未能找到解决方案。我设法让它更新秒数,但如果我指定的时间超过 1m,即 60 秒,它会自动将其转换为秒,并开始赠品,剩余时间为 just 秒 。我希望它以给定单位保留时间并以--天、--小时、--分钟、--秒为单位更新时间。

这里有一些图片,我的意思是:

目前做什么:

enter image description here

我想要它做什么:

enter image description here

它只是结束于或时间剩下我想要改变的!

我当前的代码:

@commands.command()
    @commands.guild_only()
    async def gstart(self, ctx, duration, *, prize):
        time = self.convert(duration)
        if time == -1:
            await ctx.send(f'Answer Time With A Proper Unit (s, m, h, d)')
            return
        elif time == -2:
            await ctx.send(f'Time Must Be A Integer!')
            return
        giveawayembed = discord.Embed(
            title="🎉 New Giveaway! 🎉",
            description=f"**Prize:** {prize}\n"
                        f"**Hosted By:** {ctx.author.mention}\n"
                        f"**Ends In:** {time} Seconds",
            colour=discord.Color.green()
        )

        msg = await ctx.send(embed=giveawayembed)

        reactions = await msg.add_reaction("🎉")

        while time:
            await sleep(10)
            time -= 10
            giveawayembed.description= f"**Prize:** {prize}\n**Hosted By:** {ctx.author.mention}\n**Ends In:** {time} Seconds"
            await msg.edit(embed=giveawayembed)

        new_msg = await ctx.fetch_message(msg.id)

        users = await new_msg.reactions[0].users().flatten()
        users.pop(users.index(self.client.user))

        winner = random.choice(users)

        endembed = discord.Embed(
            title="Giveaway ended!",
            description=f"Prize: {prize}\nWinner: {winner.mention}")

        await msg.edit(embed=endembed)
        await ctx.send(f"🎉 Giveaway Winner: {winner.mention} | Prize: {prize}")

我有转换时间:

class Giveaway(commands.Cog):
    def __init__(self, client):
        self.client = client

    def convert(self, time):
        pos = ["s", "m", "h", "d"]
        time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}
        unit = time[-1]

        if unit not in pos:
            return -1
        try:
            val = int(time[:-1])
        except:
            return -2

        return val * time_dict[unit]

非常感谢任何帮助! 😁 如果我没能让你理解我的问题,我很抱歉。 😅

python python-3.x discord discord.py
1个回答
1
投票

我理解你的问题,因为它实际上是一个非常简单的修复,你可以导入时间,或使用

await asyncio.sleep(time)

在使用我提供的代码之前,请确保在导入中添加

import asyncio

您的代码:

    @commands.command()
    @commands.guild_only()
    async def gstart(self, ctx, duration, *, prize):
        time = self.convert(duration)
        if time == -1:
            await ctx.send(f'Answer Time With A Proper Unit (s, m, h, d)')
            return
        elif time == -2:
            await ctx.send(f'Time Must Be A Integer!')
            return
        giveawayembed = discord.Embed(
            title="🎉 New Giveaway! 🎉",
            description=f"**Prize:** {prize}\n"
                        f"**Hosted By:** {ctx.author.mention}\n"
                        f"**Ends In:** {time} Seconds",
            colour=discord.Color.green()
        )

        msg = await ctx.send(embed=giveawayembed)

        reactions = await msg.add_reaction("🎉")

        while time:
            await sleep(10)
            time -= 10
            giveawayembed.description= f"**Prize:** {prize}\n**Hosted By:** {ctx.author.mention}\n**Ends In:** {time} Seconds"
            await msg.edit(embed=giveawayembed)

        new_msg = await ctx.fetch_message(msg.id)

        users = await new_msg.reactions[0].users().flatten()
        users.pop(users.index(self.client.user))

        winner = random.choice(users)

        endembed = discord.Embed(
            title="Giveaway ended!",
            description=f"Prize: {prize}\nWinner: {winner.mention}")

        await msg.edit(embed=endembed)
        await ctx.send(f"🎉 Giveaway Winner: {winner.mention} | Prize: {prize}")

在这两个修复中,我都会修复一个很容易修复的小问题,所以当时间到来时,它会减少 10,我建议这样做,这样它就会显示

while time > 0:
,这样一旦它达到 0,它就不会继续计数下来。

使用

await asyncio.sleep(time)
轻松修复:

    @commands.command()
    @commands.guild_only()
    async def gstart(self, ctx, duration, *, prize):
        time = self.convert(duration)
        if time == -1:
            await ctx.send(f'Answer Time With A Proper Unit (s, m, h, d)')
            return
        elif time == -2:
            await ctx.send(f'Time Must Be A Integer!')
            return
        giveawayembed = discord.Embed(
            title="🎉 New Giveaway! 🎉",
            description=f"**Prize:** {prize}\n"
                        f"**Hosted By:** {ctx.author.mention}\n"
                        f"**Ends In:** {time} Seconds",
            colour=discord.Color.green()
        )

        msg = await ctx.send(embed=giveawayembed)

        reactions = await msg.add_reaction("🎉")

                while time >= 0:
            if time <= 60:
                giveaway.remove_field(index=1)
                giveaway.insert_field_at(index=1, name='Ends:', value=f'{time} second(s) from now')
                await my_msg.edit(embed=giveaway)
                time -= 10
                await asyncio.sleep(10)
            elif 60 <= time < 3600:
                giveaway.remove_field(index=1)
                giveaway.insert_field_at(index=1, name='Ends:', value=f'{time/60} minute(s) from now')
                await my_msg.edit(embed=giveaway)
                time -= 6
                await asyncio.sleep(6)
            elif 3600 <= time < 86400:
                giveaway.remove_field(index=1)
                giveaway.insert_field_at(index=1, name='Ends:', value=f'{time/3600} hour(s) from now')
                await my_msg.edit(embed=giveaway)
                time -= 360
                await asyncio.sleep(360)
            elif time >= 86400:
                giveaway.remove_field(index=1)
                giveaway.insert_field_at(index=1, name='Ends:', value=f'{time/86400} day(s) from now')
                await my_msg.edit(embed=giveaway)
                time -= 8640
                await asyncio.sleep(8640)
        if time <= 0:
            giveaway.remove_field(index=1)
            giveaway.insert_field_at(index=1, name='Ends:', value=f'Ended at {datetime.datetime.now().strftime("%B %d, %I:%M %p")}') # noqa
            await my_msg.edit(embed=giveaway)

        await asyncio.sleep(time)

        new_msg = await ctx.fetch_message(msg.id)

        users = await new_msg.reactions[0].users().flatten()
        users.pop(users.index(self.client.user))

        winner = random.choice(users)

        endembed = discord.Embed(
            title="Giveaway ended!",
            description=f"Prize: {prize}\nWinner: {winner.mention}")

        await msg.edit(embed=endembed)
        await ctx.send(f"🎉 Giveaway Winner: {winner.mention} | Prize: {prize}")
© www.soinside.com 2019 - 2024. All rights reserved.