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

Adding a timer to giveaway command discord.py

我试图用 giveaway 命令创建一个 discord 机器人,它在 giveaway embed 中每 1-2 分钟更新一次剩余时间。自 3 天以来我一直在尝试,但无法找到解决方案。我设法让它更新秒数,但如果我指定的时间超过 1 米,即 60 秒,它会自动将其转换为秒数并开始赠品,剩余时间只剩 秒数 。我希望它以给定的单位保持时间,并以 --days、--hours、--minutes、--seconds left 为单位更新时间。

这里有几张图片是我的意思:

目前的工作:

我想要它做什么:

它只是结束于或剩余我想要更改的内容!

我当前的代码:

@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]

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

我理解你的问题,因为它实际上是一个非常简单的修复,你可以导入时间,或者使用 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}")

如果您仍然感到困惑或有任何其他问题,可以通过 killrebeest#7187 在 discord 上与我联系或对此答案发表评论。祝你有美好的一天!