discord.py中将消息转为字符串及实现自定义消息存储回复功能的方法
discord.py 功能实现方案
1. 用户消息转字符串格式
discord.py 中,消息对象 message 的 content 属性本身就是字符串类型,无需额外转换,直接读取即可。
示例用法:
@bot.event async def on_message(message): # 过滤机器人自身发送的消息 if message.author == bot.user: return # 直接获取字符串格式的消息文本 text = message.content # 后续可直接对text字符串做处理 await bot.process_commands(message)
如果需要提取消息中的嵌入、附件等非文本内容转字符串,可单独针对对应属性做字符串格式化处理即可。
2. 指令触发的内容存储与调用功能
以下提供两种实现方案,可按需选择:
临时存储方案(机器人重启后内容清空)
直接用全局变量存储内容,代码实现最简单:
import discord from discord.ext import commands # 开启消息内容意图,必须在Discord开发者后台也同步开启该权限 intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='$', intents=intents) # 初始化存储变量 saved_content = "" # $equal 存储指令 @bot.command(name='equal') async def save_msg(ctx, *, content: str): global saved_content saved_content = content await ctx.send("内容已成功保存") # $message 调用指令 @bot.command(name='message') async def send_saved_msg(ctx): global saved_content if saved_content.strip() == "": await ctx.send("还没有存储任何内容") return await ctx.send(saved_content) # 运行机器人,替换为自己的机器人Token bot.run("你的机器人Token")
持久化存储方案(机器人重启后内容保留)
把存储的内容写入本地JSON文件,避免重启丢失:
import discord from discord.ext import commands import json intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='$', intents=intents) # 启动时读取本地存储的内容 try: with open("saved_content.json", "r", encoding="utf-8") as f: saved_content = json.load(f) except: saved_content = "" @bot.command(name='equal') async def save_msg(ctx, *, content: str): global saved_content saved_content = content # 写入本地文件 with open("saved_content.json", "w", encoding="utf-8") as f: json.dump(saved_content, f, ensure_ascii=False) await ctx.send("内容已成功保存") @bot.command(name='message') async def send_saved_msg(ctx): global saved_content if saved_content.strip() == "": await ctx.send("还没有存储任何内容") return await ctx.send(saved_content) bot.run("你的机器人Token")
注意事项
- 指令中参数前的
*符号作用是接收指令后的所有内容作为一个字符串参数,支持带空格的内容存储 - 必须在Discord开发者平台的机器人设置页开启
Message Content Intent权限,否则机器人无法读取用户发送的消息内容
内容的提问来源于stack exchange,提问作者boiboi
相关产品推荐
相关产品推荐

