A standalone AI chatbot is useful. An AI connected to your tools is transformative.
Imagine:
- Customer emails trigger AI analysis and suggested responses
- Slack messages get instant AI-powered answers from your docs
- Form submissions automatically create AI-generated reports
- Discord community questions answered by your AI in real-time
This is what integrations enable. Here's how to build them.
Integration Architecture Overview
AI integrations typically follow one of these patterns:
Pattern 1: Webhook Triggers
External event → Webhook → AI Processing → Response/Action
[Slack message] → [Webhook to your app] → [AI generates response] → [Reply in Slack]
Pattern 2: Polling/Scheduled
Timer → Check for updates → AI Processing → Action
[Every 5 minutes] → [Check email inbox] → [AI categorizes new emails] → [Route to team]
Pattern 3: Direct API
Your app → AI API → Your app
[User clicks button] → [Call AI API] → [Display result in app]
Pattern 4: Middleware (Zapier/Make/n8n)
Trigger → Middleware → AI → Middleware → Action
[Form submitted] → [Zapier catches] → [AI analyzes] → [Zapier] → [Notion page created]
Slack Integration
Setting Up a Slack App
-
Go to api.slack.com/apps
-
Create New App → From scratch
-
Add permissions (scopes):
chat:write- Send messageschannels:history- Read channel messagesapp_mentions:read- Respond to @mentionsim:history- Direct messages
-
Enable Event Subscriptions:
- URL: Your webhook endpoint
- Events:
app_mention,message.im
Basic Slack Bot with AI
from flask import Flask, request, jsonify
from slack_sdk import WebClient
from slack_sdk.signature import SignatureVerifier
from aimagicx import AIChat
app = Flask(__name__)
slack_client = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
verifier = SignatureVerifier(os.environ["SLACK_SIGNING_SECRET"])
ai = AIChat(model="claude-3-5-sonnet")
@app.route("/slack/events", methods=["POST"])
def slack_events():
# Verify request is from Slack
if not verifier.is_valid_request(request.get_data(), request.headers):
return "Invalid request", 403
data = request.json
# Handle URL verification
if data.get("type") == "url_verification":
return jsonify({"challenge": data["challenge"]})
# Handle events
if data.get("type") == "event_callback":
event = data["event"]
if event["type"] == "app_mention":
handle_mention(event)
return "", 200
def handle_mention(event):
channel = event["channel"]
user = event["user"]
text = event["text"]
# Remove the @mention from the text
query = text.split(">", 1)[1].strip() if ">" in text else text
# Get AI response
response = ai.chat(
message=query,
context=f"Responding to Slack user {user} in channel {channel}"
)
# Reply in thread
slack_client.chat_postMessage(
channel=channel,
text=response.text,
thread_ts=event.get("thread_ts", event["ts"])
)
Advanced: Slash Commands
Create richer interactions with slash commands:
@app.route("/slack/commands", methods=["POST"])
def slash_command():
command = request.form.get("command")
text = request.form.get("text")
user_id = request.form.get("user_id")
channel_id = request.form.get("channel_id")
if command == "/ask":
# Immediate response (Slack requires response within 3s)
# Process async for longer operations
response = ai.chat(message=text)
return jsonify({
"response_type": "in_channel",
"text": response.text
})
elif command == "/summarize":
# Get recent channel history and summarize
history = slack_client.conversations_history(
channel=channel_id,
limit=50
)
messages = [m["text"] for m in history["messages"]]
summary = ai.chat(
message=f"Summarize this Slack conversation:\n\n{messages}"
)
return jsonify({
"response_type": "ephemeral", # Only visible to user
"text": summary.text
})
Tips for Slack Integration
- Use threading: Reply in threads to keep channels clean
- Ephemeral for personal: Use ephemeral messages for user-specific info
- Show typing: Send typing indicator for longer operations
- Rate limits: Slack has rate limits; implement queuing for high volume
- Blocks for rich UI: Use Block Kit for interactive messages
Discord Integration
Setting Up a Discord Bot
- Go to discord.com/developers/applications
- Create New Application
- Go to Bot → Create Bot
- Enable these Intents:
- Message Content Intent
- Server Members Intent (if needed)
- Get your bot token
Basic Discord Bot with AI
import discord
from aimagicx import AIChat
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
ai = AIChat(model="claude-3-5-sonnet")
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
@client.event
async def on_message(message):
# Don't respond to ourselves
if message.author == client.user:
return
# Respond to mentions
if client.user.mentioned_in(message):
query = message.content.replace(f'<@{client.user.id}>', '').strip()
# Show typing indicator
async with message.channel.typing():
response = ai.chat(message=query)
# Reply to the message
await message.reply(response.text)
# Respond to DMs
if isinstance(message.channel, discord.DMChannel):
async with message.channel.typing():
response = ai.chat(message=message.content)
await message.reply(response.text)
client.run(os.environ["DISCORD_TOKEN"])
Discord Slash Commands
Modern Discord bots use slash commands:
from discord import app_commands
class MyBot(discord.Client):
def __init__(self):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
await self.tree.sync()
bot = MyBot()
@bot.tree.command(name="ask", description="Ask the AI a question")
async def ask(interaction: discord.Interaction, question: str):
await interaction.response.defer() # For longer operations
response = ai.chat(message=question)
await interaction.followup.send(response.text)
@bot.tree.command(name="summarize", description="Summarize recent messages")
async def summarize(interaction: discord.Interaction, count: int = 20):
await interaction.response.defer()
# Get recent messages
messages = []
async for msg in interaction.channel.history(limit=count):
messages.append(f"{msg.author.name}: {msg.content}")
messages.reverse()
history = "\n".join(messages)
response = ai.chat(
message=f"Summarize this Discord conversation:\n\n{history}"
)
await interaction.followup.send(response.text)
Tips for Discord Integration
- Use embeds: Rich embeds look better than plain text
- Rate limits: Discord has strict rate limits; use queues
- Per-server settings: Store settings per guild (server)
- Slash commands: Preferred over text commands now
- Defer for long operations: Acknowledge within 3 seconds, send followup later
Zapier Integration
Zapier connects 5,000+ apps without code. Here's how to use AI in your Zaps.
Using Zapier Webhooks to Trigger AI
- Trigger: Choose your trigger app (Gmail, Typeform, etc.)
- Action: Webhooks by Zapier → POST
- Configure:
- URL: Your AI endpoint
- Payload: Data to send to AI
URL: https://api.aimagicx.com/v1/chat
Method: POST
Headers:
Authorization: Bearer your-api-key
Content-Type: application/json
Data:
{
"message": "Analyze this customer email: {{email_body}}",
"model": "claude-3-5-sonnet"
}
Using AI Response in Subsequent Steps
Zapier can parse the AI response and use it:
Step 1: Trigger (New Gmail)
Step 2: Webhook to AI (Analyze and categorize)
Step 3: Parse JSON (Extract category, sentiment, priority)
Step 4: Conditional (If priority is high...)
Step 5: Slack notification / Create ticket / etc.
Example Zap: AI Email Responder
Trigger: New email in Gmail matching "support@"
Step 1: Webhook to AI
- Message: "Draft a response to: {{email_body}}"
- Context: "We are a SaaS company. Be helpful but professional."
Step 2: Filter
- Only continue if AI confidence > 0.8
Step 3: Create Gmail Draft
- To: {{from_email}}
- Subject: Re: {{subject}}
- Body: {{ai_response}}
Step 4: Slack notification
- "AI drafted response to {{from_email}} - please review"
Example Zap: Content Generation Pipeline
Trigger: New item in Notion database
Step 1: Webhook to AI
- Message: "Write a blog post about: {{topic}}"
- Style: {{tone}} (from Notion property)
Step 2: Webhook to AI (Image prompt)
- Message: "Create an image prompt for: {{topic}}"
Step 3: DALL-E / Midjourney
- Generate image from prompt
Step 4: Update Notion
- Add generated content and image
- Set status to "Ready for Review"
Make (Integromat) Integration
Make offers more complex workflows than Zapier:
HTTP Module for AI
Module: HTTP → Make a Request
URL: https://api.aimagicx.com/v1/chat
Method: POST
Headers:
Authorization: Bearer {{connection.api_key}}
Content-Type: application/json
Body:
{
"message": "{{1.email_content}}",
"model": "claude-3-5-sonnet"
}
Parse response: Yes
Iterators and Aggregators
Make excels at processing lists:
Scenario: Process all comments on a post
1. Trigger: New social media post
2. HTTP: Get all comments
3. Iterator: Process each comment
4. AI: Analyze sentiment
5. Filter: Only negative sentiment
6. Aggregator: Collect flagged comments
7. Slack: Send summary of issues
Error Handling
Make has built-in error handling:
Route 1: Normal flow → AI processing → Success actions
Route 2: Error handler → If AI fails → Fallback actions
n8n Integration
n8n is self-hosted and developer-friendly.
HTTP Request Node
Node: HTTP Request
Method: POST
URL: https://api.aimagicx.com/v1/chat
Authentication: Header Auth
Headers:
Content-Type: application/json
Body:
{
"message": "{{ $json.input_text }}",
"model": "claude-3-5-sonnet"
}
Code Node for Complex Logic
// Code node for custom AI processing
const response = await $http.request({
method: 'POST',
url: 'https://api.aimagicx.com/v1/chat',
headers: {
'Authorization': `Bearer ${$env.AI_MAGICX_API_KEY}`,
'Content-Type': 'application/json'
},
body: {
message: items[0].json.query,
context: items[0].json.context
}
});
return [{
json: {
original: items[0].json,
ai_response: response.data.response
}
}];
n8n AI Nodes (Native)
n8n now has native AI nodes:
- AI Agent: Autonomous agent with tools
- AI Chain: Sequential AI operations
- AI Memory: Maintain conversation state
- AI Tools: Connect AI to other n8n nodes
Webhook Best Practices
Security
-
Verify signatures: Always verify webhook signatures
import hmac import hashlib def verify_webhook(payload, signature, secret): expected = hmac.new( secret.encode(), payload, hashlib.sha256 ).hexdigest() return hmac.compare_digest(signature, expected) -
Use HTTPS: Never accept webhooks over HTTP
-
Validate payloads: Check required fields exist
-
Rate limit: Prevent webhook floods
Reliability
- Respond quickly: Return 200 within 5 seconds
- Process async: Queue work for background processing
- Retry handling: Handle duplicate webhooks idempotently
- Timeout handling: Set reasonable timeouts for AI calls
Example: Robust Webhook Handler
from flask import Flask, request
from celery import Celery
import hashlib
import hmac
app = Flask(__name__)
celery = Celery(app.name, broker='redis://localhost:6379')
@app.route("/webhook", methods=["POST"])
def webhook():
# Verify signature
signature = request.headers.get("X-Signature")
if not verify_signature(request.data, signature):
return "Invalid signature", 401
# Parse and validate
data = request.json
if not data.get("event") or not data.get("payload"):
return "Invalid payload", 400
# Idempotency check
event_id = data.get("event_id")
if event_already_processed(event_id):
return "Already processed", 200
# Queue for processing
process_webhook.delay(data)
# Respond immediately
return "Accepted", 202
@celery.task
def process_webhook(data):
# AI processing happens here
response = ai.chat(message=data["payload"]["text"])
# Send result to appropriate destination
send_response(data["callback_url"], response)
# Mark as processed
mark_event_processed(data["event_id"])
AI Magicx Integration Features
AI Magicx provides built-in integrations:
Slack Integration
- One-click Slack app installation
- Automatic bot configuration
- Channel selection for responses
- Thread support
Discord Integration
- Bot token configuration
- Server/channel permissions
- Slash command registration
Webhooks (Outgoing)
- Trigger external services on AI events
- Configurable payloads
- Retry logic built-in
Webhooks (Incoming)
- Receive events from external services
- Route to appropriate AI agents
- Transform payloads automatically
Zapier/Make Templates
- Pre-built templates for common workflows
- AI Magicx app in Zapier marketplace
- Native Make module
Building Your Integration
Step 1: Define the Use Case
What should trigger AI?
- User messages in chat?
- Form submissions?
- Scheduled events?
- Database changes?
What should AI do?
- Generate content?
- Analyze data?
- Make decisions?
- Take actions?
Step 2: Choose the Pattern
- Direct API: For your own apps
- Webhooks: For event-driven triggers
- Middleware: For connecting existing tools
Step 3: Build and Test
- Start with a simple flow
- Test with real data
- Handle errors gracefully
- Monitor for issues
Step 4: Scale
- Add queuing for volume
- Implement caching where sensible
- Monitor costs and latency
- Iterate based on usage
Ready to connect AI to your tools? AI Magicx's integrations make it easy to add AI to Slack, Discord, and your automation workflows.