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
相关产品推荐
相关产品推荐

