如何让Python开发的Discord Bot重启后保留自定义响应?
解决方案:让Discord Bot持久化自定义响应
问题根源是你当前的!learn命令只把自定义响应存在内存里,Bot重启后内存数据清空,导致添加的内容丢失。要实现重启后仍能记住响应,核心是实时将新添加的响应写入JSON文件,同时启动Bot时从文件加载已有数据。
步骤1:启动时加载已有响应
写一个加载函数,启动Bot时读取custom_responses.json的内容到内存字典;如果文件不存在,就初始化一个空字典:
import json import discord from discord.ext import commands # 加载自定义响应 def load_custom_responses(): try: with open('custom_responses.json', 'r', encoding='utf-8') as f: return json.load(f) except FileNotFoundError: # 文件不存在时返回空字典 return {} # 初始化全局字典存储响应 custom_responses = load_custom_responses() # 配置Intents(必须开启message_content权限) intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='!', intents=intents)
步骤2:修改!learn命令,添加持久化逻辑
在!learn命令处理函数里,把新响应添加到内存字典后,立即将整个字典写入JSON文件:
@bot.command() async def learn(ctx, trigger_word, *, response_content): # 触发词转小写,避免大小写敏感问题 trigger = trigger_word.lower() # 更新内存中的响应字典 custom_responses[trigger] = response_content # 写入JSON文件保存 with open('custom_responses.json', 'w', encoding='utf-8') as f: json.dump(custom_responses, f, indent=2, ensure_ascii=False) await ctx.send(f"已成功记住:`{trigger}` -> {response_content}")
步骤3:处理消息匹配逻辑
监听用户消息,检查消息内容是否在自定义响应字典中,匹配成功则回复:
@bot.event async def on_message(message): # 忽略Bot自身发送的消息 if message.author == bot.user: return # 消息内容转小写,和触发词统一匹配规则 message_content = message.content.lower() # 检查是否有匹配的自定义响应 if message_content in custom_responses: await message.channel.send(custom_responses[message_content]) # 必须调用此方法,否则Bot无法处理命令 await bot.process_commands(message)
检查Intents配置
确保你的intents.json开启了message_content权限,否则Bot无法读取用户消息内容:
{ "intents": { "guilds": true, "messages": true, "message_content": true, "members": false } }
测试验证
- 启动Bot,执行
!learn cat cat is good,此时custom_responses.json会新增"cat": "cat is good"的记录 - 重启Bot,发送消息
cat,Bot会自动回复cat is good
内容的提问来源于stack exchange,提问作者hutcch
相关产品推荐
相关产品推荐

