【问题标题】:Formatting Discord Bot Output格式化 Discord Bot 输出
【发布时间】:2021-01-14 20:51:14
【问题描述】:

我正在尝试使用 Python 和 JS 为 Discord Bot 制作一些特定的命令。 我遇到了一些格式化我希望它看起来像的问题。有没有人偶然知道我错过了什么?

目标:在用户名前添加索引值和缩进。另外,在每个条目之间添加一个行距。

@bot.command(name='qs', aliases=['showqueue'], help='Show the current queue')
async def queue_show(ctx):
    queue = get_guild_queue(ctx)
    now = datetime.now()
    
    embed = discord.Embed(title='Queue', colour = discord.Colour.blue())
    if len(queue) == 0:
        value='The queue is empty!'
    else:
        entries = []
        for entry in queue:
            joined = datetime.strptime(entry['datetime'], '%Y-%m-%d %H:%M:%S') 
            wait_min = (now-joined).seconds / 60

            if entry['msg']:
                entries.append('**{}** *({:.0f} min)*: {}'
                               .format(entry['name'], wait_min, entry['msg']))
            else:
                entries.append('**{}** *({:.0f} min)*'
                               .format(entry['name'], wait_min))
        value='\n'.join(entries)

    name = 'Users in the queue ({})'.format(len(queue))
    embed.add_field(name=name, value=value, inline=False)

    await ctx.send(embed=embed)

目前的样子:

目标:

【问题讨论】:

  • 目标/当前版本之间有很多不同之处,您能更具体一点吗?行距?缩进? “当前回合”?队列编号?
  • 它在第二段'目标:在前面添加索引值并在用户名之前缩进。此外,在每个条目之间添加一个行距。如果不清楚,请告诉我

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


【解决方案1】:

缩进可以通过在条目前面简单地添加一些空格来实现。如果这不起作用(Discord 可能会截断前导空格),请尝试使用制表符:

entries.append('\t**{}** *....[truncated]
                ^^

对于索引,我会使用enumerate function,当给定迭代器作为输入时,它会产生索引和元素的元组。这是一个使用打印功能的简单示例,可以应用于您的案例。

for index, entry in enumerate(queue):
    # add one as index starts at 0
    print(index + 1, entry)

【讨论】:

  • 我知道在 Python 中可以使用空格,但我不确定是因为它进入了 Discord 还是因为我使用的是 Repl.it,但空格不起作用为了我。至于索引,我是否只需将'for entry in queue:'换成'for index,entry in enumerate(queue):',因为我没有使用打印功能而是追加,我希望将其显示在我的代码
  • 新的编辑给了我错误'IndexError: Replacement index 2 out of range for positional args tuple'并且枚举仍然不允许我输出索引值,我需要更改格式追加和格式化
猜你喜欢
  • 1970-01-01
  • 2020-07-16
  • 2022-07-28
  • 2021-12-19
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多