Skip to content

⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.

security: remove Midjourney/Discord integration from art skill

Daniel Miessler67fda3263dde
diff --git a/.claude/skills/art/lib/discord-bot.ts b/.claude/skills/art/lib/discord-bot.ts
deleted file mode 100644
index 158982c6..00000000
--- a/.claude/skills/art/lib/discord-bot.ts
+++ /dev/null
@@ -1,275 +0,0 @@
-/**
- * discord-bot.ts - Discord Bot Client for Midjourney Integration
- *
- * Official Discord bot wrapper using discord.js for legitimate interaction
- * with Midjourney bot. Handles connection, message sending, monitoring,
- * and image downloads.
- *
- * @see ~/.claude/skills/art/SKILL.md
- */
-
-import {
- Client,
- GatewayIntentBits,
- Message,
- TextChannel,
- Partials
-} from 'discord.js';
-import { writeFile } from 'node:fs/promises';
-
-// ============================================================================
-// Constants
-// ============================================================================
-
-const MIDJOURNEY_BOT_ID = '936929561302675456'; // Official Midjourney bot ID
-
-// ============================================================================
-// Types
-// ============================================================================
-
-export interface DiscordBotConfig {
- token: string;
- channelId: string;
-}
-
-export interface WaitForResponseOptions {
- timeout: number; // in seconds
- pollInterval?: number; // in milliseconds
-}
-
-// ============================================================================
-// Discord Bot Client
-// ============================================================================
-
-export class DiscordBotClient {
- private client: Client;
- private config: DiscordBotConfig;
- private connected: boolean = false;
-
- constructor(config: DiscordBotConfig) {
- this.config = config;
-
- // Initialize Discord client with required intents
- this.client = new Client({
- intents: [
- GatewayIntentBits.Guilds,
- GatewayIntentBits.GuildMessages,
- GatewayIntentBits.MessageContent,
- ],
- partials: [Partials.Message, Partials.Channel],
- });
- }
-
- /**
- * Connect to Discord
- */
- async connect(): Promise<void> {
- if (this.connected) {
- return;
- }
-
- return new Promise((resolve, reject) => {
- // Set up event handlers
- this.client.once('ready', () => {
- console.log(`✅ Discord bot connected as ${this.client.user?.tag}`);
- this.connected = true;
- resolve();
- });
-
- this.client.on('error', (error) => {
- console.error('❌ Discord client error:', error);
- });
-
- // Login with bot token
- this.client.login(this.config.token).catch(reject);
- });
- }
-
- /**
- * Send a message to the specified channel
- */
- async sendMessage(content: string): Promise<Message> {
- if (!this.connected) {
- throw new Error('Bot not connected. Call connect() first.');
- }
-
- const channel = await this.client.channels.fetch(this.config.channelId);
-
- if (!channel || !channel.isTextBased()) {
- throw new Error(`Channel ${this.config.channelId} is not a text channel`);
- }
-
- const message = await (channel as TextChannel).send(content);
- console.log(`📤 Sent message: ${content}`);
-
- return message;
- }
-
- /**
- * Wait for Midjourney's response to a prompt
- *
- * Polls the channel for messages from Midjourney bot that reference
- * our initial message. Returns when the response is complete (has image attachments).
- */
- async waitForMidjourneyResponse(
- initialMessageId: string,
- options: WaitForResponseOptions
- ): Promise<Message> {
- const { timeout, pollInterval = 5000 } = options;
- const startTime = Date.now();
- const timeoutMs = timeout * 1000;
-
- console.log(`⏳ Waiting for Midjourney response (timeout: ${timeout}s)...`);
-
- while (Date.now() - startTime < timeoutMs) {
- // Fetch recent messages from channel
- const channel = await this.client.channels.fetch(this.config.channelId);
-
- if (!channel || !channel.isTextBased()) {
- throw new Error('Channel not found or not text-based');
- }
-
- const messages = await (channel as TextChannel).messages.fetch({ limit: 20 });
-
- // Find Midjourney's response to our prompt
- for (const [_, message] of messages) {
- // Check if message is from Midjourney bot
- if (message.author.id !== MIDJOURNEY_BOT_ID) {
- continue;
- }
-
- // Check if this message references our initial prompt
- const referencesOurMessage =
- message.reference?.messageId === initialMessageId ||
- message.interaction?.id === initialMessageId ||
- message.content.includes(initialMessageId);
-
- if (!referencesOurMessage) {
- continue;
- }
-
- // Check if generation is complete
- if (this.isGenerationComplete(message)) {
- console.log(`✅ Midjourney generation complete!`);
- return message;
- } else {
- console.log(`⏳ Generation in progress... (${Math.floor((Date.now() - startTime) / 1000)}s)`);
- }
- }
-
- // Wait before next poll
- await this.sleep(pollInterval);
- }
-
- throw new Error(`Timeout waiting for Midjourney response after ${timeout}s`);
- }
-
- /**
- * Check if Midjourney generation is complete
- *
- * A complete generation has:
- * - Image attachments
- * - No "Waiting to start" or "%" progress indicators
- */
- private isGenerationComplete(message: Message): boolean {
- // Must have attachments (the generated image)
- if (message.attachments.size === 0) {
- return false;
- }
-
- // Check for in-progress indicators
- const content = message.content.toLowerCase();
- const inProgressIndicators = [
- 'waiting to start',
- '(waiting)',
- '(0%)',
- '(1%)',
- '(2%)',
- '(3%)',
- '(4%)',
- '(5%)',
- '(6%)',
- '(7%)',
- '(8%)',
- '(9%)',
- // Continue patterns for progress
- '%)',
- ];
-
- for (const indicator of inProgressIndicators) {
- if (content.includes(indicator)) {
- return false;
- }
- }
-
- return true;
- }
-
- /**
- * Download image from URL to local path
- */
- async downloadImage(url: string, outputPath: string): Promise<void> {
- console.log(`📥 Downloading image from ${url}...`);
-
- const response = await fetch(url);
-
- if (!response.ok) {
- throw new Error(`Failed to download image: ${response.statusText}`);
- }
-
- const arrayBuffer = await response.arrayBuffer();
- const buffer = Buffer.from(arrayBuffer);
-
- await writeFile(outputPath, buffer);
-
- console.log(`✅ Image saved to ${outputPath}`);
- }
-
- /**
- * Disconnect from Discord
- */
- async disconnect(): Promise<void> {
- if (!this.connected) {
- return;
- }
-
- await this.client.destroy();
- this.connected = false;
- console.log('👋 Discord bot disconnected');
- }
-
- /**
- * Get the first image attachment URL from a message
- */
- getImageUrl(message: Message): string | null {
- if (message.attachments.size === 0) {
- return null;
- }
-
- // Get first attachment
- const attachment = message.attachments.first();
-
- if (!attachment) {
- return null;
- }
-
- // Verify it's an image
- const imageExtensions = ['.png', '.jpg', '.jpeg', '.webp', '.gif'];
- const isImage = imageExtensions.some(ext =>
- attachment.url.toLowerCase().includes(ext)
- );
-
- if (!isImage) {
- return null;
- }
-
- return attachment.url;
- }
-
- /**
- * Sleep utility
- */
- private sleep(ms: number): Promise<void> {
- return new Promise(resolve => setTimeout(resolve, ms));
- }
-}
diff --git a/.claude/skills/art/lib/midjourney-client.ts b/.claude/skills/art/lib/midjourney-client.ts
deleted file mode 100644
index 8305f69a..00000000
--- a/.claude/skills/art/lib/midjourney-client.ts
+++ /dev/null
@@ -1,336 +0,0 @@
-/**
- * midjourney-client.ts - Midjourney Interaction Client
- *
- * High-level client for interacting with Midjourney bot through Discord.
- * Handles prompt formatting, command submission, response parsing,
- * and error detection.
- *
- * @see ~/.claude/skills/art/SKILL.md
- */
-
-import { DiscordBotClient } from './discord-bot.js';
-import { Message } from 'discord.js';
-
-// ============================================================================
-// Types
-// ============================================================================
-
-export interface MidjourneyOptions {
- prompt: string;
- aspectRatio?: string;
- version?: string;
- stylize?: number;
- quality?: number;
- chaos?: number;
- weird?: number;
- tile?: boolean;
- timeout?: number; // in seconds
-}
-
-export interface MidjourneyResult {
- imageUrl: string;
- prompt: string;
- messageId: string;
-}
-
-export type MidjourneyErrorType =
- | 'content_policy'
- | 'timeout'
- | 'connection'
- | 'invalid_params'
- | 'generation_failed'
- | 'no_image';
-
-export class MidjourneyError extends Error {
- constructor(
- public type: MidjourneyErrorType,
- message: string,
- public originalPrompt?: string,
- public suggestion?: string
- ) {
- super(message);
- this.name = 'MidjourneyError';
- }
-}
-
-// ============================================================================
-// Midjourney Client
-// ============================================================================
-
-export class MidjourneyClient {
- private discordBot: DiscordBotClient;
-
- constructor(discordBot: DiscordBotClient) {
- this.discordBot = discordBot;
- }
-
- /**
- * Generate image with Midjourney
- *
- * Submits prompt, waits for generation, and returns image URL
- */
- async generateImage(options: MidjourneyOptions): Promise<MidjourneyResult> {
- const {
- prompt,
- aspectRatio = '16:9',
- version = '6.1',
- stylize = 100,
- quality = 1,
- chaos,
- weird,
- tile = false,
- timeout = 120,
- } = options;
-
- // Format the Midjourney prompt
- const formattedPrompt = this.formatPrompt({
- prompt,
- aspectRatio,
- version,
- stylize,
- quality,
- chaos,
- weird,
- tile,
- });
-
- console.log(`🎨 Submitting to Midjourney: ${formattedPrompt}`);
-
- // Send the /imagine command
- const initialMessage = await this.discordBot.sendMessage(`/imagine prompt: ${formattedPrompt}`);
-
- // Wait for Midjourney to complete generation
- let responseMessage: Message;
- try {
- responseMessage = await this.discordBot.waitForMidjourneyResponse(initialMessage.id, {
- timeout,
- pollInterval: 5000,
- });
- } catch (error) {
- if (error instanceof Error && error.message.includes('Timeout')) {
- throw new MidjourneyError(
- 'timeout',
- `Generation timed out after ${timeout}s. The image may still be processing in Discord.`,
- formattedPrompt,
- 'Try checking Discord manually or increasing the timeout value.'
- );
- }
- throw error;
- }
-
- // Check for errors in response
- this.detectErrors(responseMessage, formattedPrompt);
-
- // Extract image URL
- const imageUrl = this.discordBot.getImageUrl(responseMessage);
-
- if (!imageUrl) {
- throw new MidjourneyError(
- 'no_image',
- 'No image found in Midjourney response',
- formattedPrompt,
- 'The generation may have failed. Check Discord for error messages.'
- );
- }
-
- return {
- imageUrl,
- prompt: formattedPrompt,
- messageId: responseMessage.id,
- };
- }
-
- /**
- * Format Midjourney prompt with parameters
- *
- * Converts structured options into Midjourney command syntax
- */
- private formatPrompt(options: {
- prompt: string;
- aspectRatio: string;
- version: string;
- stylize: number;
- quality: number;
- chaos?: number;
- weird?: number;
- tile: boolean;
- }): string {
- const { prompt, aspectRatio, version, stylize, quality, chaos, weird, tile } = options;
-
- let formattedPrompt = prompt;
-
- // Add aspect ratio
- formattedPrompt += ` --ar ${aspectRatio}`;
-
- // Add version
- formattedPrompt += ` --v ${version}`;
-
- // Add stylize (default is 100, only add if different)
- if (stylize !== 100) {
- formattedPrompt += ` --s ${stylize}`;
- }
-
- // Add quality (default is 1, only add if different)
- if (quality !== 1) {
- formattedPrompt += ` --q ${quality}`;
- }
-
- // Add optional parameters
- if (chaos !== undefined) {
- formattedPrompt += ` --chaos ${chaos}`;
- }
-
- if (weird !== undefined) {
- formattedPrompt += ` --weird ${weird}`;
- }
-
- if (tile) {
- formattedPrompt += ` --tile`;
- }
-
- return formattedPrompt;
- }
-
- /**
- * Detect errors in Midjourney response
- */
- private detectErrors(message: Message, originalPrompt: string): void {
- const content = message.content.toLowerCase();
-
- // Content policy violations
- const contentPolicyIndicators = [
- 'banned prompt',
- 'content policy',
- 'violates our community standards',
- 'inappropriate content',
- 'against our terms',
- ];
-
- for (const indicator of contentPolicyIndicators) {
- if (content.includes(indicator)) {
- throw new MidjourneyError(
- 'content_policy',
- 'Prompt violates Midjourney content policy',
- originalPrompt,
- 'Try rephrasing your prompt to avoid potentially sensitive content.'
- );
- }
- }
-
- // Invalid parameters
- const invalidParamIndicators = [
- 'invalid parameter',
- 'unknown parameter',
- 'invalid aspect ratio',
- 'invalid version',
- ];
-
- for (const indicator of invalidParamIndicators) {
- if (content.includes(indicator)) {
- throw new MidjourneyError(
- 'invalid_params',
- 'Invalid Midjourney parameters',
- originalPrompt,
- 'Check your aspect ratio, version, and other parameter values.'
- );
- }
- }
-
- // Generation failures
- const failureIndicators = [
- 'failed to generate',
- 'generation failed',
- 'error generating',
- 'something went wrong',
- ];
-
- for (const indicator of failureIndicators) {
- if (content.includes(indicator)) {
- throw new MidjourneyError(
- 'generation_failed',
- 'Midjourney generation failed',
- originalPrompt,
- 'Try again or check Discord for more details.'
- );
- }
- }
- }
-
- /**
- * Parse Midjourney response to extract metadata
- */
- parseResponse(message: Message): {
- prompt: string;
- parameters: Record<string, string>;
- } {
- const content = message.content;
-
- // Extract prompt (usually before the first --)
- const promptMatch = content.match(/^(.+?)(?:\s+--|\s*$)/);
- const prompt = promptMatch ? promptMatch[1].trim() : content;
-
- // Extract parameters
- const parameters: Record<string, string> = {};
- const paramRegex = /--(\w+)\s+([^\s-]+)/g;
- let match;
-
- while ((match = paramRegex.exec(content)) !== null) {
- parameters[match[1]] = match[2];
- }
-
- return { prompt, parameters };
- }
-
- /**
- * Validate Midjourney options before submission
- */
- static validateOptions(options: MidjourneyOptions): void {
- // Validate aspect ratio
- const validAspectRatios = [
- '1:1', '16:9', '9:16', '2:3', '3:2', '4:5', '5:4', '7:4', '4:7',
- '21:9', '9:21', '3:4', '4:3'
- ];
-
- if (options.aspectRatio && !validAspectRatios.includes(options.aspectRatio)) {
- throw new Error(
- `Invalid aspect ratio: ${options.aspectRatio}. Valid ratios: ${validAspectRatios.join(', ')}`
- );
- }
-
- // Validate version
- const validVersions = ['6.1', '6', '5.2', '5.1', '5', 'niji', 'niji 6'];
-
- if (options.version && !validVersions.includes(options.version)) {
- throw new Error(
- `Invalid version: ${options.version}. Valid versions: ${validVersions.join(', ')}`
- );
- }
-
- // Validate stylize (0-1000)
- if (options.stylize !== undefined && (options.stylize < 0 || options.stylize > 1000)) {
- throw new Error('Stylize must be between 0 and 1000');
- }
-
- // Validate quality
- const validQualities = [0.25, 0.5, 1, 2];
-
- if (options.quality !== undefined && !validQualities.includes(options.quality)) {
- throw new Error('Quality must be 0.25, 0.5, 1, or 2');
- }
-
- // Validate chaos (0-100)
- if (options.chaos !== undefined && (options.chaos < 0 || options.chaos > 100)) {
- throw new Error('Chaos must be between 0 and 100');
- }
-
- // Validate weird (0-3000)
- if (options.weird !== undefined && (options.weird < 0 || options.weird > 3000)) {
- throw new Error('Weird must be between 0 and 3000');
- }
-
- // Validate timeout
- if (options.timeout !== undefined && options.timeout < 30) {
- throw new Error('Timeout must be at least 30 seconds');
- }
- }
-}
diff --git a/.claude/skills/art/tools/generate-midjourney-image.ts b/.claude/skills/art/tools/generate-midjourney-image.ts
deleted file mode 100755
index 636ee107..00000000
--- a/.claude/skills/art/tools/generate-midjourney-image.ts
+++ /dev/null
@@ -1,371 +0,0 @@
-#!/usr/bin/env bun
-
-/**
- * generate-midjourney-image - Midjourney Image Generation CLI
- *
- * Generate images using Midjourney via Discord bot integration.
- * Follows llcli pattern for deterministic, composable CLI design.
- *
- * Usage:
- * generate-midjourney-image --prompt "..." --aspect-ratio 16:9 --output /tmp/image.png
- *
- * @see ~/.claude/skills/art/SKILL.md
- */
-
-import { DiscordBotClient } from '../lib/discord-bot.js';
-import { MidjourneyClient, MidjourneyError } from '../lib/midjourney-client.js';
-import { readFile } from 'node:fs/promises';
-import { resolve } from 'node:path';
-
-// ============================================================================
-// Environment Loading
-// ============================================================================
-
-/**
- * Load environment variables from ~/.claude/.env
- * This ensures API keys are available regardless of how the CLI is invoked
- */
-async function loadEnv(): Promise<void> {
- const envPath = resolve(process.env.HOME!, '.claude/.env');
- try {
- const envContent = await readFile(envPath, 'utf-8');
- for (const line of envContent.split('\n')) {
- const trimmed = line.trim();
- if (!trimmed || trimmed.startsWith('#')) continue;
- const eqIndex = trimmed.indexOf('=');
- if (eqIndex === -1) continue;
- const key = trimmed.slice(0, eqIndex).trim();
- let value = trimmed.slice(eqIndex + 1).trim();
- // Remove surrounding quotes if present
- if ((value.startsWith('"') && value.endsWith('"')) ||
- (value.startsWith("'") && value.endsWith("'"))) {
- value = value.slice(1, -1);
- }
- // Only set if not already defined (allow overrides from shell)
- if (!process.env[key]) {
- process.env[key] = value;
- }
- }
- } catch (error) {
- // Silently continue if .env doesn't exist - rely on shell env vars
- }
-}
-
-// ============================================================================
-// Types
-// ============================================================================
-
-interface CLIArgs {
- prompt: string;
- aspectRatio: string;
- version: string;
- stylize: number;
- quality: number;
- chaos?: number;
- weird?: number;
- tile: boolean;
- output: string;
- timeout: number;
-}
-
-// ============================================================================
-// Configuration
-// ============================================================================
-
-const DEFAULTS = {
- aspectRatio: '16:9',
- version: process.env.MIDJOURNEY_DEFAULT_VERSION || '6.1',
- stylize: parseInt(process.env.MIDJOURNEY_DEFAULT_STYLIZE || '100'),
- quality: parseInt(process.env.MIDJOURNEY_DEFAULT_QUALITY || '1'),
- tile: false,
- output: '/tmp/midjourney-image.png',
- timeout: 120,
-};
-
-// ============================================================================
-// Error Handling
-// ============================================================================
-
-class CLIError extends Error {
- constructor(message: string, public exitCode: number = 1) {
- super(message);
- this.name = 'CLIError';
- }
-}
-
-function handleError(error: unknown): never {
- if (error instanceof MidjourneyError) {
- console.error(`\n❌ Midjourney Error: ${error.message}`);
- console.error(` Type: ${error.type}`);
- if (error.originalPrompt) {
- console.error(` Prompt: ${error.originalPrompt}`);
- }
- if (error.suggestion) {
- console.error(` Suggestion: ${error.suggestion}`);
- }
- process.exit(1);
- }
-
- if (error instanceof CLIError) {
- console.error(`❌ Error: ${error.message}`);
- process.exit(error.exitCode);
- }
-
- if (error instanceof Error) {
- console.error(`❌ Unexpected error: ${error.message}`);
- console.error(error.stack);
- process.exit(1);
- }
-
- console.error(`❌ Unknown error:`, error);
- process.exit(1);
-}
-
-// ============================================================================
-// Help Text
-// ============================================================================
-
-function showHelp(): void {
- console.log(`
-generate-midjourney-image - Midjourney Image Generation CLI
-
-Generate images using Midjourney via Discord bot integration.
-
-USAGE:
- generate-midjourney-image --prompt "<prompt>" [OPTIONS]
-
-REQUIRED:
- --prompt <text> Image generation prompt (quote if contains spaces)
-
-OPTIONS:
- --aspect-ratio <ratio> Aspect ratio (default: 16:9)
- Valid: 1:1, 16:9, 9:16, 2:3, 3:2, 4:5, 5:4, 7:4, 4:7, 21:9, 9:21, 3:4, 4:3
- --version <version> Midjourney version (default: ${DEFAULTS.version})
- Valid: 6.1, 6, 5.2, 5.1, 5, niji, niji 6
- --stylize <value> Stylization 0-1000 (default: ${DEFAULTS.stylize})
- --quality <value> Quality: 0.25, 0.5, 1, 2 (default: ${DEFAULTS.quality})
- --chaos <value> Chaos 0-100 (optional)
- --weird <value> Weird 0-3000 (optional)
- --tile Enable tiling mode (default: false)
- --output <path> Output file path (default: ${DEFAULTS.output})
- --timeout <seconds> Max wait time (default: ${DEFAULTS.timeout})
-
-ENVIRONMENT VARIABLES:
- DISCORD_BOT_TOKEN Discord bot token (required)
- MIDJOURNEY_CHANNEL_ID Channel ID for Midjourney (required)
- MIDJOURNEY_DEFAULT_VERSION Default Midjourney version
- MIDJOURNEY_DEFAULT_QUALITY Default quality setting
- MIDJOURNEY_DEFAULT_STYLIZE Default stylize setting
-
-EXAMPLES:
- # Standard blog header
- generate-midjourney-image \\
- --prompt "abstract flowing data streams, minimal shapes, Tokyo Night colors" \\
- --aspect-ratio 16:9 \\
- --output /tmp/header.png
-
- # High quality square image
- generate-midjourney-image \\
- --prompt "geometric network visualization, abstract tech concept" \\
- --aspect-ratio 1:1 \\
- --quality 2 \\
- --output /tmp/square.png
-
- # Creative with high stylization
- generate-midjourney-image \\
- --prompt "flowing organic shapes, data visualization" \\
- --stylize 500 \\
- --weird 1000
-`);
-}
-
-// ============================================================================
-// Argument Parsing
-// ============================================================================
-
-function parseArgs(args: string[]): CLIArgs {
- const result: Partial<CLIArgs> = {
- aspectRatio: DEFAULTS.aspectRatio,
- version: DEFAULTS.version,
- stylize: DEFAULTS.stylize,
- quality: DEFAULTS.quality,
- tile: DEFAULTS.tile,
- output: DEFAULTS.output,
- timeout: DEFAULTS.timeout,
- };
-
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
-
- switch (arg) {
- case '--help':
- case '-h':
- showHelp();
- process.exit(0);
- break;
-
- case '--prompt':
- result.prompt = args[++i];
- break;
-
- case '--aspect-ratio':
- case '--ar':
- result.aspectRatio = args[++i];
- break;
-
- case '--version':
- case '-v':
- result.version = args[++i];
- break;
-
- case '--stylize':
- case '-s':
- result.stylize = parseInt(args[++i]);
- break;
-
- case '--quality':
- case '-q':
- result.quality = parseFloat(args[++i]);
- break;
-
- case '--chaos':
- result.chaos = parseInt(args[++i]);
- break;
-
- case '--weird':
- result.weird = parseInt(args[++i]);
- break;
-
- case '--tile':
- result.tile = true;
- break;
-
- case '--output':
- case '-o':
- result.output = args[++i];
- break;
-
- case '--timeout':
- result.timeout = parseInt(args[++i]);
- break;
-
- default:
- throw new CLIError(`Unknown argument: ${arg}`);
- }
- }
-
- // Validate required args
- if (!result.prompt) {
- throw new CLIError('Missing required argument: --prompt');
- }
-
- return result as CLIArgs;
-}
-
-// ============================================================================
-// Main
-// ============================================================================
-
-async function main() {
- try {
- // Load API keys from ~/.claude/.env
- await loadEnv();
-
- // Parse arguments
- const args = parseArgs(process.argv.slice(2));
-
- // Validate environment variables
- const botToken = process.env.DISCORD_BOT_TOKEN;
- const channelId = process.env.MIDJOURNEY_CHANNEL_ID;
-
- if (!botToken) {
- throw new CLIError(
- 'Missing DISCORD_BOT_TOKEN environment variable. Add it to ~/.claude/.env'
- );
- }
-
- if (!channelId) {
- throw new CLIError(
- 'Missing MIDJOURNEY_CHANNEL_ID environment variable. Add it to ~/.claude/.env'
- );
- }
-
- // Validate Midjourney options
- MidjourneyClient.validateOptions({
- prompt: args.prompt,
- aspectRatio: args.aspectRatio,
- version: args.version,
- stylize: args.stylize,
- quality: args.quality,
- chaos: args.chaos,
- weird: args.weird,
- tile: args.tile,
- timeout: args.timeout,
- });
-
- console.log('🤖 Midjourney Image Generation');
- console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
- console.log(`Prompt: ${args.prompt}`);
- console.log(`Aspect Ratio: ${args.aspectRatio}`);
- console.log(`Version: ${args.version}`);
- console.log(`Stylize: ${args.stylize}`);
- console.log(`Quality: ${args.quality}`);
- if (args.chaos) console.log(`Chaos: ${args.chaos}`);
- if (args.weird) console.log(`Weird: ${args.weird}`);
- if (args.tile) console.log(`Tile: enabled`);
- console.log(`Output: ${args.output}`);
- console.log(`Timeout: ${args.timeout}s`);
- console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
-
- // Initialize Discord bot
- const discordBot = new DiscordBotClient({
- token: botToken,
- channelId: channelId,
- });
-
- // Initialize Midjourney client
- const midjourneyClient = new MidjourneyClient(discordBot);
-
- try {
- // Connect to Discord
- await discordBot.connect();
-
- // Generate image
- const result = await midjourneyClient.generateImage({
- prompt: args.prompt,
- aspectRatio: args.aspectRatio,
- version: args.version,
- stylize: args.stylize,
- quality: args.quality,
- chaos: args.chaos,
- weird: args.weird,
- tile: args.tile,
- timeout: args.timeout,
- });
-
- // Download image
- await discordBot.downloadImage(result.imageUrl, args.output);
-
- console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
- console.log('✅ Success!');
- console.log(` Image URL: ${result.imageUrl}`);
- console.log(` Saved to: ${args.output}`);
- console.log(` Message ID: ${result.messageId}`);
- console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
-
- // Disconnect
- await discordBot.disconnect();
-
- process.exit(0);
- } catch (error) {
- // Ensure we disconnect even on error
- await discordBot.disconnect();
- throw error;
- }
- } catch (error) {
- handleError(error);
- }
-}
-
-// Run
-main();