【问题标题】:How do you make a countdown bot in discord using python如何使用 python 在不和谐中制作倒计时机器人
【发布时间】:2021-01-14 19:01:24
【问题描述】:

我正在尝试制作一个机器人,如果你告诉它倒计时,例如7:00 pm,它会对该时间进行倒计时,然后发送一条消息,例如@everyone 倒计时结束,如果用户键入取消,倒计时取消,我想要它

请注意,我希望它像闹钟,而不是计时器

除了倒计时和倒计时后的留言,我都已经做好了

这里是现在的代码

import discord
from discord.ext import commands
from discord.ext import tasks

client = commands.Bot(command_prefix = "m!")

@client.command(aliases = ["countdown"])
async def countdown_at(ctx, time):
    await ctx.send(f"OK\countdown made to {time}")

【问题讨论】:

  • 你可能想使用 asyncio create_task 和 asyncio sleep
  • 该死,这个问题有 1k 浏览量,没想到...

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


【解决方案1】:

在等待取消消息时,您可以使用wait_for 上的timeout 作为计时器:

@bot.command()
async def ex(ctx, time: int):
    await ctx.send("Countdown started")
    def check(message):
        return message.channel == ctx.channel and message.author == ctx.author and message.content.lower() == "cancel"
    try:
        m = await bot.wait_for("message", check=check, timeout=time)
        await ctx.send("Countdown cancelled")
    except asyncio.TimeoutError:
        await ctx.send(f"{ctx.guild.default_role} countdown finished")

【讨论】:

  • @AbdullahAlawad 将其更改为 {ctx.guild.default_role} 修复了 @@,不知道为什么。
  • 暂时仍将其用作占位符
  • 你也许可以将它与这样的东西结合起来:stackoverflow.com/questions/36810003/…
  • 具体应该放在哪里,我之前没做过机器人,所以不知道
【解决方案2】:

我想出了如何制作它, 在这里:

@bot.command()
async def alarm(ctx, time)
    now = datetime.now()
    mtimeA = time
    mtimeB = mtimeA.split(":")
    hr = int(mtimeB[0])
    min = int(mtimeB[1])
    secsleft = int((timedelta(hours=24) - (now - now.replace(hour=hr, minute=min, second=0, microsecond=0))).total_seconds() % (24 * 3600))
    await ctx.send(f"OK\nAlarm set to {time}")
    def check(message):
        return message.author == ctx.author and message.content.lower() == "cancel alarm"
    try:
        await bot.wait_for("message", check=check, timeout=secsleft)
        await ctx.send("Alarm cancelled")
    except:
        await ctx.send(f"{ctx.author.mention} alarm finished")

所有这些都需要时间,例如。 “19:20”,并将其拆分为 2 个值“[19, 20]”。然后它使用 timedelta 将给定的时间转换为秒。最后,它等待“取消警报”,如果它没有收到此消息并且警报完成,它会发送一条消息通知用户他的警报完成

【讨论】:

    猜你喜欢
    • 2021-07-13
    • 2021-05-17
    • 1970-01-01
    • 2022-07-12
    • 2020-08-26
    • 2021-01-24
    • 2021-04-12
    • 1970-01-01
    • 2021-10-30
    相关资源
    最近更新 更多