Ejemplo n.º 1
0
 def write_volume(self):
     """Writes the current volume to the data.json"""
     # Update the volume
     data = datatools.get_data()
     data["discord"]["servers"][self.server_id][
         _data.modulename]["volume"] = self.volume
     datatools.write_data(data)
Ejemplo n.º 2
0
async def warn_user(channel, user):
    """
    Gives a user a warning, and bans them if they are over the maximum warnings

    Args:
        channel: The channel to send the warning message in
        user: The user to give the warning to
    """

    data = datatools.get_data()
    server_id = channel.server.id

    if "warnings_max" not in data["discord"]["servers"][server_id][_data.modulename]:
        data["discord"]["servers"][server_id][_data.modulename]["warnings_max"] = 3
    if "warnings" not in data["discord"]["servers"][server_id][_data.modulename]:
        data["discord"]["servers"][server_id][_data.modulename]["warnings"] = {}

    if user.id in data["discord"]["servers"][server_id][_data.modulename]["warnings"]:
        data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] += 1
    else:
        data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] = 1

    datatools.write_data(data)

    warnings = data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id]
    max_warnings = data["discord"]["servers"][server_id][_data.modulename]["warnings_max"]

    await client.send_typing(channel)
    embed = ui_embed.user_warning(channel, user, warnings, max_warnings)
    await embed.send()

    if warnings >= max_warnings:
        await ban_user(channel, user)
Ejemplo n.º 3
0
async def activate_module(channel, module_name, activate):
    """
    Changes a modules activated/deactivated state for a server

    Args:
        channel: The channel to send the message to
        module_name: The name of the module to change state for
        activate: The activated/deactivated state of the module
    """

    data = datatools.get_data()
    server_id = channel.server.id

    _dir = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
    _dir_modules = "{}/../".format(_dir)
    if not os.path.isfile("{}/{}/_data.py".format(_dir_modules, module_name)):
        await client.send_typing(channel)
        embed = ui_embed.error(channel, "Error", "No module found named '{}'".format(module_name))
        await embed.send()
        return

    try:
        import_name = ".discord_modis.modules.{}.{}".format(module_name, "_data")
        module_data = importlib.import_module(import_name, "modis")

        # Don't try and deactivate this module (not that it would do anything)
        if module_data.modulename == _data.modulename:
            await client.send_typing(channel)
            embed = ui_embed.error(channel, "Error", "I'm sorry, Dave. I'm afraid I can't do that.")
            await embed.send()
            return

        # This /should/ never happen if everything goes well
        if module_data.modulename not in data["discord"]["servers"][server_id]:
            await client.send_typing(channel)
            embed = ui_embed.error(channel, "Error",
                                   "No data found for module '{}'".format(module_data.modulename))
            await embed.send()
            return

        # Modify the module
        if "activated" in data["discord"]["servers"][server_id][module_data.modulename]:
            data["discord"]["servers"][server_id][module_data.modulename]["activated"] = activate
            # Write the data
            datatools.write_data(data)

            await client.send_typing(channel)
            embed = ui_embed.modify_module(channel, module_data.modulename, activate)
            await embed.send()
            return
        else:
            await client.send_typing(channel)
            embed = ui_embed.error(channel, "Error", "Can't deactivate module '{}'".format(module_data.modulename))
            await embed.send()
            return
    except Exception as e:
        logger.error("Could not modify module {}".format(module_name))
        logger.exception(e)
