FlaskIt Discord Notifications

🔔 Send beautiful Discord notifications from your FlaskIt app.

🚀 Quick Start

1. Setup Webhooks

Add Discord webhook URLs to your .env file:

.env

DISCORD_NEWUSER=https://discord.com/api/webhooks/123456789/abcdefg
DISCORD_CONTACT=https://discord.com/api/webhooks/987654321/hijklmn
DISCORD_ERRORS=https://discord.com/api/webhooks/555555555/opqrstu
Quick tip: the first argument passed to discord.send() must match the webhook name in lowercase.
DISCORD_NEWUSERdiscord.send("newuser", ...)
DISCORD_ORDERSdiscord.send("orders", ...)

2. Send Notifications

notifications.py
from flaskit import discord, discord_colors

# Simple notification
discord.send("newuser", "🆕 Un nouvel utilisateur s'est inscrit !",
             color=discord_colors.BLUE)

# Contact form notification
discord.send("contact", "📩 Nouveau message du formulaire de contact",
             color=discord_colors.GREEN)

# Error notification
discord.send("errors", "❌ Une erreur s'est produite",
             color=discord_colors.RED)

📚 Usage Examples

Example 1: New User Registration

app/logic/auth.py
from datetime import datetime
from flaskit import discord, discord_colors, jsonify


class AuthLogic:
    @staticmethod
    def register():
        # ... registration logic ...

        # Send Discord notification
        discord.send_success("newuser", "New user registered!", details={
            "Username": user.username,
            "Email": user.email,
            "Date": datetime.now().strftime("%Y-%m-%d %H:%M")
        })

        return jsonify({"success": True})

Example 2: Contact Form

app/logic/contact.py
from flaskit import discord, discord_colors, request


class ContactLogic:
    @staticmethod
    def submit():
        data = request.get_json()

        # Send to Discord
        discord.send("contact", "📬 New contact form submission",
            title="Contact Form",
            color=discord_colors.TEAL,
            fields=[
                {"name": "Name", "value": data['name'], "inline": True},
                {"name": "Email", "value": data['email'], "inline": True},
                {"name": "Message", "value": data['message'], "inline": False}
            ]
        )

        return {"success": True}

Example 3: Error Monitoring

app/middleware/error_handler.py
import traceback
from flaskit import discord


def handle_error(error):
    # Log error to Discord
    discord.send_error("errors",
        f"Application Error: {str(error)}",
        details=traceback.format_exc()
    )

    return {"error": "Internal server error"}, 500

Example 4: Advanced Notification

notifications.py
from flaskit import discord, discord_colors


# Rich notification with all options
discord.send(
    "newuser",
    "A new premium user has joined! 🎉",
    title="Premium Registration",
    color=discord_colors.PURPLE,
    fields=[
        {"name": "Username", "value": "john_doe", "inline": True},
        {"name": "Plan", "value": "Premium", "inline": True},
        {"name": "Email", "value": "john@example.com", "inline": False}
    ],
    footer="FlaskIt Notifications",
    thumbnail="https://example.com/avatar.png",
    author={
        "name": "FlaskIt App",
        "icon_url": "https://example.com/logo.png"
    }
)

🎨 Available Colors

colors.py
from flaskit import discord_colors

discord_colors.BLUE      # 0x3498db
discord_colors.GREEN     # 0x2ecc71
discord_colors.RED       # 0xe74c3c
discord_colors.YELLOW    # 0xf39c12
discord_colors.PURPLE    # 0x9b59b6
discord_colors.ORANGE    # 0xe67e22
discord_colors.TEAL      # 0x1abc9c
discord_colors.PINK      # 0xe91e63
discord_colors.BLACK     # 0x000000
discord_colors.WHITE     # 0xffffff

# Aliases
discord_colors.SUCCESS   # GREEN
discord_colors.ERROR     # RED
discord_colors.WARNING   # YELLOW
discord_colors.INFO      # BLUE

