Exemple #1
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)
Exemple #2
0
 def save_infos(self):
     json_data = {}
     delta = datetime.now() - self.bot.launched_at
     json_data["total runtime"] = int((self.bot.total_runtime + delta).total_seconds())
     json_data["total commands"] = self.bot.total_commands
     json_data["created at"] = self.bot.created_at.strftime("%d/%m/%Y %H:%M:%S")
     utils.save_json(json_data, self.bot.info_file_path)
Exemple #3
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
Exemple #4
0
 def set_user_sub_config(self, user: discord.Member, sub_config_name: str,
                         attribute: str, value):
     if user.id not in self.users_configuration:
         self.users_configuration[user.id] = {}
     if sub_config_name not in self.users_configuration[user.id]:
         self.users_configuration[user.id][sub_config_name] = {}
     self.users_configuration[user.id][sub_config_name][attribute] = value
     utils.save_json(self.users_configuration,
                     self.users_configuration_path)
Exemple #5
0
 async def reset(self, ctx):
     """Resets your configuration"""
     if ctx.message.author.id in self.users_configuration:
         del self.users_configuration[ctx.message.author.id]
         utils.save_json(self.users_configuration,
                         self.users_configuration_path)
         await ctx.channel.send("Done.")
     else:
         await ctx.channel.send("You hadn't any configured settings.")
Exemple #6
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)
Exemple #7
0
    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)
Exemple #8
0
    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)
Exemple #9
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)
Exemple #10
0
    async def add_blacklist_id(self, ctx, user_id: int):
        """Adds an user to the bot's blacklist using his ID
        Parameters:
            user_id: The ID of the user you want to add to the bot's blacklist.

        Example: [p]add_blacklist_id 346654353341546499"""
        if user_id not in self.bot.blacklist:
            self.bot.blacklist.append(user_id)
            utils.save_json(self.bot.blacklist, self.bot.blacklist_file_path)
            await ctx.channel.send("Done.")
        else:
            await ctx.channel.send("This ID is already in the blacklist.")
Exemple #11
0
 async def load(self, module : str):
     """Loads a module."""
     try:
         self.bot.load_extension("modules." + module)
         self.bot.loaded_modules.append(module)
         utils.save_json(self.bot.loaded_modules, self.bot.modules_file_path)
     except Exception as e:
         await self.bot.say('\U0001f52b')
         await self.bot.say(str(e))
     else:
         await self.bot.say('\U0001f44c')
         print(module + " loaded.")
Exemple #12
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"]
Exemple #13
0
    async def rem_blacklist_id(self, user_id: str):
        """Removes an user from the bot's blacklist using his ID
        Parameters:
            user_id: The ID of the user you want to to remove from the bot's blacklist.

        Example: [p]rem_blacklist @AGoodGuyUnfairlyBlacklisted"""
        if user_id in self.bot.blacklist:
            self.bot.blacklist.remove(user_id)
            utils.save_json(self.bot.blacklist, self.bot.blacklist_file_path)
            await self.bot.say("Done.")
        else:
            await self.bot.say("This ID wasn't even in the blacklist.")
Exemple #14
0
    async def remove_blacklist(self, ctx, user: discord.Member):
        """Removes an user from the bot's blacklist
        Parameters:
            user: The user you want to remove from the bot's blacklist.

        Example: [p]rem_blacklist @AGoodGuyUnfairlyBlacklisted"""
        if user.id in self.bot.blacklist:
            self.bot.blacklist.remove(user.id)
            utils.save_json(self.bot.blacklist, self.bot.blacklist_file_path)
            await ctx.channel.send("Done.")
        else:
            await ctx.channel.send("This user wasn't even blacklisted.")
Exemple #15
0
    async def add_blacklist(self, user: discord.Member):
        """Adds an user to the bot's blacklist
        Parameters:
            user: The user you want to add to the bot's blacklist.

        Example: [p]add_blacklist @AVeryMeanUser"""
        if user.id not in self.bot.blacklist:
            self.bot.blacklist.append(user.id)
            utils.save_json(self.bot.blacklist, self.bot.blacklist_file_path)
            await self.bot.say("Done.")
        else:
            await self.bot.say(user.name + "#" + user.discriminator + " (" + \
                user.id + ") is already blacklisted.")
Exemple #16
0
 def save_servers_config(self):
     """Saves the servers configuration"""
     json_data = {}
     for server in self.servers_config:
         json_data[server] = {}
         for role_id in self.servers_config[server]:
             role_config = self.servers_config[server][role_id]
             json_data[server][role_id] = { \
                                     "assign-conditions": role_config["assign-conditions"], \
                                     "assign-expression": role_config["assign-expression"], \
                                     "removal-conditions": role_config["removal-conditions"], \
                                     "removal-expression": role_config["removal-expression"] \
                                       }
     utils.save_json(json_data, self.servers_config_file_path)
