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

标签 python python-3.x discord discord.py

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

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

目前做什么:

enter image description here

我想要它做什么:

enter image description here

它只是 Ends In Or 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:
            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}")

在这两个修复中,我将修复一个可以轻松修复的小问题,你有它,所以 while time,它会下降 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 上与我联系或对此答案发表评论。祝你有美好的一天!

关于python - 将计时器添加到赠品命令 discord.py,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65943784/

相关文章:

python - 无法使用 Django 在 GCM 中发送 POST 请求

python - SQL 命令 SELECT 从 Postgresql 数据库中获取未提交的数据

python argparse遇到 '$'后停止解析

python - 我需要帮助在 discord py 中制作一个 discord py temp mute 命令

javascript - 为什么我的清除命令出错了?

python - Python 的性能是否物有所值?

python - 导入cv2错误python

python - 创建元组,其中第一个元素是混合大小写的单词,第二个元素是完全小写的字符串

python - 如何解决窗口8中Visual Studio代码中的导入错误?

javascript - 我正在尝试删除 discord.js 中的消息