Chuyển tới nội dung chính

Building a Webex Chatbot for Testbed Environment Monitoring 🤖

🚀 Build an Intelligent Testbed Monitoring Bot

Automate testbed management with WebSocket-powered real-time monitoring

📋 Table of Contents

Overview

The Testbed Monitor Bot is a sophisticated Webex-integrated chatbot that revolutionizes how teams manage and track test environment resources. Built with Python and leveraging WebSocket technology, it eliminates the need for webhooks and public IP addresses.

📊

Real-time Monitoring

Track testbed availability and usage with instant updates

🔔

Smart Broadcasting

Notify teams across multiple Webex rooms automatically

📝

Easy Registration

Book testbeds with interactive Adaptive Cards UI

🔒

WebSocket Security

No public IP needed - secure behind firewalls

🎯 Key Features

🔌Why WebSocket?

Unlike traditional webhook-based bots that require:

  • ✗ Public IP address
  • ✗ SSL certificates
  • ✗ Firewall configurations
  • ✗ ngrok tunnels

This bot uses WebSocket connections:

  • ✓ Works behind corporate firewalls
  • ✓ No complex network setup
  • ✓ Real-time bidirectional communication
  • ✓ Automatic reconnection on failure

Core Capabilities

Real-time Testbed Status

  • View all testbeds at a glance
  • See who's using what resource
  • Track usage duration and expected release time
  • Color-coded availability indicators
# Bot automatically tracks:
{
"testbed_name": "Testbed-1",
"status": "in_use",
"user_email": "engineer@company.com",
"registered_time": "2025-10-01T10:30:00Z",
"expected_release_time": "2025-10-01T18:00:00Z"
}

🏗️ System Architecture

🏗️ Interactive System Architecture

Webex Cloud
Bot Server
JSON DB
Adaptive Cards

Technology Stack

🐍 Python 3.10+
Core language
🔌 websockets
Real-time communication
💾 JSON Database
Lightweight storage
🎴 Adaptive Cards
Interactive UI
Main Menu

🏠 Main Menu - Entry point with all bot functions

Main Menu
Status View
Registration Form
Success Message
Broadcast Selection
Broadcast Message
Release Form
Help Command
Feedback

🚀 Getting Started

1
Setup Bot
2
Configure Env
3
Install Deps
4
Deploy
5
Test

Prerequisites

Requirements Checklist

Before starting, ensure you have:

  • Python 3.10+ installed and configured
  • Webex Teams account with bot creation privileges
  • Network access to Webex APIs (or proxy configuration)
  • Basic knowledge of Python and REST APIs

Optional but recommended:

  • Git for version control
  • Virtual environment (venv/conda)
  • Docker for containerized deployment

Step 1: Create Your Webex Bot

Register via Webex Developer Portal:

  1. Visit developer.webex.com

  2. Sign in with your Webex credentials

  3. Navigate to My AppsCreate a New App

  4. Select Create a Bot

  5. Fill in bot details:

Bot Name: Testbed Monitor Bot
Bot Username: testbed-monitor@webex.bot
Bot Icon: [Upload custom icon]
Description: Intelligent bot for tracking and managing testbed usage
  1. Click Add Bot and copy the Bot Access Token

⚠️🔒 Security Warning

Never commit your bot token to version control!

The bot access token is like a password. If exposed:

  • Anyone can impersonate your bot
  • Unauthorized access to conversations
  • Potential data breaches

Always store it in:

  • Environment variables
  • .env files (add to .gitignore)
  • Secret management systems (AWS Secrets Manager, Azure Key Vault)

Step 2: Environment Setup

Windows Setup:

# Clone the repository
git clone https://github.com/ngtanthanh-qc/webexchatbot_sample.git
cd webexchatbot_sample

# Create virtual environment
python -m venv .venv

# Activate virtual environment
.venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

Step 3: Configuration

Create .env file in project root:

.env
# Webex Bot Configuration
WEBEX_ACCESS_TOKEN=your_bot_access_token_here
BOT_NAME=Testbed Monitor Bot

# Database Configuration
TESTBED_DB_NAME=testbed_monitor.json