Ejemplo n.º 4
0
async def on_message(message):
    """The on_message event handler for this module

    Args:
        message (discord.Message): Input message
    """

    # Simplify message info
    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    if not data["discord"]["servers"][server.id][
            _data.modulename]["activated"]:
        return

    # Only reply to server messages and don't reply to myself
    if server is not None and author != channel.server.me:
        # Only reply to mentions
        if channel.server.me in message.mentions:

            logger.info("Bot was mentioned, summoning Mitsuku")
            await client.send_typing(channel)

            # Get new botcust2 from Mitsuku if does not exist for channel in serverdata
            if channel.id not in data["discord"]["servers"][server.id][
                    _data.modulename]["channels"]:
                new_serverdata = data
                new_serverdata["discord"]["servers"][server.id][_data.modulename]["channels"][channel.id] = \
                    api_mitsuku.get_botcust2()
                datatools.write_data(new_serverdata)

            # Get botcust2 from serverdata
            botcust2 = data["discord"]["servers"][server.id][
                _data.modulename]["channels"][channel.id]

            # Remove mention from message content so Mitsuku doesn't see it
            content = content.replace(
                "<@{}>".format(str(channel.server.me.id)), ' ')
            content = content.replace(
                "<@!{}>".format(str(channel.server.me.id)), ' ')

            # Send Mitsuku's reply
            if botcust2:
                response = api_mitsuku.query(botcust2, content)
                if response:
                    await client.send_message(channel, response)
                else:
                    await client.send_message(
                        channel,
                        "```Couldn't get readable response from Mitsuku.```")
            else:
                await client.send_message(
                    channel, "```Couldn't initialise with Mitsuku.```")
Ejemplo n.º 5
0
    async def set_topic_channel(self, channel):
        """Set the topic channel for this server"""
        data = datatools.get_data()
        data["discord"]["servers"][self.server_id][
            _data.modulename]["topic_id"] = channel.id
        datatools.write_data(data)

        self.topicchannel = channel
        await self.set_topic(self.topic)

        await client.send_typing(channel)
        embed = ui_embed.topic_update(channel, self.topicchannel)
        await embed.send()
Ejemplo n.º 6
0
def remove_server_data(server_id):
    """
    Remove a server from the server data

    Args:
        server_id (int): The server to remove from the server data
    """

    logger.debug("Removing server from serverdata")
    # Remove the server from data
    data = datatools.get_data()
    if server_id in data["discord"]["servers"]:
        data["discord"]["servers"].pop(server_id)
        datatools.write_data(data)
Ejemplo n.º 7
0
    async def clear_topic_channel(self, channel):
        """Set the topic channel for this server"""
        try:
            if self.topicchannel:
                await client.edit_channel(self.topicchannel, topic="")
        except Exception as e:
            logger.exception(e)

        self.topicchannel = None
        logger.debug("Clearing topic channel")

        data = datatools.get_data()
        data["discord"]["servers"][self.server_id][
            _data.modulename]["topic_id"] = ""
        datatools.write_data(data)

        await client.send_typing(channel)
        embed = ui_embed.topic_update(channel, self.topicchannel)
        await embed.send()
Ejemplo n.º 8
0
async def ban_user(channel, user):
    """
    Bans a user from a server

    Args:
        channel: The channel to send the warning message in
        user: The user to give the warning to
    """

    data = datatools.get_data()
    server_id = channel.server.id

    try:
        await client.ban(user)
    except discord.errors.Forbidden:
        await client.send_typing(channel)
        embed = ui_embed.error(channel, "Ban Error", "I do not have the permissions to ban that person.")
        await embed.send()
        return

    # Set the user's warnings to 0
    if "warnings" in data["discord"]["servers"][server_id][_data.modulename]:
        if user.id in data["discord"]["servers"][server_id][_data.modulename]["warnings"]:
            data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] = 0
            datatools.write_data(data)

    await client.send_typing(channel)
    embed = ui_embed.user_ban(channel, user)
    await embed.send()

    try:
        response = "You have been banned from the server '{}' " \
                   "contact the owners to resolve this issue.".format(channel.server.name)
        await client.send_message(user, response)
    except Exception as e:
        logger.exception(e)
