Real-world examples to integrate ReplyHub into your applications. Copy, modify, and deploy in minutes.
Simple chat implementation with ReplyHub API
// Basic chat with ReplyHub
const sendMessage = async (message, assistantId) => {
try {
const response = await fetch('https://replyhub.app/api/webhook/ai-assistant', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'ak_live_your_api_key_here'
},
body: JSON.stringify({
input: message,
assistantId: assistantId
})
});
const data = await response.json();
return data.response;
} catch (error) {
console.error('Error:', error);
return 'Sorry, I encountered an error.';
}
};
// Usage
const reply = await sendMessage("Hello, how can you help?", "ast_1234567890");
console.log(reply);
Complete React chat interface with ReplyHub
import React, { useState } from 'react';
export function ChatComponent({ assistantId, apiKey }) {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const [loading, setLoading] = useState(false);
const sendMessage = async () => {
if (!input.trim()) return;
const userMessage = { role: 'user', content: input };
setMessages(prev => [...prev, userMessage]);
setLoading(true);
setInput('');
try {
const response = await fetch('https://replyhub.app/api/webhook/ai-assistant', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey
},
body: JSON.stringify({
input: input,
assistantId: assistantId
})
});
const data = await response.json();
const aiMessage = { role: 'assistant', content: data.response };
setMessages(prev => [...prev, aiMessage]);
} catch (error) {
console.error('Error:', error);
} finally {
setLoading(false);
}
};
return (
<div className="chat-container">
<div className="messages">
{messages.map((msg, i) => (
<div key={i} className={`message ${msg.role}`}>
{msg.content}
</div>
))}
{loading && <div className="loading">AI is thinking...</div>}
</div>
<div className="input-area">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
placeholder="Type your message..."
/>
<button onClick={sendMessage} disabled={loading}>
Send
</button>
</div>
</div>
);
}
Search through uploaded documents with AI responses
import requests
import json
class ReplyHubClient:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://replyhub.app/api"
def search_knowledge(self, query, assistant_id, conversation_id=None):
"""Search knowledge base and get AI response"""
url = f"{self.base_url}/webhook/ai-assistant"
headers = {
'Content-Type': 'application/json',
'x-api-key': self.api_key
}
payload = {
'input': query,
'assistantId': assistant_id
}
if conversation_id:
payload['conversationId'] = conversation_id
response = requests.post(url, headers=headers, json=payload)
return response.json()
def upload_document(self, file_path, assistant_id):
"""Upload document to knowledge base"""
url = f"{self.base_url}/embeddings/upload"
headers = {'x-api-key': self.api_key}
with open(file_path, 'rb') as file:
files = {'file': file}
data = {'assistantId': assistant_id}
response = requests.post(url, headers=headers, files=files, data=data)
return response.json()
# Usage example
client = ReplyHubClient("ak_live_your_api_key")
# Upload a document
result = client.upload_document("company_policy.pdf", "ast_1234567890")
print(f"Upload status: {result.get('status')}")
# Search the knowledge base
response = client.search_knowledge(
"What is our return policy?",
"ast_1234567890"
)
print(f"AI Response: {response.get('response')}")
Integrate ReplyHub with Slack, Discord, or other platforms
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
// Slack bot integration
app.post('/slack/events', async (req, res) => {
const { challenge, event } = req.body;
// Slack URL verification
if (challenge) {
return res.json({ challenge });
}
// Handle message events
if (event && event.type === 'message' && !event.bot_id) {
const userMessage = event.text;
const channel = event.channel;
try {
// Get AI response from ReplyHub
const aiResponse = await axios.post('https://replyhub.app/api/webhook/ai-assistant', {
input: userMessage,
assistantId: 'ast_your_assistant_id'
}, {
headers: {
'Content-Type': 'application/json',
'x-api-key': 'ak_live_your_api_key'
}
});
// Send response back to Slack
await axios.post('https://slack.com/api/chat.postMessage', {
channel: channel,
text: aiResponse.data.response
}, {
headers: {
'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`,
'Content-Type': 'application/json'
}
});
} catch (error) {
console.error('Error:', error);
}
}
res.status(200).send('OK');
});
// Discord bot integration
app.post('/discord/webhook', async (req, res) => {
const { content, channel_id } = req.body;
try {
const aiResponse = await axios.post('https://replyhub.app/api/webhook/ai-assistant', {
input: content,
assistantId: 'ast_your_assistant_id'
}, {
headers: {
'x-api-key': 'ak_live_your_api_key'
}
});
// Send back to Discord
res.json({
type: 4, // CHANNEL_MESSAGE_WITH_SOURCE
data: {
content: aiResponse.data.response
}
});
} catch (error) {
res.status(500).json({ error: 'Failed to process message' });
}
});
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
iOS/Android integration with ReplyHub API
import Foundation
class ReplyHubService {
private let apiKey: String
private let baseURL = "https://replyhub.app/api"
init(apiKey: String) {
self.apiKey = apiKey
}
func sendMessage(
message: String,
assistantId: String,
completion: @escaping (Result<String, Error>) -> Void
) {
guard let url = URL(string: "\(baseURL)/webhook/ai-assistant") else {
completion(.failure(URLError(.badURL)))
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(apiKey, forHTTPHeaderField: "x-api-key")
let body = [
"input": message,
"assistantId": assistantId
]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: body)
} catch {
completion(.failure(error))
return
}
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(URLError(.badServerResponse)))
return
}
do {
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
let responseText = json?["response"] as? String ?? "No response"
completion(.success(responseText))
} catch {
completion(.failure(error))
}
}.resume()
}
}
// Usage in your View Controller
class ChatViewController: UIViewController {
let replyHub = ReplyHubService(apiKey: "ak_live_your_api_key")
func sendUserMessage(_ message: String) {
replyHub.sendMessage(
message: message,
assistantId: "ast_your_assistant_id"
) { result in
DispatchQueue.main.async {
switch result {
case .success(let response):
self.displayMessage(response, isFromUser: false)
case .failure(let error):
print("Error: \(error)")
}
}
}
}
}
Real-time streaming for faster user experience
// Streaming chat responses for real-time experience
async function streamChatResponse(message, assistantId, onChunk, onComplete) {
try {
const response = await fetch('https://replyhub.app/api/webhook/ai-assistant', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'ak_live_your_api_key',
'Accept': 'text/event-stream'
},
body: JSON.stringify({
input: message,
assistantId: assistantId,
stream: true
})
});
if (!response.body) {
throw new Error('No response body');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6));
if (data.chunk) {
onChunk(data.chunk);
}
if (data.done) {
onComplete();
return;
}
} catch (e) {
// Skip invalid JSON
}
}
}
}
} catch (error) {
console.error('Streaming error:', error);
throw error;
}
}
// Usage with React component
function StreamingChat() {
const [message, setMessage] = useState('');
const [currentResponse, setCurrentResponse] = useState('');
const [isStreaming, setIsStreaming] = useState(false);
const handleSend = async () => {
if (!message.trim()) return;
setIsStreaming(true);
setCurrentResponse('');
await streamChatResponse(
message,
'ast_your_assistant_id',
(chunk) => {
setCurrentResponse(prev => prev + chunk);
},
() => {
setIsStreaming(false);
}
);
setMessage('');
};
return (
<div>
<div className="response">
{currentResponse}
{isStreaming && <span className="cursor">▋</span>}
</div>
<input
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
disabled={isStreaming}
/>
<button onClick={handleSend} disabled={isStreaming}>
Send
</button>
</div>
);
}