示例#1
0
    def __init__(self):
        formatter = Formatter(
            "%(asctime)s:%(levelname)s:%(name)s: %(message)s")
        log_path = path.from_root("sooch.log")
        file_handler = TimedRotatingFileHandler(filename=log_path,
                                                when="midnight",
                                                backupCount=14,
                                                encoding="utf-8",
                                                utc=True)
        file_handler.setFormatter(formatter)
        stream_handler = StreamHandler(stream=sys.stdout)
        stream_handler.setFormatter(formatter)
        self.logger = logging.getLogger("sooch")
        self.logger.setLevel(DEBUG)
        self.logger.addHandler(stream_handler)
        self.logger.addHandler(file_handler)
        discord_logger = logging.getLogger("discord")
        discord_logger.setLevel(DEBUG)
        discord_logger.addHandler(stream_handler)
        discord_logger.addHandler(file_handler)

        # Read from config.
        self.config = self.load_config()
        self.database = Database(self.config)

        # Initialize all the other modules.
        listeners.servers = Servers(self.database)
        services.player_svc = Players(self.database)
        services.reg_buildings_svc = RegBuildings(self.database)

        super().__init__()
示例#2
0
    def __init__(self, config):
        self.logger = logging.getLogger("sooch")
        self.logger.info("Initializing database")

        db_config = config["database"]
        db_type = db_config["type"]

        if db_type == "postgres":
            self.logger.info("Connecting to postgres")
            self.connection = psycopg2.connect(url=db_config["url"],
                                               username=db_config["username"],
                                               password=db_config["password"])
        elif db_type == "mysql":
            self.logger.info("Connecting to mysql")
            self.connection = mysql.connector.connect(
                url=db_config["url"],
                username=db_config["username"],
                password=db_config["password"])
        elif db_type == "sqlite":
            self.logger.info("Connecting to sqlite")

            db_file_path = path.from_root(db_config["file"])
            self.connection = sqlite3.connect(db_file_path)
        else:
            self.connection = None
            self.logger.error("Invalid database type %s",
                              config["database"]["type"])
            sys.exit()
        self.migrate()
示例#3
0
 def load_config(self):
     """
     Load configs from a config file, generating the default one if
     necessary.
     """
     self.save_default_config()
     config_path = path.from_root("config.json")
     with open(config_path, "r", encoding="utf-8") as config_file:
         config_text = config_file.read()
         return json.loads(config_text)
示例#4
0
 def save_default_config(self):
     """
     Save the default config file at the expected location if it
     does not exist.
     """
     config_path = path.from_root("config.json")
     if not os.path.isfile(config_path):
         with open(config_path, "w", encoding="utf-8") as config_file:
             config_file.writelines(
                 json.dumps(
                     {
                         "token": "",
                         "database": {
                             "type": "sqlite",
                             "file": "./sooch.db"
                         }
                     },
                     indent=4))
         self.logger.info(
             "Config file has been created. Please fill in the token.")
         sys.exit()
示例#5
0
                  content: List[str]) -> Optional[discord.Embed]:
    """Handle all invalid command with Sooch prefixes."""
    del client, message
    command = content[0]

    embed = discord.Embed()
    embed.add_field(name="Invalid command.",
                    value=("{} is an invalid command. "
                           "Please try again or type `s!help` or `s.help` "
                           "for a list of commands.").format(command),
                    inline=False)
    return embed


credits_embed = discord.Embed()
credits_path = path.from_root("resources/embeds/credits.txt")
with open(credits_path, "r", encoding="utf-8") as credits_file:
    credits_text = credits_file.read()
    for field_data in credits_text.split("\n\n===\n\n"):
        field = field_data.split("\n", maxsplit=1)
        credits_embed.add_field(
            name=field[0],
            value=field[1],
            inline=True,
        )


async def credits_command(client: discord.Client, message: discord.Message,
                          content: List[str]) -> Optional[discord.Embed]:
    """Handle the s!credit command."""
    del client, message, content