# Webex API Configuration
WEBEX_API_URL=https://webexapis.com/v1

# Approved Rooms (comma-separated room IDs)
# Find room ID: Open Webex web, go to room, copy ID from URL
APPROVED_ROOMS=Y2lzY29zcGFyazovL3VzL1JPT00vNTU4NGI4MjAtNTRkMi0xMWVkLTg0YWItYzMyYWU2ZGNhOGE4

# Proxy Configuration (if behind corporate firewall)
HTTPS_PROXY=http://proxy.company.com:80
WSS_PROXY=socks5://proxy.company.com:1080

🆔🔍 Finding Room IDs

How to get Webex Room ID:

  1. Open Webex Web App
  2. Navigate to the desired room/space
  3. Look at the browser URL:
    https://web.webex.com/spaces/Y2lzY29zcGFyazovL3VzL1JPT00v...
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    This is your Room ID
  4. Copy the ID after /spaces/

Alternative method via API:

from webexpythonsdk import WebexAPI

api = WebexAPI(access_token='YOUR_TOKEN')
rooms = api.rooms.list()

for room in rooms:
print(f"{room.title}: {room.id}")

Step 4: Database Initialization

The bot uses JSON for lightweight data storage. Customize testbed_monitor.json:

testbed_monitor.json
{
"testbeds": [
{
"id": 1,
"testbed_name": "Production-Mirror",
"status": "available",
"user_email": null,
"user_name": null,
"registered_time": null,
"purpose": null,
"expected_release_time": null
},
{
"id": 2,
"testbed_name": "Dev-Environment-1",
"status": "available",
"user_email": null,
"user_name": null,
"registered_time": null,
"purpose": null,
"expected_release_time": null
},
{
"id": 3,
"testbed_name": "IaC-Sandbox",
"status": "in_use",
"user_email": "engineer@company.com",
"user_name": "John Doe",
"registered_time": "2025-10-01T09:00:00Z",
"purpose": "Testing CI/CD pipeline",
"expected_release_time": "2025-10-01T17:00:00Z"
}
]
}

Database Schema:

FieldTypeDescription
idIntegerUnique testbed identifier
testbed_nameStringTestbed display name
statusStringavailable or in_use
user_emailString/nullEmail of current user
user_nameString/nullName of current user
registered_timeISO8601/nullWhen testbed was booked
purposeString/nullUsage purpose/description
expected_release_timeISO8601/nullExpected availability time

Step 5: Main Bot Implementation

example.py
import os
from webex_bot.commands.testbed_main import TestbedMainCommand
from webex_bot.commands.help_custom import CustomHelpCommand
from webex_bot.webex_bot import WebexBot
from config import Config

# Proxy configuration (optional)
proxies = {
'https': 'http://proxy.company.com:80',
'wss': 'socks5://proxy.company.com:1080'
}

# Validate configuration
try:
Config.validate_config()
except ValueError as e:
print(f"❌ Configuration error: {e}")
exit(1)

# Create Bot instance
bot = WebexBot(
teams_bot_token=os.getenv("WEBEX_ACCESS_TOKEN"),
approved_rooms=Config.APPROVED_ROOMS,
bot_name=Config.BOT_NAME,
include_demo_commands=False,
help_command=CustomHelpCommand(),
proxies=proxies
)

# Register custom commands
bot.add_command(TestbedMainCommand())

# Start the bot (blocking call)
if __name__ == "__main__":
print("🚀 Starting Testbed Monitor Bot...")
print(f"📝 Bot Name: {Config.BOT_NAME}")
print(f"🔧 Approved Rooms: {len(Config.APPROVED_ROOMS)}")
bot.run()
print("✅ Bot is running! Press Ctrl+C to stop.")

🎨 Bot Features Deep Dive

Interactive Command Demo

Try the bot command simulator below:

💬 Bot Command Simulator

Webex Bot v1.0.8
// Type a command below

Custom Adaptive Cards

The bot uses Adaptive Cards for rich, interactive UI:

Main Menu Card Structure:

from webexpythonsdk.models.cards import AdaptiveCard, TextBlock, ActionSet
from webexpythonsdk.models.cards.actions import Submit

