You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py中如何将多个内容合并为单条消息发送

问题原因

你之前的错误写法是把Python变量、表达式直接放在字符串引号内部,此时Python解释器会将其识别为普通文本内容,不会实际执行表达式取值,所以无法输出你想要的@和随机回复内容。

推荐实现方案(f-string写法,Python3.6及以上版本通用)

这是最简洁易读的写法,只需要在字符串前加f标识,把需要取值的变量/表达式用{}包裹即可:

import random
# 此处省略你其他的代码逻辑
if msg.startswith('respond'):
    await message.channel.send(f'alright then, {message.author.mention} {random.choice(responses)}')

其他可选实现方式

如果你需要兼容更旧的Python版本,也可以用下面两种写法实现相同效果:

  • 字符串拼接写法
if msg.startswith('respond'):
    await message.channel.send('alright then, ' + message.author.mention + ' ' + random.choice(responses))
  • str.format()写法
if msg.startswith('respond'):
    await message.channel.send('alright then, {} {}'.format(message.author.mention, random.choice(responses)))

补充提示

message.author.mention本身返回的就是符合Discord规则的提及格式字符串,不需要你额外套尖括号,直接拼入内容就能正常@到对应的用户。

内容的提问来源于stack exchange,提问作者tazzan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 03:06:03