🛠️ API Reference

discord.send()

Send a notification with full customization.

discord.send(
    channel: str,              # Webhook name (e.g., "newuser")
    message: str,              # Main message
    title: str = None,         # Embed title
    color: int = None,         # Embed color
    fields: list = None,       # List of fields
    footer: str = None,        # Footer text
    thumbnail: str = None,     # Thumbnail URL
    image: str = None,         # Large image URL
    author: dict = None,       # Author info
    timestamp: bool = True     # Add timestamp
) -> bool

discord.send_simple()

discord.send_simple("newuser", "🆕 New user!", color=discord_colors.BLUE)

discord.send_success()

discord.send_success("newuser", "User created!", details={
    "Username": "john_doe",
    "Email": "john@example.com"
})

discord.send_error()

discord.send_error("errors", "Database error", details=str(exception))

discord.send_warning()

discord.send_warning("alerts", "High memory usage", details="85% used")

🔧 Configuration

Environment Variables

.env
# Format: DISCORD_=

DISCORD_NEWUSER=https://discord.com/api/webhooks/...
DISCORD_CONTACT=https://discord.com/api/webhooks/...
DISCORD_ERRORS=https://discord.com/api/webhooks/...
DISCORD_ORDERS=https://discord.com/api/webhooks/...
DISCORD_PAYMENTS=https://discord.com/api/webhooks/...

Programmatic Configuration

config.py
from flaskit import discord

# Add webhook at runtime
discord.add_webhook("custom", "https://discord.com/api/webhooks/...")

# List all webhooks
channels = discord.list_webhooks()
print(channels)  # ['newuser', 'contact', 'errors', 'custom']

📋 Use Cases

✅ User Events

  • New registrations
  • Profile updates
  • Account deletions
  • Password resets

📬 Forms & Submissions

  • Contact forms
  • Feedback submissions
  • Survey responses
  • Support tickets

🛒 E-commerce

  • New orders
  • Payment confirmations
  • Refund requests
  • Inventory alerts

⚠️ Monitoring

  • Error tracking
  • Performance alerts
  • Security events
  • System health

📊 Analytics

  • Daily reports
  • Milestone achievements
  • Usage statistics
  • Revenue updates

🎯 Best Practices

1. Use Descriptive Channel Names

# ✅ Good
DISCORD_NEWUSER=...
DISCORD_CONTACT=...
DISCORD_PAYMENT_SUCCESS=...

# ❌ Bad
DISCORD_HOOK1=...
DISCORD_WEBHOOK=...

2. Handle Errors Gracefully

# Discord notifications are non-blocking
# They return True/False but won't crash your app
success = discord.send("newuser", "New user!")
if not success:
    # Log to file or alternative system
    logger.warning("Failed to send Discord notification")

3. Don't Spam

# ✅ Good - Batch notifications
discord.send("daily_report", "10 new users today")

# ❌ Bad - Send for every single event
for user in users:
    discord.send("newuser", f"User {user.name}")  # Too many!

4. Use Colors Meaningfully

# Success events
discord.send("orders", "New order!", color=discord_colors.GREEN)

# Errors
discord.send("errors", "Failed!", color=discord_colors.RED)

# Warnings
discord.send("alerts", "High load", color=discord_colors.YELLOW)

# Info
discord.send("updates", "System update", color=discord_colors.BLUE)

🔗 Getting Discord Webhooks

  1. Open your Discord server.
  2. Go to Server SettingsIntegrations.
  3. Click Create Webhook.
  4. Choose a channel.
  5. Copy the webhook URL.
  6. Add it to your .env file.

⚡ Performance

  • Notifications are sent asynchronously (10s timeout).
  • Failed notifications will not crash your app.
  • Webhook URLs are cached after first load.
  • No external dependencies except requests.

Created with ❤️ by FlaskIt Framework

Back to documentation