def create_main_menu():
card = AdaptiveCard(
body=[
TextBlock(
"🤖 Testbed Monitor Bot",
size="Large",
weight="Bolder",
color="Accent"
),
TextBlock(
"Choose an action:",
wrap=True
)
],
actions=[
Submit(title="📊 Check Status", data={"action": "status"}),
Submit(title="✍️ Register Testbed", data={"action": "register"}),
Submit(title="🔓 Release Testbed", data={"action": "release"}),
Submit(title="📢 Broadcast", data={"action": "broadcast"}),
]
)
return card.to_dict()

Broadcasting System

📡📢 Multi-Room Broadcasting

The bot can send notifications to multiple Webex rooms simultaneously. Perfect for:

  • Team coordination - Notify all stakeholders
  • Resource alerts - Broadcast availability changes
  • Scheduled maintenance - Inform users of downtime
  • Usage reports - Share testbed statistics

Broadcast Configuration (broadcast_rooms.json):

{
"broadcast_rooms": [
{
"name": "QA Team",
"room_id": "Y2lzY29zcGFyazovL...",
"description": "Quality assurance team"
},
{
"name": "DevOps Team",
"room_id": "Y2lzY29zcGFyazovL...",
"description": "Infrastructure team"
}
]
}

🚢 Deployment Options

For Testing and Development:

# Start bot in foreground
python example.py

# Output:
🚀 Starting Testbed Monitor Bot...
📝 Bot Name: Testbed Monitor Bot
🔧 Approved Rooms: 1
✅ Bot is running! Press Ctrl+C to stop.
⚡ WebSocket connected to Webex Cloud

💡Development Tips

Best practices for local development:

  • Use .env.local for local-specific configuration
  • Enable debug logging: logging.basicConfig(level=logging.DEBUG)
  • Test in private Webex room first
  • Use ngrok if you need to test webhooks
  • Monitor testbed_monitor.json changes in real-time

🔧 Advanced Configuration

Proxy Support

🔒🌐 Corporate Proxy Configuration

Many corporate environments require proxy configuration:

HTTP/HTTPS Proxy:

proxies = {
'https': 'http://proxy.company.com:80'
}

SOCKS5 Proxy (for WebSocket):

proxies = {
'wss': 'socks5://proxy.company.com:1080'
}

Authenticated Proxy:

proxies = {
'https': 'http://username:password@proxy.company.com:80'
}

In config.py:

@classmethod
def get_proxies(cls):
proxies = {}
if cls.HTTPS_PROXY:
proxies['https'] = cls.HTTPS_PROXY
if cls.WSS_PROXY:
proxies['wss'] = cls.WSS_PROXY
return proxies if proxies else None

Custom Logging

logging_config.py
import logging
from colorlog import ColoredFormatter

# Create colored formatter
formatter = ColoredFormatter(
"%(log_color)s%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt='%Y-%m-%d %H:%M:%S',
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red,bg_white',
}
)

# Configure handlers
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)

file_handler = logging.FileHandler('testbed_bot.log')
file_handler.setFormatter(logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
))

# Configure root logger
logging.basicConfig(
level=logging.INFO,
handlers=[console_handler, file_handler]
)

# Bot-specific logger
logger = logging.getLogger('testbed_bot')
logger.setLevel(logging.DEBUG)

Database Migration

Current Implementation - Simple and Portable:

✅ Advantages:

  • No external dependencies
  • Easy to read/edit manually
  • Simple backup (just copy file)
  • Works everywhere

❌ Limitations:

  • Not suitable for high concurrency
  • Limited query capabilities
  • No built-in transactions

🐛 Troubleshooting

🔧Common Issues & Solutions

Bot Not Responding

Symptoms:

  • Bot appears online but doesn't reply
  • Commands are ignored
  • No error messages

Solutions:

🔍 Issue Troubleshooter

Debug Mode

Enable detailed logging for troubleshooting:

debug_bot.py
import logging
import os
from webex_bot.webex_bot import WebexBot

