【问题标题】:Send multiple messages discord python bot in for loop在for循环中发送多条消息discord python bot
【发布时间】:2020-12-23 04:25:57
【问题描述】:

我有一个数组,我想用 discord.py 在 for 循环中发送一些消息。我正在尝试使用 on_ready() 命令,但仅发送第一条消息时遇到问题。我对异步和不和谐机器人都很陌生。这里一定有更简单的解决方案...

client = discord.Client()
links = []
for x in y:
    # do some things
    links.append(stuff)

@client.event
async def on_ready():
    channel = client.get_channel(12345678910)
    for link in links:
        await channel.send(link)


client.run(DISCORD_TOKEN)

提前感谢您的帮助!

【问题讨论】:

  • 你能提供一个你的数组是什么样子的例子吗?
  • 它们只是一堆 URL 字符串。 ['google.com', 'amazon.com', 'facebook.com']
  • 当机器人准备就绪时,您希望将它们发送到channel
  • 没错,就是想把它们一个一个转储到频道里

标签: python async-await discord discord.py


【解决方案1】:

除了在on_ready() 事件下添加代码之外,您还可以创建一个循环,该循环在机器人准备好后运行 1 次然后停止。要创建循环,请使用discord.ext.tasks

from discord.ext.tasks import loop

@loop(count=1)
async def send_links():
    channel = client.get_channel(730064641857683581)
    links = ['link1', 'link2', 'link3', 'link4']
    for link in links:
        await channel.send(link)


@send_links.before_loop
async def before_send_links():
    await client.wait_until_ready()  # Wait until bot is ready.

@send_links.after_loop
async def after_send_links():
    await client.logout()  # Make the bot log out.


send_links.start()
client.run(DISCORD_TOKEN)

【讨论】:

  • 最后一个问题。我的程序在完成任务后似乎挂起。执行后关闭它的任何方法。 client.logout() 似乎是移动,但不确定它的去向
  • 挂起是什么意思?
  • 发布链接后程序不会终止。我想在 cron 中运行它,所以不想要大量挂起的进程。
  • 您希望机器人发布链接然后退出?
  • 美丽。太感谢了! (有点尴尬,我无法弄清楚那部分:P)
【解决方案2】:

起初,client = discord.Client() 绝对不适合定义client。你应该用

定义client

client = commands.Bot(command_prefix='command's prefix here')。那么如果你想让它成为一个命令,你可以这样做:

@client.command()
async def send_link(ctx):
    for link in links:
        await ctx.send(link)

但这并不好,因为它会发送很多消息,所以我宁愿使用 embeds

async def send_link(ctx):
    embed = discord.Embed()
    for link in links:
        embed.add_field(name=" ", value=link, inline=False)
    await ctx.send(embed=embed)

您不应该在on_message 中使用它,因为那毫无意义。在代码中,你做了channel = client.get_channel(1234667890)。这也是一个问题,你必须用真实的频道ID来改变它。

【讨论】:

  • 感谢您的帮助。正在做一些改变。我在真实代码中有正确的 id。我正在尝试做的部分事情是 not 有消息提示,因为我计划在 cron 中运行它
  • ctx 代表什么,send_link 函数会在client.run(DISCORD_TOKEN) 中调用吗?
  • 你应该阅读一些文档,例如api referencessend_link 是当您在聊天中键入 prefix + send_link 时运行的命令,例如 .send_link。 Ctx 正在获取消息发送的通道并在该通道中发送消息。因此,使用这些代码,如果您在 commands.Bot 中定义 command_prefix 然后在您的公会中键入 prefix + send_link,它将发送数组数据。
  • 这是有道理的,但我试图让它在没有提示的情况下发送。我似乎在文档中找不到这种示例。
  • 您希望它只发送一次吗?
猜你喜欢
  • 2021-01-12
  • 2018-07-24
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2018-05-03
  • 2020-12-01
相关资源
最近更新 更多