【问题标题】:Python auto random message every xx minutesPython 自动随机消息每 xx 分钟
【发布时间】:2018-07-11 01:55:18
【问题描述】:

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

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

【问题讨论】:

  • 我不明白你的问题陈述。您是否希望目标通道是它们传递给命令的东西,或者是硬编码的,机器人总是向该通道发送消息。
  • 我需要机器人从响应列表中发送一条随机消息以发送到特定频道。
  • 是的,但是您如何选择该频道?您现在是否有一个想法,或者您希望用户为任意渠道触发此过程?
  • 示例:我将添加一个响应列表(["one", "two", "three"]) bot 应该每 5 分钟向频道 ID 发送一条随机消息。
  • 什么频道?调用命令的通道?一些特定的审核渠道?来电者选择的渠道?

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


【解决方案1】:
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 列表可从某个包含范围内获得。

【讨论】:

  • 当然。您只需使用您拥有的响应列表,而不是接受消息作为参数。没有它,也很容易为所有内容提供默认参数。
  • ctx.message.server,不过您也可以编写命令检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 2019-10-25
相关资源
最近更新 更多