# Enable DEBUG logging for all components
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# Enable webex_bot specific debug logs
logging.getLogger('webex_bot').setLevel(logging.DEBUG)
logging.getLogger('webexpythonsdk').setLevel(logging.DEBUG)
logging.getLogger('websockets').setLevel(logging.DEBUG)

# Start bot with debug info
bot = WebexBot(
teams_bot_token=os.getenv("WEBEX_ACCESS_TOKEN"),
bot_name="Testbed Monitor (DEBUG)",
include_demo_commands=True # Include demo commands for testing
)

bot.run()

Health Check Endpoint

Add health monitoring:

health_check.py
from datetime import datetime
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

class HealthCheckHandler(BaseHTTPRequestHandler):
bot_status = {
'started_at': datetime.utcnow().isoformat(),
'last_message': None,
'websocket_connected': False,
'messages_processed': 0
}

def do_GET(self):
if self.path == '/health':
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()

status = {
'status': 'healthy' if self.bot_status['websocket_connected'] else 'unhealthy',
'uptime': (datetime.utcnow() - datetime.fromisoformat(
self.bot_status['started_at']
)).total_seconds(),
**self.bot_status
}

self.wfile.write(json.dumps(status, indent=2).encode())
else:
self.send_response(404)
self.end_headers()

def log_message(self, format, *args):
pass # Suppress HTTP logs

def start_health_server(port=8080):
server = HTTPServer(('0.0.0.0', port), HealthCheckHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
print(f"✅ Health check server started on port {port}")
return server

# In your main bot script:
# health_server = start_health_server(8080)
# bot.run()

Test health endpoint:

curl http://localhost:8080/health

📊 Monitoring & Analytics

Usage Statistics

Track bot usage with metrics:

📈 Bot Analytics Dashboard

💬
1247
Total Commands
✍️
342
Registrations
🔓
318
Releases
📢
87
Broadcasts
👥
45
Active Users
0.8s
Avg Response

🎓 Best Practices

🔒Security

Never commit sensitive data:

  • Use .env files
  • Add .env to .gitignore
  • Use secret management tools
  • Rotate tokens regularly
  • Implement rate limiting

🛡️Error Handling

Robust error handling:

  • Try-except blocks everywhere
  • Log all errors with context
  • Graceful degradation
  • User-friendly error messages
  • Automatic retry logic

Performance

Optimize for speed:

  • Cache frequently used data
  • Async operations where possible
  • Database indexing
  • Minimize card complexity
  • Connection pooling

📊Monitoring

Track everything:

  • Command usage metrics
  • Response times
  • Error rates
  • User engagement
  • Resource utilization

🚀 Next Steps & Enhancements

Potential Enhancements:

  1. 📅 Calendar Integration

    • Sync with Google Calendar/Outlook
    • Automated scheduling
    • Conflict detection
    • Reminder notifications
  2. 📧 Email Notifications

    • Release reminders
    • Overdue alerts
    • Weekly summary reports
    • Team digests
  3. 🤖 AI/ML Features

    • Usage pattern analysis
    • Predictive availability
    • Smart recommendations
    • Anomaly detection
  4. 📱 Mobile Optimization

    • Responsive card designs
    • Push notifications
    • Mobile-first UI
    • Gesture support
  5. 🔗 CI/CD Integration

    • Jenkins/GitHub Actions hooks
    • Automated testbed allocation
    • Pipeline status updates
    • Test result reporting

📚 Resources & References

🔗 Official Documentation

📖 Learning Resources

🛠️ Tools & Utilities

🎉 Conclusion

🎊

You're Ready to Build!

You now have everything needed to create a production-ready Webex chatbot for testbed monitoring. Start small, iterate quickly, and scale as needed.

Key Takeaways

🔌

WebSocket Magic

No webhooks, no public IP, works behind firewalls

🎴

Rich UI

Adaptive Cards provide interactive, beautiful interfaces

📊

Real-time

Instant updates and bidirectional communication

🚀

Scalable

Start simple, scale to enterprise-grade deployments

🔒

Secure

Built-in authentication and authorization

🛠️

Extensible

Easy to add new features and integrations


Built with ❤️ using Webex, Python, and WebSockets

Questions? Issues? Visit the GitHub Issues page

Last updated: October 2025 | Version 1.0