使用 discord bot 发送多行字符串作为消息时出现布局错误

Layout error when sending a multiline string as message with discord bot

我启动了一个 discord 机器人 运行。我的目标是在某个命令后向用户发送消息。这行得通,但不知何故我的布局是错误的。我的字符串的第一行是正确的,之后发送的其余部分带有一些前导空格。

client = commands.Bot(command_prefix = '/')

@client.command()
async def start(ctx):
    welcome_message = f"""
    Welcome to my bot
    here is a new line which has leading spaces
    this line here has some aswell
    """
    await ctx.send(welcome_message)

基本上我的消息是这样的:

Welcome to my bot
    here is a new line which has leading spaces
    this line here has some aswell

即使在发送前使用 welcome_message = welcome_message.lstrip() 也无法解决问题。

本例中的缩进是字符串的一部分(因为它是多行字符串),您可以简单地删除它:

@client.command()
async def start(ctx):
    welcome_message = welcome_message = f"""
Welcome to my bot
here is a new line which has leading spaces
this line here has some aswell
    """
    await ctx.send(welcome_message)

如果你想保留缩进使用textwrap.dedent方法:

import textwrap

@client.command()
async def start(ctx):
    welcome_message = welcome_message = f"""
    Welcome to my bot
    here is a new line which has leading spaces
    this line here has some aswell
    """
    await ctx.send(textwrap.dedent(welcome_message))