(Discord.py) 使用 on_guild_join 事件为 dm 消息添加延迟

时间:2021-07-03 13:40:47

标签: python events discord discord.py

我拥有一个很大的 Discord 服务器,在我的机器人发布后,每个人都在几秒钟内添加了它。我的机器人的功能之一是 dm 所有者说“感谢邀请我,输入 -help 来检查命令”。这背后有一个问题:机器人在 5 秒内向不同的所有者发送了 30 条消息,而我的机器人最终因垃圾邮件不和谐而被禁止。经过几次尝试后,我了解到可以每 15 秒发送一次 dm,以免被禁止。

我如何为每个 dm 添加一个冷却时间?例如,如果有人添加它,机器人会向所有者发送 dm,然后另一个所有者在 15 秒前邀请机器人,但他将在冷却后收到 dm。 我使用的命令:

@bot.event
async def on_guild_join(guild):
    await guild.owner.send("Thanks for inviting the bot! Type -help to check the commands!")

2 个答案:

答案 0 :(得分:0)

简单。您可以使用 asyncio.sleep 等待

import asyncio 

@bot.event
async def on_guild_join(guild):
    await asyncio.sleep(time_seconds)
    await guild.owner.send("Thanks for inviting the bot! Type -help to check the commands!")

答案 1 :(得分:0)

根据您的要求,您希望机器人等待 15 秒,直到向所有者发送消息。您可以通过使用名为 last_dm_sent_time 的全局变量来存储上次发送 dm 的日期和时间。在 on_guild_join 事件中,您可以等待 15 秒过去

在导入后将其添加到文件的开头

import datetime
import asyncio

last_dm_sent_time = datetime.datetime.now()
TIME_DIFFERENCE = 15  # Replace with how many seconds before sending new messages

现在在您的函数中:

@bot.event
async def on_guild_join(guild):
    global last_dm_sent_time
    while datetime.datetime.now() <= abs(last_dm_sent_time+datetime.timedelta(seconds=TIME_DIFFERENCE)):  # Wait Until TIME_DIFFERENCE seconds have passed from last message sent time
        asyncio.sleep(1)  # Wait before rechecking while loop condition (Helps in reducing errors)
    last_dm_sent_time = datetime.datetime.now()  # Reset the timer for other instanced of the same function call.
    await guild.owner.send("Thanks for inviting the bot! Type -help to check the commands!")

注意:该解决方案完全符合 OP 的要求,但如果例如 4 个用户同时邀请它,则将需要 1 分钟发送给所有用户,因为它将等待 15 秒每一个。这不是错误,只是为了让其他人理解。

这是您可以使用的替代实现:

import asyncio

TIME_DIFFERENCE = 15

global message_queue = []

async def message_sender():
    while True:
        asyncio.sleep(TIME_DIFFERENCE)
        if len(message_queue) > 0:
            await message_queue.pop(0)

对于以上内容,这里是 on_guild_join 事件:

@bot.event
async def on_guild_join(guild):
    message_queue.append(guild.owner.send("Thanks for inviting the bot! Type -help to check the commands!"))