Ejemplo n.º 1
0
    def load_servers_config(self):
        """Loads the servers configuration"""
        if not os.path.exists(self.servers_config_file_path):

            if not os.path.isdir("data/roles"):
                os.makedirs("data/roles")

            utils.save_json(self.servers_config, self.servers_config_file_path)
        else:
            data = utils.load_json(self.servers_config_file_path)
            for server_id in data:
                self.servers_config[server_id] = {}
                for role_id in data[server_id]:
                    role = data[server_id][role_id]
                    self.servers_config[server_id][role_id] = role
                    assign_functions = []
                    for cond in role["assign-conditions"]:
                        assign_functions.append(
                            partial(CONDITIONS[cond[0]]["function"], cond[1]))
                    self.servers_config[server_id][role_id][
                        "assign-functions"] = assign_functions
                    removal_functions = []
                    for cond in role["removal-conditions"]:
                        removal_functions.append(
                            partial(CONDITIONS[cond[0]]["function"], cond[1]))
                    self.servers_config[server_id][role_id][
                        "removal-functions"] = removal_functions
Ejemplo n.º 2
0
    def load_modules(self):
        """Loads the bot modules"""
        # Première lancement du bot ou édition manuelle de l'utilisateur
        if not os.path.exists(self.modules_file_path):
            json_data = self.default_modules
            self.modules = self.default_modules
            utils.save_json(json_data, self.modules_file_path)

        print("\n\n")
        self.modules = utils.load_json(self.modules_file_path)
        to_remove = []
        for mod in self.modules:
            module_path = "modules/" + mod + ".py"
            module_name = module_path.replace('/', '.')[:-3]
            if not os.path.exists(module_path):
                print("\n\nThe module \"" + mod + "\" doesn't exist!")
                to_remove.append(mod)
            else:
                try:
                    print("Loading " + mod + " module...")
                    module = importlib.import_module(
                        module_path.replace('/', '.')[:-3])
                    importlib.reload(module)
                    super().load_extension(module_name)
                    self.loaded_modules.append(mod)
                except SyntaxError as ex:
                    print("Error in " + mod + " module:\n\n" + str(ex) +
                          "\n\n")
                    to_remove.append(mod)
        for mod in to_remove:
            self.modules.remove(mod)
        if to_remove:
            utils.save_json(self.modules, self.modules_file_path)
Ejemplo n.º 3
0
    def __init__(self, bot):
        self.bot = bot
        self.timeout = 15
        self.data_folder_path = "data/code/"
        self.prefix = bot.get_prefix
        self.pastebin_api_key_file_path = self.data_folder_path + \
            "pastebin_key.txt"
        self.users_configuration_path = self.data_folder_path + \
            "users_configuration.json"
        self.languages_identifiers_file_path = self.data_folder_path + \
            "languages_identifiers.json"
        self.default_engines_file_path = self.data_folder_path + \
            "default_engines.json"
        self.languages_images_file_path = self.data_folder_path + \
            "languages_images.json"
        self.languages_files_extensions_file_path = self.data_folder_path + \
            "languages_files_extensions.json"
        self.users_configuration = {}
        self.load_pastebin_api_key()
        self.load_users_configuration()

        # Elements are list in case some extensions can be used.
        # Lazy K isn't supported yet (as this language use the character `,
        # it looks really ugly on Discord).
        self.languages_identifiers = utils.load_json(
            self.languages_identifiers_file_path)

        # The first element is the template name and the second one is the
        # engine name
        self.default_engines = utils.load_json(self.default_engines_file_path)

        # Languages logos
        self.languages_images = utils.load_json(
            self.languages_images_file_path)

        # Languages files extensions
        # https://fileinfo.com/filetypes/developer
        # https://www.wikiwand.com/en/List_of_file_formats
        # The first element must be the extension used in the
        # parameter "display-compile-command" for every language
        self.languages_files_extensions = utils.load_json(
            self.languages_files_extensions_file_path)

        self.configuration = {}
        self.load_info()
Ejemplo n.º 4
0
    def load_blacklist(self):
        """Loads the blacklist"""
        if not os.path.exists(self.blacklist_file_path):
            if not os.path.isdir("settings"):
                os.makedirs("settings")

            utils.save_json(self.blacklist, self.blacklist_file_path)
        else:
            self.blacklist = utils.load_json(self.blacklist_file_path)
