Build an iMessage Chatbot with Blue Replies and OpenAI

AI-Powered Customer Support via iMessage
Imagine your customers texting your business via iMessage and getting instant, intelligent responses at any hour — no hold times, no support tickets, no waiting until Monday. By combining Blue Replies's iMessage API with OpenAI's language models, you can build a chatbot that handles common inquiries, answers FAQs, and seamlessly escalates to human agents when needed.
This is not a clunky phone tree or a "type 1 for billing" bot. This is natural, conversational AI delivered through the channel your customers already prefer.
Architecture Overview
The system works in three steps:
- 1. Customer sends iMessage → Blue Replies receives it and triggers your webhook
- 2. Your server processes the message → Sends the message to OpenAI with context and instructions
- 3. OpenAI generates a response → Your server sends it back via Blue Replies as an iMessage
Step 1: Set Up the Webhook Handler
Create an Express.js server that receives incoming iMessages and routes them to OpenAI:
import express from 'express';
import OpenAI from 'openai';
import Blue Replies from '@bluereplies/sdk';
const app = express();
app.use(express.json());
const openai = new OpenAI({ apiKey: process.env.OPENAI_KEY });
const bluereplies = new Blue Replies({ apiKey: process.env.BLUEREPLIES_KEY });
// In-memory conversation history (use Redis in production)
const conversations = new Map();
app.post('/webhooks/bluereplies', async (req, res) => {
res.status(200).send('OK');
const { type, data } = req.body;
if (type !== 'message.received') return;
const { from, body } = data;
await handleIncomingMessage(from, body);
});
app.listen(3000);
Step 2: Build the AI Response Logic
Maintain conversation history for context-aware responses:
async function handleIncomingMessage(from, body) {
// Get or create conversation history
if (!conversations.has(from)) {
conversations.set(from, []);
}
const history = conversations.get(from);
// Add the customer's message to history
history.push({ role: 'user', content: body });
// Send typing indicator while AI processes
await bluereplies.messages.sendTypingIndicator({ to: from });
// Generate AI response
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'system',
content: `You are a helpful customer support agent for Blue Replies,
an iMessage API platform. Be friendly, concise, and helpful.
Keep responses under 300 characters when possible — this is
a text message conversation, not an email.
If you cannot answer a question, say you will connect them
with a human agent.`,
},
...history,
],
max_tokens: 200,
});
const reply = completion.choices[0].message.content;
// Save AI response to history
history.push({ role: 'assistant', content: reply });
// Send the response via iMessage
await bluereplies.messages.send({ to: from, body: reply });
// Check if escalation is needed
if (reply.includes('connect you with') || reply.includes('human agent')) {
await escalateToHuman(from, history);
}
}
Step 3: Add Smart Escalation
Not every question should be handled by AI. Build escalation logic for complex issues:
async function escalateToHuman(customerPhone, history) {
// Notify your support team via Slack, email, or CRM
const summary = history
.map(m => `${m.role}: ${m.content}`)
.join('\n');
await fetch(process.env.SLACK_WEBHOOK_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: `🔔 Escalation needed for ${customerPhone}\n${summary}`,
}),
});
// Send handoff message to customer
await bluereplies.messages.send({
to: customerPhone,
body: 'I am connecting you with a team member who can help further. They will reach out shortly!',
});
}
Best Practices for iMessage Chatbots
- Keep responses short: This is texting, not email. Aim for 1-3 sentences per response.
- Use typing indicators: Show the typing bubble while the AI processes to mimic natural conversation flow.
- Maintain context: Use conversation history so the AI remembers what was discussed. Store in Redis with a 24-hour TTL.
- Set expectations: When a customer first messages, let them know they are chatting with an AI assistant.
- Escalate gracefully: When the AI is unsure, hand off to a human rather than guessing. Customers appreciate honesty.
- Add personality: Emojis and casual language feel natural in iMessage. "Let me check that for you! 🔍" feels right.
Going Further
Once your basic chatbot is running, consider adding:
- RAG (Retrieval-Augmented Generation): Connect your knowledge base so the AI can answer product-specific questions
- Order lookups: Let customers check order status by saying "Where is my order?"
- Appointment scheduling: Integrate with your calendar to let the AI book meetings
- Sentiment analysis: Detect frustrated customers and escalate proactively
More from the Blog
iMessage vs Email: The Channel Your Customers Actually Check
Email open rates have cratered to 21%. iMessage delivers 98%. Here is why the smartest businesses are making the switch.
iMessage vs SMS: Why Blue Bubbles Convert 3x Better
Discover why businesses switching from SMS to iMessage see dramatically higher engagement, open rates, and conversion rates.
Blue Replies vs Twilio for iMessage: What Developers Need to Know
Twilio does SMS. Blue Replies does iMessage. Here is a developer-focused comparison of both platforms and when to use each.
iMessage for Real Estate: Close More Deals with Blue Bubbles
Real estate runs on relationships and speed. Here is how top-producing agents use iMessage to respond faster, build trust, and close more deals.