Discord.py警告命令开发求助:实现警告信息存储至JSON文件
Adding JSON Storage to Your Discord Warn Command
Hey there! Nice start on your warn command—let's get those warning records saved to a JSON file properly. Here's a step-by-step modification to your code that handles loading, storing, and saving warnings reliably:
First, we'll add a couple of essential modules (json for file handling and datetime to track when warnings were issued) plus helper functions to manage the JSON data, so we don't repeat code unnecessarily.
Modified Full Code
import discord from discord.ext import commands import json import datetime # Make sure this matches your bot's actual command prefix bot = commands.Bot(command_prefix='!') def load_warnings(): """Load warnings from JSON file, or start fresh if file is missing/corrupted""" try: with open('warnings.json', 'r') as f: return json.load(f) except FileNotFoundError: # No existing file yet, return empty warning structure return {} except json.JSONDecodeError: print("⚠️ Warning: warnings.json is corrupted. Starting with empty warning list.") return {} def save_warnings(warnings_data): """Save updated warning data to JSON with readable formatting""" with open('warnings.json', 'w') as f: json.dump(warnings_data, f, indent=4) @bot.command() @commands.has_permissions(kick_members=True) async def warn(ctx, member: discord.Member, *, arg): logsChannel = bot.get_channel(839235810200780800) # Create a single embed (no need for duplicate identical embeds!) embed = discord.Embed(title="Warning issued: ", color=0xf40000) embed.add_field(name="Warning: ", value=f'Reason: {arg}', inline=False) embed.add_field(name="User warned: ", value=f'{member.mention}', inline=False) embed.add_field(name="Warned by: ", value=f'{ctx.author}', inline=False) await logsChannel.send(embed=embed) await member.send(f'You have been warned in Jackkkks Society for **{arg}**!') await ctx.send(embed=embed) # Now handle saving the warning to JSON warnings = load_warnings() # Use member ID as the key (nicknames change, IDs are permanent!) user_id = str(member.id) # Initialize empty warning list for the user if they have no prior warnings if user_id not in warnings: warnings[user_id] = [] # Add the new warning record with detailed info warnings[user_id].append({ "reason": arg, "warned_by_id": str(ctx.author.id), "warned_by_name": str(ctx.author), "timestamp": datetime.datetime.utcnow().isoformat() }) # Save the updated warnings back to the file save_warnings(warnings)
Key Improvements Explained
- Permanent User Linking: We use the member's ID (stored as a string, since JSON handles large integers poorly) instead of mentions or nicknames. This ensures warnings stay tied to the correct user even if they change their display name.
- Robust File Handling: The
load_warningsfunction gracefully handles missing or corrupted JSON files, so your bot won't crash unexpectedly. - Audit-Friendly Data: We store not just the warning reason, but also who issued it (both ID and name) and a UTC timestamp—perfect for later moderation reviews.
- Code Cleanup: I removed the duplicate
embed2since it was identical toembed—no need to repeat redundant code!
Quick Tips
- Ensure your bot has read/write permissions for the directory it's running in, so it can create and modify
warnings.json. - If you want to store the file in a specific folder, replace
'warnings.json'with an absolute path (like'./moderation_data/warnings.json'—just make sure the folder exists first). - Later, you could add a
checkwarnscommand to pull up a user's warning history using the sameload_warningsfunction!
内容的提问来源于stack exchange,提问作者Jack Mills
相关产品推荐
相关产品推荐