Ejemplo n.º 5
0
Archivo: admin.py Proyecto: Asurixx/Bot
    def load_moderators(self):
        """Loads the moderators"""
        if not os.path.exists(self.bot.moderators_file_path):

            if not os.path.isdir("data/admin"):
                os.makedirs("data/admin")

            utils.save_json(self.bot.moderators, self.bot.moderators_file_path)
        else:
            self.bot.moderators = utils.load_json(self.bot.moderators_file_path)
Ejemplo n.º 6
0
Archivo: admin.py Proyecto: Asurixx/Bot
    def load_b1nzy_banlist(self):
        """Loads the b1nzy banlist"""
        if not os.path.exists(self.b1nzy_banlist_path):

            if not os.path.isdir("data/admin"):
                os.makedirs("data/admin")

            utils.save_json(self.b1nzy_banlist, self.b1nzy_banlist_path)
        else:
            self.b1nzy_banlist = utils.load_json(self.b1nzy_banlist_path)
Ejemplo n.º 7
0
    def load_users_configuration(self):
        """Loads the users configuration"""
        if not os.path.exists(self.users_configuration_path):
            if not os.path.isdir("data/code"):
                os.makedirs("data/code")

            utils.save_json(self.users_configuration,
                            self.users_configuration_path)
        else:
            self.users_configuration = utils.load_json(
                self.users_configuration_path)
Ejemplo n.º 8
0
    def load_config(self):
        """Loads self.config_file_path, gets the infos if the file
        doesn't exists"""
        if not os.path.exists(self.config_file_path):

            json_data = {}
            token = input("Please put your bot's token here:\n> ")
            print("DO NOT SPREAD YOUR bot'S TOKEN TO ANYONE. NEVER.\n")
            prefix = input("\n\nPlease put your bot's prefix here:\n> ")
            description = input(
                "\n\nPlease put a little description "
                "for your bot (optionnal)\n> "
            )
            if description == "":
                description = (
                    "A bot that runs code.\nIf you have any "
                    "problem with Discode or if you just want "
                    "to be in the development server, you can "
                    "join it using this link: discord.gg/UpYc98d"
                )
            owner_id = int(input("\n\nPlease put your ID:\n> "))

            json_data["token"] = token
            json_data["prefix"] = prefix
            json_data["description"] = description
            json_data["owner id"] = owner_id
            self.token = token
            self.prefix = prefix
            self.description = description
            self.owner_id = owner_id

            if not os.path.isdir("settings"):
                os.makedirs("settings")

            utils.save_json(json_data, self.config_file_path)

        else:
            json_data = utils.load_json(self.config_file_path)
            if "token" not in json_data or "prefix" not in json_data \
                    or "description" not in json_data \
                    or "owner id" not in json_data:
                print(
                    "\"settings/config.json\" is incorrect! "
                    "The bot will be reseted, "
                    "please restart the bot!"
                )
                os.remove(self.config_file_path)
                sys.exit(1)
            else:
                self.token = json_data["token"]
                self.prefix = json_data["prefix"]
                self.description = json_data["description"]
                self.owner_id = json_data["owner id"]
Ejemplo n.º 9
0
    def load_communications_file(self):
        """Loads self.communications_file_path in self.communications"""
        self.communications = {}
        if not os.path.exists(self.communications_file_path):

            if not os.path.isdir("data/communications"):
                os.makedirs("data/communications")

            utils.save_json(self.communications, self.communications_file_path)
        else:
            conv = utils.load_json(self.communications_file_path)
            for com in conv:
                self.communications[com] = Conversation(conv[com])
            self.parse_communications()
Ejemplo n.º 10
0
 def load_infos(self):
     """Load bot's info"""
     # Premier lancement du bot ou édition manuelle de l'utilisateur
     if not os.path.exists(self.info_file_path):
         self.reset_infos()
     else:
         json_data = utils.load_json(self.info_file_path)
         if not "created at" in json_data or not "total commands" in json_data \
                                         or not "total runtime" in json_data:
             print("\"settings/infos.json\" is incorrect! The info of " + \
                 "the bot will be reseted!")
             self.reset_infos()
         else:
             self.created_at = datetime.strptime(json_data["created at"], "%d/%m/%Y %H:%M:%S")
             self.total_commands = json_data["total commands"]
             self.total_runtime = timedelta(seconds=json_data["total runtime"])