Exemple #17
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()
 async def load(self, ctx, module: str):
     """Loads a module."""
     try:
         self.bot.load_extension("modules." + module)
         if module not in self.bot.loaded_modules:
             self.bot.loaded_modules.append(module)
             utils.save_json(self.bot.loaded_modules,
                             self.bot.modules_file_path)
     except Exception:
         tb = traceback.format_exc()
         await ctx.channel.send("\U0001f52b\n```" + tb + "```")
     else:
         await ctx.channel.send('\U0001f44c')
         print(module + " loaded.")
Exemple #19
0
    def reset_infos(self):
        """Resets bot's info"""
        json_data = {}
        json_data["created at"] = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
        json_data["total commands"] = 0
        json_data["total runtime"] = 0
        self.created_at = datetime.now()
        self.total_commands = 0
        self.total_runtime = timedelta(seconds=0)

        # Shouldn't be call, except if the user deletes this folder
        if not os.path.isdir("settings"):
            os.makedirs("settings")

        utils.save_json(json_data, self.info_file_path)
Exemple #20
0
 def save_servers_config(self):
     """Saves the configuration"""
     self.servers_config["id counter"] = Log.id_counter
     data = copy.deepcopy(self.servers_config)
     for server in data["servers"]:
         if "log channel" in data["servers"][server]:
             data["servers"][server]["log channel"] = data["servers"][server]["log channel"].id
         if "logs" in data["servers"][server]:
             logs = {}
             for user_id in data["servers"][server]["logs"]:
                 logs[user_id] = []
                 for log in data["servers"][server]["logs"][user_id]:
                     logs[user_id].append(log.get_save())
             data["servers"][server]["logs"] = logs
     utils.save_json(data, self.servers_config_file_path)
Exemple #21
0
 async def unload(self, module : str):
     """Unloads a module."""
     if module in self.bot.loaded_modules:
         try:
             self.bot.unload_extension("modules." + module)
             self.bot.loaded_modules.remove(module)
             utils.save_json(self.bot.loaded_modules, self.bot.modules_file_path)
         except Exception as e:
             await self.bot.say('\U0001f52b')
             await self.bot.say(str(e))
         else:
             await self.bot.say('\U0001f44c')
             print(module + " unloaded.")
     else:
         await self.bot.say("This module isn't even loaded")
 async def unload(self, ctx, module: str):
     """Unloads a module."""
     if module in self.bot.loaded_modules:
         try:
             self.bot.unload_extension("modules." + module)
             self.bot.loaded_modules.remove(module)
             utils.save_json(self.bot.loaded_modules,
                             self.bot.modules_file_path)
         except Exception:
             tb = traceback.format_exc()
             await ctx.channel.send("\U0001f52b\n```" + tb + "```")
         else:
             await ctx.channel.send('\U0001f44c')
             print(module + " unloaded.")
     else:
         await ctx.channel.send("This module isn't even loaded")
Exemple #23
0
    def reset_infos(self):
        """Resets bot's info"""
        json_data = {}
        json_data["created at"] = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
        json_data["total commands"] = 0
        json_data["total runtime"] = 0
        self.created_at = datetime.now()
        self.total_commands = 0
        self.total_runtime = timedelta(seconds=0)

        # Ne devrait pas être nécessaire étant donné que load_config
        # est appelé juste avant mais on ne sait jamais...
        if not os.path.isdir("settings"):
            os.makedirs("settings")

        utils.save_json(json_data, self.info_file_path)
Exemple #24
0
    async def reload(self, module: str):
        """Reloads a module."""
        try:
            if module in self.bot.loaded_modules:
                self.bot.unload_extension("modules." + module)
                self.bot.loaded_modules.remove(module)
                utils.save_json(self.bot.loaded_modules,
                                self.bot.modules_file_path)

            self.bot.load_extension("modules." + module)
            self.bot.loaded_modules.append(module)
            utils.save_json(self.bot.loaded_modules, self.bot.modules_file_path)
        except Exception:
            tb = traceback.format_exc()
            await self.bot.say("\U0001f52b\n```" + tb + "```")
        else:
            await self.bot.say('\U0001f44c')
            print(module + " reloaded.")
Exemple #25
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"]
Exemple #26
0
    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
Exemple #27
0
 def save_b1nzy_banlist(self):
     """Saves the b1nzy banlist"""
     utils.save_json(self.b1nzy_banlist, self.b1nzy_banlist_path)
Exemple #28
0
 def save_moderators(self):
     """Saves the moderators"""
     utils.save_json(self.bot.moderators, self.bot.moderators_file_path)
Exemple #29
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()
Exemple #30
0
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()