08. Knowledge Base Integration
Chapter 8 of 18 · 20 min
A standalone FAQ bot is useful, but integration with existing tools makes it actually valuable. Common integrations include Slack, Microsoft Teams, and web interfaces.
A Slack integration requires a Flask web server and the Slack SDK:
from flask import Flask, request, jsonify
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
import os
app = Flask(__name__)
slack_client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])
CHUNKS = [] # Loaded from knowledge base
@app.route('/slack/events', methods=['POST'])
def slack_events():
"""Handle incoming Slack events."""
data = request.json
# URL verification
if data.get('type') == 'url_verification':
return jsonify({'challenge': data['challenge']})
# Direct message or mention
event = data.get('event', {})
if event.get('type') == 'message' and 'bot_id' not in event:
user_id = event.get('user')
question = event.get('text')
channel = event.get('channel')
response = answer_faq(question, CHUNKS)
try:
slack_client.chat_postMessage(
channel=channel,
text=f"<@{user_id}> {response['answer']}"
)
except SlackApiError as e:
print(f"Error posting message: {e}")
return '', 200
A web interface requires a simple HTML page and a backend endpoint:
<!DOCTYPE html>
<html>
<head>
<title>FAQ Assistant</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 40px auto; padding: 20px; }
.question-input { width: 100%; padding: 12px; font-size: 16px; }
.response { margin-top: 20px; padding: 20px; background: #f5f5f5; border-radius: 8px; }
.sources { font-size: 12px; color: #666; margin-top: 10px; }
</style>
</head>
<body>
<h1>FAQ Assistant</h1>
<input type="text" class="question-input" id="question" placeholder="Ask a question...">
<button onclick="ask()">Ask</button>
<div class="response" id="response"></div>
<div class="sources" id="sources"></div>
<script>
async function ask() {
const question = document.getElementById('question').value;
if (!question) return;
const res = await fetch('/api/faq', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({question})
});
const data = await res.json();
document.getElementById('response').innerText = data.answer;
document.getElementById('sources').innerText =
'Sources: ' + (data.sources || []).join(', ');
}
</script>
</body>
</html>
@app.route('/api/faq', methods=['POST'])
def faq_api():
"""API endpoint for FAQ questions."""
data = request.json
question = data.get('question', '')
if not question:
return jsonify({'error': 'No question provided'}), 400
response = answer_faq(question, CHUNKS)
return jsonify(response)
Integration patterns remain similar across platforms. The core logic lives in answer_faq(), and platform-specific code only handles transport and authentication.
EXERCISE
Deploy your FAQ bot with one integration (Slack, Teams, or web). Test the complete user flow from question to answer.