Ejemplo n.º 11
0
 def load_infos(self):
     """Load bot's info"""
     if not os.path.exists(self.info_file_path):
         self.reset_infos()
     else:
         json_data = utils.load_json(self.info_file_path)
         if "created at" not in json_data or "total commands" \
                 not in json_data or "total runtime" not in json_data:
             print("\"settings/infos.json\" is incorrect! The info of "
                   "the bot will be reseted!")
             self.reset_infos()
         else:
             self.created_at = datetime.strptime(json_data["created at"],
                                                 "%d/%m/%Y %H:%M:%S")
             self.total_commands = json_data["total commands"]
             self.total_runtime = timedelta(
                 seconds=json_data["total runtime"])
Ejemplo n.º 12
0
    def load_config(self):
        """Loads self.config_file_path, gets the infos if the file doesn't exists"""
        # Premier lancement du bot ou édition manuelle de l'utilisateur
        if not os.path.exists(self.config_file_path):

            json_data = {}
            token = input("Please put your bot's token here:\n> ")
            print("DO NOT SPREAD YOUR bot'S TOKEN TO ANYONE. NEVER.\n")
            prefix = input("\n\nPlease put your bot's prefix here:\n> ")
            description = input(
                "\n\nPlease put a little description for your bot (optionnal)\n> "
            )
            if description == "":
                description = "A basic bot originally made for Asurix#4727"
            owner_id = input("\n\nPlease put your ID:\n> ")

            json_data["token"] = token
            json_data["prefix"] = prefix
            json_data["description"] = description
            json_data["owner id"] = owner_id
            self.token = token
            self.prefix = prefix
            self.description = description
            self.owner_id = owner_id

            if not os.path.isdir("settings"):
                os.makedirs("settings")

            utils.save_json(json_data, self.config_file_path)

        else:
            json_data = utils.load_json(self.config_file_path)
            if not "token" in json_data or not "prefix" in json_data \
            or not "description" in json_data or not "owner id" in json_data:
                print("\"settings/config.json\" is incorrect! The bot will be reseted, " \
                        + "please restart the bot!")
                os.remove(self.config_file_path)
                sys.exit(1)
            else:
                self.token = json_data["token"]
                self.prefix = json_data["prefix"]
                self.description = json_data["description"]
                self.owner_id = json_data["owner id"]
Ejemplo n.º 13
0
Archivo: admin.py Proyecto: Asurixx/Bot
    def load_servers_config(self):
        """Loads the configuration"""
        #pylint: disable=too-many-nested-blocks
        if not os.path.exists(self.servers_config_file_path):

            if not os.path.isdir("data/admin"):
                os.makedirs("data/admin")

            self.servers_config["id counter"] = 1
            self.servers_config["servers"] = {}
            Log.id_counter = 1
            utils.save_json(self.servers_config, self.servers_config_file_path)
        else:
            data = utils.load_json(self.servers_config_file_path)
            for server in data["servers"]:
                if "log channel" in data["servers"][server]:
                    data["servers"][server]["log channel"] = discord.utils.find(lambda c, s=server:\
                            c.id == data["servers"][s]["log channel"], self.bot.get_all_channels())
                if "logs" in data["servers"][server]:
                    logs = {}
                    known_admins = {}
                    for user_id in data["servers"][server]["logs"]:
                        member = discord.utils.find(lambda m, u=user_id: m.id == u, \
                                                    self.bot.get_all_members())
                        logs[user_id] = []
                        for log in data["servers"][server]["logs"][user_id]:
                            if log["responsible"] not in known_admins:
                                responsible = discord.utils.find(lambda r, l=log: \
                                        r.id == l["responsible"], self.bot.get_all_members())
                                known_admins[log["responsible"]] = responsible
                            else:
                                responsible = known_admins[log["responsible"]]
                            logs[user_id].append(Log(log_type=log["type"],
                                                     member_id=member.id if member else "UNKNOWN",
                                                     responsible_id=responsible.id,
                                                     reason=log["reason"],
                                                     date=log["date"]))
                    data["servers"][server]["logs"] = logs
            Log.id_counter = data["id counter"]
            self.servers_config = data
