如何在Python的Discord Bot中实现多行消息与描述格式化?
解决Discord.py Embed消息换行/多行显示问题
下面是几种实现Embed文本换行、分段的实用方法,适合初学者快速上手:
方法1:直接插入换行符\n
在字符串中加入\n即可实现换行,连续两个\n会生成空行,实现分段效果:
from discord import Embed import discord from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @bot.command() async def test_embed(ctx): embed = Embed(title="测试标题", description="第一行描述内容\n第二行描述内容\n\n空一行后的第三行内容") await ctx.send(embed=embed) bot.run("你的Bot令牌")
方法2:使用多行字符串(三引号)
用三个双引号或单引号包裹文本,直接按需求换行输入内容,格式更直观:
@bot.command() async def multi_line_embed(ctx): embed = Embed(title="多行字符串示例") # 直接按换行编写内容,空行也会被保留 embed.description = """这是第一段内容 这是第二段内容 这是空一行后的第三段内容""" await ctx.send(embed=embed)
方法3:Embed字段内换行
如果是给Embed的字段添加多行内容,同样适用上面的两种方法:
@bot.command() async def field_embed(ctx): embed = Embed(title="字段换行演示") # 字段值里用\n换行 embed.add_field(name="基础字段", value="字段第一行\n字段第二行", inline=False) # 字段值用多行字符串 embed.add_field(name="多行字段", value="""字段第一段 字段第二段 字段第三段""", inline=False) await ctx.send(embed=embed)
注意事项
- 不要将
\n写成\\n,后者会被识别成普通文本而不是换行符 - 使用多行字符串时,注意不要在换行后添加不必要的缩进,否则会在Embed里显示空格
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

