Skip to content
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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,6 @@ async def get_or_fetch_user(self, id: int) -> discord.User:
return self.get_user(id) or await self.fetch_user(id)

async def retrieve_emoji(self) -> typing.Tuple[str, str]:

sent_emoji = self.config["sent_emoji"]
blocked_emoji = self.config["blocked_emoji"]

Expand Down Expand Up @@ -731,7 +730,6 @@ def check_manual_blocked_roles(self, author: discord.Member) -> bool:
if isinstance(author, discord.Member):
for r in author.roles:
if str(r.id) in self.blocked_roles:

blocked_reason = self.blocked_roles.get(str(r.id)) or ""

try:
Expand Down Expand Up @@ -790,7 +788,6 @@ async def is_blocked(
channel: discord.TextChannel = None,
send_message: bool = False,
) -> bool:

member = self.guild.get_member(author.id)
if member is None:
# try to find in other guilds
Expand Down
51 changes: 51 additions & 0 deletions cogs/modmail.py
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
Expand Down Expand Up @@ -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):
Copy link
Collaborator

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?

Copy link
Author

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.

"""
Export a backup of a collection in the form of a json file.
Copy link
Collaborator

Choose a reason for hiding this comment

The 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>
Copy link
Collaborator

Choose a reason for hiding this comment

The 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))
2 changes: 0 additions & 2 deletions cogs/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,6 @@ async def load_plugin(self, plugin):
raise InvalidPluginError("Cannot load extension, plugin invalid.") from exc

async def parse_user_input(self, ctx, plugin_name, check_version=False):

if not self.bot.config["enable_plugins"]:
embed = discord.Embed(
description="Plugins are disabled, enable them by setting `ENABLE_PLUGINS=true`",
Expand Down Expand Up @@ -380,7 +379,6 @@ async def plugins_add(self, ctx, *, plugin_name: str):
await self.bot.config.update()

if self.bot.config.get("enable_plugins"):

invalidate_caches()

try:
Expand Down
1 change: 0 additions & 1 deletion cogs/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -599,7 +599,6 @@ async def status(self, ctx, *, status_type: str.lower):
return await ctx.send(embed=embed)

async def set_presence(self, *, status=None, activity_type=None, activity_message=None):

if status is None:
status = self.bot.config.get("status")

Expand Down
33 changes: 32 additions & 1 deletion core/clients.py
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
Expand All @@ -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.
Expand Down Expand Up @@ -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:
Copy link
Collaborator

Choose a reason for hiding this comment

The 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 BytesIO instead.

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
Copy link
Collaborator

Choose a reason for hiding this comment

The 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):
Expand Down
1 change: 0 additions & 1 deletion core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@


class ConfigManager:

public_keys = {
# activity
"twitch_url": "https://www.twitch.tv/discordmodmail/",
Expand Down
1 change: 0 additions & 1 deletion core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,6 @@ async def convert(self, ctx, argument):
try:
return await super().convert(ctx, argument)
except commands.ChannelNotFound:

if guild:
categories = {c.name.casefold(): c for c in guild.categories}
else:
Expand Down
2 changes: 0 additions & 2 deletions core/thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -716,7 +716,6 @@ async def delete_message(
async def find_linked_message_from_dm(
self, message, either_direction=False, get_thread_channel=False
) -> typing.List[discord.Message]:

joint_id = None
if either_direction:
joint_id = get_joint_id(message)
Expand Down Expand Up @@ -909,7 +908,6 @@ async def send(
persistent_note: bool = False,
thread_creation: bool = False,
) -> None:

if not note and from_mod:
self.bot.loop.create_task(self._restart_close_timer()) # Start or restart thread auto close

Expand Down