Ejemplo n.º 14
0
Archivo: run.py Proyecto: Asurixx/Bot
def run_bot():
    """Runs the bot"""

    logger = logging.getLogger('discord')
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler(filename="discord.log", encoding='utf-8', mode='w')
    handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
    logger.addHandler(handler)
    loop = asyncio.new_event_loop()
    asyncio.get_event_loop()

    bot = AsurixBot(loop)

    @bot.event
    async def on_ready():
        """Triggers when the bot just logged in"""
        #pylint: disable=unused-variable
        print("Logged in as " + bot.user.name + "#" + bot.user.discriminator)
        print(str(len(bot.servers))+ " servers")
        print(str(len(set(bot.get_all_channels()))) + " channels")
        print(str(len(set(bot.get_all_members()))) + " members")
        bot.invite_link = "https://discordapp.com/oauth2/authorize?client_id=" \
                            + bot.user.id + "&scope=bot"
        print("\nHere's the invitation link for your bot: " + bot.invite_link)
        bot.load_modules()
        bot.launched_at = datetime.now()
        print("\n" + str(len(bot.loaded_modules)) + " modules loaded.")

    @bot.event
    async def on_command(command, ctx):
        """Triggers AFTER a command is called"""
        #pylint: disable=unused-argument
        #pylint: disable=unused-variable
        bot.total_commands += 1

    @bot.event
    async def on_message(message):
        #pylint: disable=unused-variable
        """Triggers when the bot reads a new message"""
        if message.author.id not in bot.blacklist:
            await bot.process_commands(message)

    try:
        loop.run_until_complete(bot.run(bot.token, reconnect=True))
    except discord.LoginFailure:
        print("Couldn't log in, your bot's token might be incorrect! If it's not, "\
                + "then check Discord's status here: https://status.discordapp.com/")
        answer = input("Do you want to change your bot's token? (yes/no)\n> ")
        if answer.upper() == "YES":
            token = input("\n\nPlease put your new bot's token here:\n> ")
            json_data = utils.load_json("settings/infos.json")
            json_data["token"] = token
            bot.token = token
            utils.save_json(json_data, "settings/infos.json")
    except KeyboardInterrupt:
        loop.run_util_complete(bot.close())
    except discord.GatewayNotFound:
        print("Gateway not found! The problem comes from Discord.")
        sys.exit(1)
    except discord.ConnectionClosed:
        print("No more connection.")
        loop.run_util_complete(bot.close())
        sys.exit(1)
    except discord.HTTPException:
        print("HTTP Error.")
        sys.exit(1)
    finally:
        loop.close()
Ejemplo n.º 15
0
def run_bot():
    """Runs the bot"""

    loop = asyncio.get_event_loop()

    bot = Discode(loop)

    @bot.event
    async def on_ready():
        """Triggers when the bot just logged in"""

        print("Logged in as " + bot.user.name + "#" + bot.user.discriminator)
        print(str(len(bot.guilds)) + " servers")
        print(str(len(set(bot.get_all_channels()))) + " channels")
        print(str(len(set(bot.get_all_members()))) + " members")
        bot.invite_link = "https://discordapp.com/oauth2/authorize?client_id="\
            + str(bot.user.id) + "&scope=bot"
        print("\nHere's the invitation link for your bot: " + bot.invite_link)
        bot.load_modules()
        bot.launched_at = datetime.now()
        print("\n" + str(len(bot.loaded_modules)) + " modules loaded.")

    @bot.event
    async def on_command(ctx):
        """Triggers AFTER a command is called"""
        bot.total_commands += 1

    @bot.event
    async def on_message(message):
        """Triggers when the bot reads a new message"""
        if message.author.id not in bot.blacklist:
            if message.content.startswith(bot.prefix + "code```"):
                await bot.send_message(
                    destination=message.channel,
                    content="https://i.imgur.com/eGMJXqg.png")
            else:
                await bot.process_commands(message)

    @bot.event
    async def on_command_error(ctx, error):
        await ctx.message.channel.send(error)

    try:
        bot.run(bot.token, reconnect=True)
    except discord.LoginFailure:
        print(
            "Couldn't log in, your bot's token might be incorrect! "
            "If it's not, then check Discord's status here: "
            "https://status.discordapp.com/"
        )
        answer = input("Do you want to change your bot's token? (yes/no)\n> ")
        if answer.upper() == "YES":
            token = input("\n\nPlease put your new bot's token here:\n> ")
            json_data = utils.load_json("settings/infos.json")
            json_data["token"] = token
            bot.token = token
            utils.save_json(json_data, "settings/infos.json")
    except KeyboardInterrupt:
        loop.run_util_complete(bot.close())
    except discord.GatewayNotFound:
        print("Gateway not found! The problem comes from Discord.")
        sys.exit(1)
    except discord.ConnectionClosed:
        print("No more connection.")
        loop.run_util_complete(bot.close())
        sys.exit(1)
    except discord.HTTPException:
        print("HTTP Error.")
        loop.run_util_complete(bot.close())
        sys.exit(1)
    except Exception as e:
        print(e)
        loop.run_util_complete(bot.close())
        sys.exit(1)
    finally:
        loop.close()