🎨 Python Midjourney
Midjourney automation Python package using Discord user tokens
✨ Key Features
- 🎨 Midjourney Automation: Execute
/imaginecommands using Discord user tokens - 🔪 Auto Image Splitting: Automatically split 4-grid images into individual images
- 📦 Batch Processing: Process multiple prompts simultaneously
- 💾 Auto Save: Automatically save original + split images
- 🚀 Full Automation: Command → Generate → Download → Split → Save
- 📚 Simple API: Intuitive and easy-to-use interface
🚀 Installation
Install with pip
pip install python-midjourney
Install from source
git clone https://github.com/yourusername/python_midjourney.git
cd python_midjourney
pip install -e .
⚙️ Environment Setup
1. Required Environment Variables
# Set Discord user token
export DISCORD_USER_TOKEN="your_discord_user_token_here"
# Set Midjourney channel ID
export MIDJOURNEY_CHANNEL_ID="your_midjourney_channel_id_here"
2. Using .env file (Recommended)
Create a .env file in your project root:
# Discord settings
DISCORD_USER_TOKEN=your_discord_user_token_here
MIDJOURNEY_CHANNEL_ID=your_midjourney_channel_id_here
3. How to Obtain Environment Variables
Getting Discord User Token
- Access Discord in web browser (discord.com)
- Open Developer Tools (F12)
- Go to Network tab
- Send any message
- Find Authorization header in API requests
- Copy the token (usually starts with
MTAxxxxx...)
⚠️ Important: Never share your user token!
Getting Midjourney Channel ID
- Enable Developer Mode in Discord
- Settings → Advanced → Developer Mode ON
- Right-click on Midjourney channel
- Select "Copy ID"
🎯 Usage
Basic Usage
from python_midjourney import MidjourneyClient
# Create client (automatically uses environment variables)
client = MidjourneyClient()
# Generate image
result = client.generate_image("a beautiful sunset over mountains")
if result['success']:
print(f"Original file: {result['original_file']}")
print(f"Split files: {len(result['split_files'])} files")
for i, file in enumerate(result['split_files'], 1):
print(f" {i}. {file}")
Direct Token Specification
from python_midjourney import MidjourneyClient
# Specify token and channel ID directly
client = MidjourneyClient(
user_token="your_discord_token",
channel_id="your_channel_id",
auto_split=True # Enable auto-split
)
result = client.generate_image("cyberpunk city landscape")
Batch Processing
from python_midjourney import MidjourneyClient
client = MidjourneyClient()
prompts = [
"cozy coffee shop with warm lighting",
"modern minimalist workspace",
"serene mountain lake at dawn"
]
# Batch generation (5 second intervals)
results = client.generate_batch(prompts, delay=5)
# Check results
for i, result in enumerate(results):
if result and result['success']:
print(f"✅ Image {i+1}: {result['total_files']} files generated")
else:
print(f"❌ Image {i+1}: Failed")
Quick Usage (Convenience Function)
from python_midjourney import quick_generate
# Generate image in one line
result = quick_generate(
"fantasy castle in the clouds",
user_token="your_token", # Optional
channel_id="your_channel", # Optional
auto_split=True
)
Disable Auto-Split
from python_midjourney import MidjourneyClient
# Save original image only (no splitting)
client = MidjourneyClient(auto_split=False)
result = client.generate_image("abstract art")
print(f"Original only saved: {result['original_file']}")
# split_files will be an empty list
Check Channel Information
from python_midjourney import MidjourneyClient
client = MidjourneyClient()
# Get current channel information
info = client.get_channel_info()
print(f"Channel name: {info['name']}")
print(f"Server ID: {info['guild_id']}")
# Change to another channel
client.set_channel("another_channel_id")
📂 Result File Structure
your_project/
├── images/ # Original images
│ ├── 20231201_143022_sunset_mountains_midjourney.png
│ └── 20231201_143122_cyberpunk_city_midjourney.png
└── images/split/ # Split images
├── 20231201_143022_sunset_mountains_midjourney_part1.png
├── 20231201_143022_sunset_mountains_midjourney_part2.png
├── 20231201_143022_sunset_mountains_midjourney_part3.png
└── 20231201_143022_sunset_mountains_midjourney_part4.png
🛠️ API Reference
MidjourneyClient
Constructor
MidjourneyClient(
user_token: str = None, # Discord user token
channel_id: str = None, # Midjourney channel ID
auto_split: bool = True # Whether to auto-split
)
Methods
generate_image()
generate_image(
prompt: str, # Image generation prompt
channel_id: str = None, # Channel ID (default: set during initialization)
timeout: int = 60 # Timeout in seconds
) -> Optional[Dict[str, Any]]
Return value:
{
'success': True,
'prompt': 'your prompt',
'original_file': 'images/xxx.png',
'split_files': ['images/split/xxx_part1.png', ...],
'message_id': 'discord_message_id',
'timestamp': '2023-12-01T14:30:22.123456',
'total_files': 5
}
generate_batch()
generate_batch(
prompts: List[str], # List of prompts
channel_id: str = None, # Channel ID
delay: int = 5 # Delay between requests in seconds
) -> List[Dict[str, Any]]
set_channel()
set_channel(channel_id: str) # Change default channel
get_channel_info()
get_channel_info(
channel_id: str = None # Channel ID (default: currently set channel)
) -> Dict[str, Any]
Convenience Functions
quick_generate()
quick_generate(
prompt: str, # Image generation prompt
user_token: str = None, # Discord user token
channel_id: str = None, # Channel ID
auto_split: bool = True # Whether to auto-split
) -> Optional[Dict[str, Any]]
⚠️ Important Notes
1. Discord Terms Compliance
- Using user tokens may violate Discord's Terms of Service
- Use only for personal projects
- Commercial use prohibited
2. Token Security
- Never share your user token
- Don't upload tokens to public repositories like GitHub
- Use environment variables or
.envfiles
3. Usage Limitations
- Requires paid Midjourney subscription
- Must comply with Discord API rate limits
- Avoid excessive requests
4. Technical Limitations
- Internet connection required
- Dependent on Discord server status
- Dependent on Midjourney bot status
🔧 Troubleshooting
Common Errors
1. "Discord User Token not set"
# Check environment variable
echo $DISCORD_USER_TOKEN
# Set environment variable
export DISCORD_USER_TOKEN="your_token_here"
2. "Midjourney Channel ID not set"
# Set channel ID
export MIDJOURNEY_CHANNEL_ID="your_channel_id_here"
3. "Failed to get channel info: 403"
- Token is incorrect or expired
- No access permission to the channel
- Need to check Discord account status
4. "Timeout: No response from Midjourney"
- Midjourney bot is offline or response delayed
- Try increasing timeout value (default: 60 seconds)
- Check network connection
Debugging Tips
from python_midjourney import MidjourneyClient
# Debug with detailed output
client = MidjourneyClient()
# Check channel connection
try:
info = client.get_channel_info()
print("✅ Channel connection successful:", info['name'])
except Exception as e:
print("❌ Channel connection failed:", e)
# Test image generation
result = client.generate_image("test image", timeout=120)
if result:
print("✅ Image generation successful")
else:
print("❌ Image generation failed")
📝 License
This project is distributed under the MIT License. See the LICENSE file for details.
🤝 Contributing
- Fork this repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📞 Support
- Bug Reports: GitHub Issues
- Feature Requests: GitHub Discussions
🙏 Acknowledgments
- Midjourney - Amazing AI art generation service
- Discord - Powerful communication platform
- Pillow - Python image processing library
⚠️ Disclaimer: This package is created for educational and personal use purposes. Please comply with Discord's and Midjourney's Terms of Service when using.
Metadata
Release files for python-midjourney 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| python_midjourney-1.0.0.tar.gz | 14.4 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| python_midjourney-1.0.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 24.8 kB
Release files / python_midjourney-1.0.0.tar.gz
| Download URL | python_midjourney-1.0.0.tar.gz |
|---|---|
| Size | 14.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
2c4cf8cac1610893094eea6b2eb0122c54c1c0207d3650b37ff52204451023e4
|
|
BLAKE2b-256 checksum How to use checksums |
8df413f44eaa5cf44798fbd9b811644e629dafa221a060a92ed3c56ce82f3eef
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.11.11
|
Release files / python_midjourney-1.0.0-py3-none-any.whl
| Download URL | python_midjourney-1.0.0-py3-none-any.whl |
|---|---|
| Size | 10.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c46e3a617474c13c8b57632e296300c76ed4ab5f3daab74b8b5c903583a2d1b2
|
|
BLAKE2b-256 checksum How to use checksums |
376a465a8559fdc1682966e6202d6ee1de17a8ea03ff157296ed9e51a1e6f511
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.11.11
|