每隔XX分钟发送一次Python自动随机消息

时间:2018-07-11 01:55:18

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

如何每隔xx分钟将自动随机消息发送到特定的服务器和频道ID。

async def randommessage():
        response = random.choice(["one", "two", "three"])
        await bot.say(response)
        await asyncio.sleep(120)

1 个答案:

答案 0 :(得分:2)

timeout = 60*5  # 5 minutes

@bot.command(pass_context=True)
async def randommessage(ctx, *messages):
    while True:
        await bot.say(random.choice(messages))
        await asyncio.sleep(timeout)

在这里,我们接受任意数量的参数作为潜在消息,以回显当前通道。调用看起来像

!randommessage test1 test2 "Messages with spaces go in quotes"

功能更全的版本将是

@bot.command(pass_context=True)
async def randommessage(ctx, channel: discord.Channel, timeout: int, *messages):
    while True:
        await bot.send_message(channel, random.choice(messages))
        await asyncio.sleep(timeout*60)  # timeout minutes

可以像

那样调用
!randommessages #default 5 test1 test2 "Messages with spaces go in quotes"

编辑:

如果您已经收到其他机制的响应,则可以接受等待时间和目标频道,并使用合理的默认值。

@bot.command(pass_context=True)
async def randommessage(ctx, channel: discord.Channel=None, timeout: int=5):
    channel = channel or ctx.message.channel  # default to the channel from the invocation context
    while True:
        await bot.send_message(channel , random.choice(response))
        await asyncio.sleep(timeout*60)  # timeout minutes

这假设response列表在某些范围内可用。

相关问题