-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Import/Export backups of collections in the database #3252
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
import asyncio | ||
import re | ||
import os | ||
from datetime import datetime, timezone | ||
from itertools import zip_longest | ||
from typing import Optional, Union, List, Tuple, Literal | ||
|
@@ -2186,6 +2187,56 @@ async def isenable(self, ctx): | |
|
||
return await ctx.send(embed=embed) | ||
|
||
@commands.command(name="export") | ||
@checks.has_permissions(PermissionLevel.ADMINISTRATOR) | ||
async def export_backup(self, ctx, collection_name): | ||
""" | ||
Export a backup of a collection in the form of a json file. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As noted in my other comment, we should store the backup as BSON file instead of JSON. Please change the references to BSON files instead. |
||
|
||
{prefix}export <collection_name> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The two usage examples, on L2196 and L2210, are unnecessary, since discord.py auto generates the usage spec. However, it might be useful to note in the import command's help doc that you should attach the backup file to the message. |
||
""" | ||
success_message, file = await self.bot.api.export_backups(collection_name) | ||
await ctx.send(success_message) | ||
await ctx.author.send(file=file) | ||
|
||
@commands.command(name="import") | ||
@checks.has_permissions(PermissionLevel.ADMINISTRATOR) | ||
async def import_backup(self, ctx): | ||
""" | ||
Import a backup from a json file. | ||
|
||
This will overwrite all data in the collection. | ||
|
||
{prefix}import <attach the json file> | ||
|
||
""" | ||
if len(ctx.message.attachments) == 1: | ||
attachment = ctx.message.attachments[0] | ||
await attachment.save(attachment.filename) | ||
file = discord.File(attachment.filename) | ||
collection_name = os.path.splitext(attachment.filename)[0] | ||
await ctx.send( | ||
f"This will overwrite all data in the {collection_name} collection. Are you sure you want to continue? (yes/no)" | ||
) | ||
try: | ||
msg = await self.bot.wait_for( | ||
"message", | ||
timeout=30, | ||
check=lambda m: m.author == ctx.author and m.channel.id == ctx.channel.id, | ||
) | ||
if msg.content.lower() == "yes": | ||
success_message = await self.bot.api.import_backups(collection_name, file) | ||
await ctx.send(success_message) | ||
os.remove(attachment.filename) | ||
else: | ||
return await ctx.send("Cancelled.") | ||
|
||
except asyncio.TimeoutError: | ||
return await ctx.send("You took too long to respond. Please try again.") | ||
|
||
else: | ||
return await ctx.send("Please attach 1 json file.") | ||
|
||
|
||
async def setup(bot): | ||
await bot.add_cog(Modmail(bot)) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,13 @@ | ||
import secrets | ||
import sys | ||
from json import JSONDecodeError | ||
import json | ||
from typing import Any, Dict, Union, Optional | ||
|
||
import discord | ||
from discord import Member, DMChannel, TextChannel, Message | ||
from discord.ext import commands | ||
|
||
from bson import ObjectId | ||
from aiohttp import ClientResponseError, ClientResponse | ||
from motor.motor_asyncio import AsyncIOMotorClient | ||
from pymongo.errors import ConfigurationError | ||
|
@@ -16,6 +17,13 @@ | |
logger = getLogger(__name__) | ||
|
||
|
||
class CustomJSONEncoder(json.JSONEncoder): | ||
def default(self, obj): | ||
if isinstance(obj, ObjectId): | ||
return str(obj) | ||
return super().default(obj) | ||
|
||
|
||
class GitHub: | ||
""" | ||
The client for interacting with GitHub API. | ||
|
@@ -751,6 +759,29 @@ async def get_user_info(self) -> Optional[dict]: | |
} | ||
} | ||
|
||
async def export_backups(self, collection_name: str): | ||
coll = self.db[collection_name] | ||
documents = [] | ||
async for document in coll.find(): | ||
documents.append(document) | ||
with open(f"{collection_name}.json", "w") as f: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don't write to disk, that may lead to potential issues. Use a |
||
json.dump(documents, f, cls=CustomJSONEncoder) | ||
with open(f"{collection_name}.json", "rb") as f: | ||
file = discord.File(f, f"{collection_name}.json") | ||
success_message = f"Exported {len(documents)} documents from {collection_name} to JSON. Check your DMs for the file." | ||
return success_message, file | ||
|
||
async def import_backups(self, collection_name: str, file: discord.File): | ||
contents = await self.bot.loop.run_in_executor(None, file.fp.read) | ||
documents = json.loads(contents.decode("utf-8")) | ||
coll = self.db[collection_name] | ||
await coll.delete_many({}) | ||
result = await coll.insert_many(documents) | ||
success_message = ( | ||
f"Imported {len(result.inserted_ids)} documents from {file.filename} into {collection_name}." | ||
) | ||
return success_message | ||
Comment on lines
+762
to
+783
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Instead of JSON, MongoDB stores data using BSON. Perhaps we can do something similar to this gist? This way, some other native MongoDB types can be saved, and you wouldn't need the custom JSON encoder. |
||
|
||
|
||
class PluginDatabaseClient: | ||
def __init__(self, bot): | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of exporting a collection, most users doesn't know what even are collections. Could you change it so that it exports everything (into one file) and imports them as well?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You mean export config/logs and any plugins into 1 bson file? The issue with that would be the bot wont be able to send the large files.