【问题标题】:Is there kind of a limit for asyncio in discord.py?discord.py 中的 asyncio 有限制吗?
【发布时间】:2021-08-02 11:17:15
【问题描述】:

所以我有一个 python discord 机器人。这个想法是,有一个有趣的报价频道。为了保持频道井井有条,人们也可以在其中讨论,但是如果在 24 小时后,他们的消息应该被删除,如果之前没有 %q。我有以下代码:

@bot.event
async def on_message(ctx):
    await bot.process_commands(ctx)
    channel = bot.get_channel(ID_OF_CHANNEL)
    if ctx.channel == channel:
        if not ctx.content.lower().startswith("%q"):
            await asyncio.sleep(86400)
            await ctx.delete()

问题是,它不起作用。机器人会响应其他命令,但不会在 24 小时后删除每条消息。事实上,它不会删除任何消息。我也试过只用了 3 小时,但也没有用。只需 30 秒即可通过…… 如果我的问题可能很愚蠢,我很抱歉,但我只是一无所知,我希望有人能帮助我:) 机器人可以查看的消息是否有限制或可以查看的时间有限制? 顺便说一句:我很确定机器人一直在运行,所以它没有被中断。

编辑:为了明确一点:这个想法是在每条消息上启动一个计时器之类的东西,它可以工作 30 秒,但奇怪的是 3 小时没有。

【问题讨论】:

    标签: python discord discord.py bots


    【解决方案1】:

    尝试使用 tasks 而不是 asyncio。它是为这样的重复操作而设计的,因为它是由 discord 制作的,并且包含在 discord.ext 中,所以它更容易和更好。我会这样做的方式是这样的:

    from discord.ext import tasks
    
    @bot.command()
    async def start(ctx):
        deletingLoop.start() #here you start the loop
    
    @tasks.loop(hours=24)
    async def deletingLoop():
        guild = self.bot.get_guild(guildID)    #get the guild
        channel = guild.get_channel(channelID) #and the channel
        channel.purge(limit=1000)              #clear the channel
    

    如果您担心此频道可能有超过 1000 条消息,您可以添加 on_message() 事件来计算此频道上的消息。

    【讨论】:

    • 是的,我也想过这个。我想我并没有真正说清楚,我将编辑我的帖子。这个想法是在每条 single 消息上像计时器一样开始,这奇怪地适用于 asyncio.sleep(30),但不适用于 3h 或类似的东西。
    • 在一个函数里面呆那么久还是个坏主意,你应该创建一个asyncio.Task或者创建一个任务工厂,看看我之前的一个answers
    • 那么我应该做另一个函数来启动计时器吗?循环并不能真正解决我的问题。也许你可以解释如何做到这一点@ŁukaszKwieciński? :)
    【解决方案2】:

    你必须把ctx.message 当作你想delete 上下文的消息。这可以采用参数delay,在该时间后删除选定的消息。

    代码:

    @bot.event
    async def on_message(ctx):
        await bot.process_commands(ctx)
        channel = bot.get_channel(ID_OF_CHANNEL)
        if ctx.channel == channel:
            if not ctx.content.lower().startswith("%q"):
                await ctx.message.delete(delay=24h_in_seconds)
    

    【讨论】:

    • ctx.delete() 也可以。无论如何,我会尝试:)
    • 奇怪的是 ctx 没有功能 delete 但没关系 ?‍♂️ :)
    猜你喜欢
    • 2021-05-02
    • 2021-11-13
    • 2019-07-28
    • 2021-11-18
    • 2021-12-22
    • 2021-05-23
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多