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

Separate Configurations into a TOML File #10

Merged

Conversation

Zingzy
Copy link
Owner

@Zingzy Zingzy commented Feb 2, 2025

This issue addresses Issue #9

Summary by Sourcery

Load bot configuration from a TOML file instead of environment variables and constants.

Build:

  • Load bot configuration from a TOML file.

Chores:

  • Replace requests library with aiohttp.

@Zingzy Zingzy added the enhancement New feature or request label Feb 2, 2025
@Zingzy Zingzy linked an issue Feb 2, 2025 that may be closed by this pull request
Copy link

sourcery-ai bot commented Feb 2, 2025

Reviewer's Guide by Sourcery

This pull request refactors the bot to load configurations from a TOML file instead of using environment variables and hardcoded values. This change improves maintainability and allows for easier configuration of the bot's behavior.

Sequence diagram for configuration loading process

sequenceDiagram
    participant App
    participant ConfigLoader
    participant TOML
    participant Pydantic
    participant API

    App->>ConfigLoader: Import config
    ConfigLoader->>TOML: Read config.toml
    TOML-->>ConfigLoader: Return config data
    ConfigLoader->>Pydantic: Validate config data
    Pydantic-->>ConfigLoader: Return validated Config instance
    ConfigLoader->>API: Initialize models list
    API-->>ConfigLoader: Return available models
    ConfigLoader-->>App: Return complete config
Loading

Class diagram for the new configuration system

classDiagram
    class Config {
        +bot: BotConfig
        +api: APIConfig
        +image_generation: ImageGenerationConfig
        +commands: Dict[str, CommandConfig]
        +ui: UIConfig
        +resources: ResourcesConfig
        +MODELS: List[str]
        +validate_structure()
    }

    class BotConfig {
        +command_prefix: str
        +bot_id: str
        +avatar_url: str
        +commands: Dict[str, str]
        +emojis: Dict[str, str]
    }

    class APIConfig {
        +models_list_endpoint: str
        +image_gen_endpoint: str
        +models_refresh_interval_minutes: int
        +max_timeout_seconds: int
    }

    class ImageGenerationConfig {
        +referer: str
        +fallback_model: str
        +defaults: ImageGenerationDefaults
        +validation: ImageGenerationValidation
    }

    Config --> BotConfig
    Config --> APIConfig
    Config --> ImageGenerationConfig
Loading

File-Level Changes

Change Details Files
Configuration is loaded from a TOML file.
  • Added a new config.py file to handle loading and validation of the TOML configuration.
  • Added a config.template.toml file to serve as a template for the configuration.
  • Added tomli to the project dependencies in pyproject.toml.
  • The config.py file uses pydantic to define the structure of the configuration and validate the data.
  • The config.py file includes a function to pre-initialize the models list by fetching from the API.
config.py
config.template.toml
pyproject.toml
Bot commands and their descriptions are now loaded from the configuration file.
  • The bot's command prefix is now loaded from the configuration.
  • The bot's command descriptions are now loaded from the configuration.
  • The bot's command IDs are now loaded from the configuration.
main.py
API endpoints and refresh intervals are now loaded from the configuration file.
  • The API endpoint for fetching models is now loaded from the configuration.
  • The interval for refreshing models is now loaded from the configuration.
main.py
Image generation parameters are now loaded from the configuration file.
  • Default image dimensions are now loaded from the configuration.
  • Default image generation flags (safe, cached, nologo, enhance, private) are now loaded from the configuration.
  • Image validation parameters (min width, min height, max prompt length) are now loaded from the configuration.
cogs/imagine_cog.py
cogs/multi_pollinate_cog.py
cogs/random_cog.py
utils/image_gen_utils.py
UI elements and error messages are now loaded from the configuration file.
  • The bot's invite URL is now loaded from the configuration.
  • The bot's support server URL is now loaded from the configuration.
  • The bot's GitHub repository URL is now loaded from the configuration.
  • The bot's API provider URL is now loaded from the configuration.
  • The bot's creator avatar is now loaded from the configuration.
  • The bot's UI colors are now loaded from the configuration.
  • Error messages are now loaded from the configuration.
main.py
cogs/imagine_cog.py
cogs/multi_pollinate_cog.py
cogs/random_cog.py
utils/error_handler.py
utils/embed_utils.py
Bot resources are now loaded from the configuration file.
  • The bot's waiting GIFs are now loaded from the configuration.
utils/embed_utils.py
Command cooldowns are now loaded from the configuration file.
  • Command cooldown rates and seconds are now loaded from the configuration.
cogs/imagine_cog.py
cogs/multi_pollinate_cog.py
cogs/random_cog.py
Removed the constants.py file.
  • Removed the constants.py file.
  • Removed all references to the constants.py file.
main.py
cogs/imagine_cog.py
cogs/multi_pollinate_cog.py
cogs/random_cog.py
utils/pollinate_utils.py
Updated dependencies in requirements.txt.
  • Added tomli and pydantic to the project dependencies.
  • Removed requests from the project dependencies.
requirements.txt
Added aiohttp for asynchronous HTTP requests.
  • Replaced requests with aiohttp for asynchronous HTTP requests.
main.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @Zingzy - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

start_time = None
latencies: list = []

commands_: dict[str, str] = {
"</pollinate:1223762317359976519> 🎨": """Generates AI Images based on your prompts
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider using a command registry pattern to centralize command definitions and reduce string interpolation noise.

The command configuration can be simplified while maintaining flexibility. Consider using a command registry pattern:

# commands.py
class CommandRegistry:
    def __init__(self, config):
        self.commands = {
            "pollinate": {
                "id": config.bot.commands['pollinate_id'],
                "emoji": "🎨",
                "description": """Generates AI Images based on your prompts..."""
            },
            # ... other commands
        }

    def get_formatted_command(self, name):
        cmd = self.commands[name]
        return f"</{name}:{cmd['id']}> {cmd['emoji']}"

    def get_description(self, name):
        return self.commands[name]["description"]

# Usage in main code
cmd_registry = CommandRegistry(config)
commands_ = {
    cmd_registry.get_formatted_command("pollinate"): cmd_registry.get_description("pollinate"),
    # ... other commands
}

This approach:

  1. Reduces string interpolation noise
  2. Keeps configuration flexibility
  3. Makes command management more maintainable
  4. Centralizes command definitions
  5. Makes it easier to add new commands

@Zingzy Zingzy merged commit 8da002b into main Feb 2, 2025
1 check passed
@Zingzy Zingzy deleted the 9-feature-request-separate-configurations-into-a-toml-file branch February 2, 2025 13:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Feature Request: Separate Configurations into a TOML File
1 participant