Ejemplo n.º 9
0
async def update_server_data(server):
    """
    Updates the server info for the given server

    Args:
        server: The Discord server to update info for
    """

    data = datatools.get_data()
    # Add the server to server data if it doesn't yet exist
    send_welcome_message = False
    if server.id not in data["discord"]["servers"]:
        logger.debug("Adding new server to serverdata")
        data["discord"]["servers"][server.id] = {"prefix": "!"}
        send_welcome_message = True

    # Make sure all modules are in the server
    _dir = os.path.realpath(
        os.path.join(os.getcwd(), os.path.dirname(__file__)))
    _dir_modules = "{}/../".format(_dir)
    for module_name in os.listdir(_dir_modules):
        if not os.path.isfile("{}/{}/_data.py".format(_dir_modules,
                                                      module_name)):
            logger.warning(
                "No _data.py file found for module {}".format(module_name))
            continue

        try:
            import_name = ".discord_modis.modules.{}.{}".format(
                module_name, "_data")
            _data = importlib.import_module(import_name, "modis")

            if _data.modulename not in data["discord"]["servers"][server.id]:
                data["discord"]["servers"][server.id][
                    _data.modulename] = _data.sd_structure
                datatools.write_data(data)
        except Exception as e:
            logger.error("Could not initialise module {}".format(module_name))
            logger.exception(e)

    datatools.write_data(data)

    # Send a welcome message now
    if send_welcome_message:
        default_channel = server.default_channel
        if not default_channel:
            for channel in server.channels:
                if channel.name == "general":
                    default_channel = channel
                    break
        if not default_channel:
            for channel in server.channels:
                if "general" in channel.name:
                    default_channel = channel
                    break
        if not default_channel:
            for channel in server.channels:
                if channel.type == discord.ChannelType.text:
                    default_channel = channel
                    break

        # Display a welcome message
        if default_channel:
            hello_message = "Hello! I'm Modis.\n\n" + \
                            "The prefix is currently `!`, and can be changed at any time using `!prefix`\n\n" + \
                            "You can use `!help` to get help commands for all modules, " + \
                            "or {} me to get the server prefix and help commands.".format(server.me.mention)
            await client.send_message(default_channel, hello_message)
Ejemplo n.º 10
0
async def on_message(message):
    """The on_message event handler for this module

    Args:
        message (discord.Message): Input message
    """

    # Simplify message info
    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    # Only reply to server messages and don't reply to myself
    if server is not None and author != channel.server.me:
        prefix = data["discord"]["servers"][server.id]["prefix"]
        # Check for mentions reply to mentions
        if channel.server.me in message.mentions:
            await client.send_typing(channel)
            response = "The current server prefix is `{0}`. Type `{0}help` for help.".format(
                prefix)
            await client.send_message(channel, response)

        # Commands section
        if content.startswith(prefix):
            # Parse message
            package = content.split(" ")
            command = package[0][len(prefix):]
            args = package[1:]
            arg = ' '.join(args)

            # Commands
            if command not in ["prefix", "activate", "deactivate"]:
                return

            is_admin = False
            for role in message.author.roles:
                if role.permissions.administrator or \
                        role.permissions.manage_server or \
                        role.permissions.manage_channels:
                    is_admin = True

            if not is_admin:
                await client.send_typing(channel)
                reason = "You must have a role that has the permission" + \
                         "'Administrator', 'Manage Server', or 'Manage Channels'"
                embed = ui_embed.error(channel, "Insufficient Permissions",
                                       reason)
                await embed.send()
                return

            if command == "prefix" and args:
                new_prefix = arg.replace(" ", "").strip()
                data["discord"]["servers"][server.id]["prefix"] = new_prefix
                # Write the data
                datatools.write_data(data)

                await client.send_typing(channel)
                embed = ui_embed.modify_prefix(channel, new_prefix)
                await embed.send()

            if command in ["activate", "deactivate"] and args:
                _dir = os.path.realpath(
                    os.path.join(os.getcwd(), os.path.dirname(__file__)))
                _dir_modules = "{}/../".format(_dir)
                if not os.path.isfile("{}/{}/_data.py".format(
                        _dir_modules, arg)):
                    await client.send_typing(channel)
                    embed = ui_embed.error(
                        channel, "Error",
                        "No module found named '{}'".format(arg))
                    await embed.send()
                    return

                try:
                    import_name = ".discord_modis.modules.{}.{}".format(
                        arg, "_data")
                    module_data = importlib.import_module(import_name, "modis")

                    # Don't try and deactivate this module (not that it would do anything)
                    if module_data.modulename == _data.modulename:
                        await client.send_typing(channel)
                        embed = ui_embed.error(
                            channel, "Error",
                            "I'm sorry, Dave. I'm afraid I can't do that.")
                        await embed.send()
                        return

                    # This /should/ never happen if everything goes well
                    if module_data.modulename not in data["discord"][
                            "servers"][server.id]:
                        await client.send_typing(channel)
                        embed = ui_embed.error(
                            channel, "Error",
                            "No data found for module '{}'".format(
                                module_data.modulename))
                        await embed.send()
                        return

                    # Modify the module
                    if "activated" in data["discord"]["servers"][server.id][
                            module_data.modulename]:
                        is_activate = command == "activate"
                        data["discord"]["servers"][server.id][
                            module_data.modulename]["activated"] = is_activate
                        # Write the data
                        datatools.write_data(data)

                        await client.send_typing(channel)
                        embed = ui_embed.modify_module(channel,
                                                       module_data.modulename,
                                                       is_activate)
                        await embed.send()
                        return
                    else:
                        await client.send_typing(channel)
                        embed = ui_embed.error(
                            channel, "Error",
                            "Can't deactivate module '{}'".format(
                                module_data.modulename))
                        await embed.send()
                        return
                except Exception as e:
                    logger.error("Could not modify module {}".format(arg))
                    logger.exception(e)
Ejemplo n.º 11
0
async def on_message(message):
    """The on_message event handler for this module

    Args:
        message (discord.Message): Input message
    """

    # Simplify message info
    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    # Only reply to server messages and don't reply to myself
    if server is not None and author != channel.server.me:
        prefix = data["discord"]["servers"][server.id]["prefix"]
        # Check for mentions reply to mentions
        if channel.server.me in message.mentions:
            await client.send_typing(channel)
            response = "The current server prefix is `{0}`. Type `{0}help` for help.".format(
                prefix)
            await client.send_message(channel, response)

        # Commands section
        if content.startswith(prefix):
            # Parse message
            package = content.split(" ")
            command = package[0][len(prefix):]
            args = package[1:]
            arg = ' '.join(args)

            # Commands
            if command not in [
                    "prefix", "activate", "deactivate", "warnmax", "warn",
                    "ban"
            ]:
                return

            is_admin = author == server.owner
            for role in message.author.roles:
                if role.permissions.administrator:
                    is_admin = True

            if not is_admin:
                await client.send_typing(channel)
                reason = "You must have a role that has the permission 'Administrator'"
                embed = ui_embed.error(channel, "Insufficient Permissions",
                                       reason)
                await embed.send()
                return

            if command == "prefix" and args:
                new_prefix = arg.replace(" ", "").strip()
                data["discord"]["servers"][server.id]["prefix"] = new_prefix
                # Write the data
                datatools.write_data(data)

                await client.send_typing(channel)
                embed = ui_embed.modify_prefix(channel, new_prefix)
                await embed.send()

            if command == "warnmax" and args:
                try:
                    warn_max = int(arg)
                    if warn_max > 0:
                        data["discord"]["servers"][server.id][
                            _data.modulename]["warnings_max"] = warn_max
                        datatools.write_data(data)
                        await client.send_typing(channel)
                        embed = ui_embed.warning_max_changed(channel, warn_max)
                        await embed.send()
                    else:
                        reason = "Maximum warnings must be greater than 0"
                        embed = ui_embed.error(channel, "Error", reason)
                        await embed.send()
                except (ValueError, TypeError):
                    reason = "Warning maximum must be a number"
                    embed = ui_embed.error(channel, "Error", reason)
                    await embed.send()
                except Exception as e:
                    logger.exception(e)

            if command == "warn" and args:
                for user in message.mentions:
                    await api_manager.warn_user(channel, user)

            if command == "ban" and args:
                for user in message.mentions:
                    await api_manager.ban_user(channel, user)

            if command == "activate" and args:
                await api_manager.activate_module(channel, arg, True)
            elif command == "deactivate" and args:
                await api_manager.activate_module(channel, arg, False)