/**
* Advanced Usage Example for MCP OpenClaw
*
* This example demonstrates advanced features including:
* - Error handling
* - Batch operations
* - Concurrent requests
* - Retry logic
*/
import { OpenClawClient, OpenClawApiError } from '../src/openclaw-client';
import type {
SendMessageParams,
ExecuteCommandParams,
CreateCalendarEventParams,
SendEmailParams,
} from '../src/types';
/**
* Example 1: Error handling
*/
async function exampleErrorHandling(client: OpenClawClient) {
console.log('=== Example 1: Error Handling ===\n');
try {
// Try to send with invalid platform
const result = await client.sendMessage({
platform: 'invalid' as any,
recipient: '@user',
message: 'Test',
});
console.log('Handled invalid platform:', result);
} catch (error) {
if (error instanceof OpenClawApiError) {
console.error(`API Error [${error.code}]: ${error.message}`);
}
}
console.log('');
}
/**
* Example 2: Batch messaging
*/
async function exampleBatchMessaging(client: OpenClawClient) {
console.log('=== Example 2: Batch Messaging ===\n');
const recipients = ['@user1', '@user2', '@user3'];
const message = 'This is a batch message from OpenClaw!';
const promises = recipients.map((recipient) =>
client.sendMessage({
platform: 'telegram',
recipient,
message,
})
);
const results = await Promise.allSettled(promises);
let successCount = 0;
let failureCount = 0;
results.forEach((result, index) => {
if (result.status === 'fulfilled' && result.value.success) {
successCount++;
console.log(` ✓ Sent to ${recipients[index]}`);
} else {
failureCount++;
console.log(` ✗ Failed to send to ${recipients[index]}`);
}
});
console.log(`\nSummary: ${successCount} succeeded, ${failureCount} failed`);
console.log('');
}
/**
* Example 3: Polling task completion
*/
async function exampleTaskPolling(client: OpenClawClient) {
console.log('=== Example 3: Task Polling ===\n');
// Start a long-running command
const { taskId } = await client.executeCommand({
command: 'sleep 10 && echo "Task complete"',
timeout: 120,
async: true,
});
if (!taskId) {
console.log('Failed to start task');
return;
}
console.log(`Started task: ${taskId}`);
console.log('Polling for completion...');
const startTime = Date.now();
let attempts = 0;
const maxAttempts = 30;
while (attempts < maxAttempts) {
const status = await client.getTaskStatus({ taskId });
attempts++;
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
if (status.status === 'completed') {
console.log(`\n✓ Task completed after ${elapsed}s`);
console.log(`Output: ${status.output}`);
return;
}
if (status.status === 'failed') {
console.log(`\n✗ Task failed after ${elapsed}s`);
console.log(`Error: ${status.error}`);
return;
}
process.stdout.write(`\r [${elapsed}s] Status: ${status.status}...`);
await new Promise((resolve) => setTimeout(resolve, 1000));
}
console.log('\n\nTask timed out');
console.log('');
}
/**
* Example 4: Creating recurring calendar events
*/
async function exampleRecurringEvents(client: OpenClawClient) {
console.log('=== Example 4: Recurring Calendar Events ===\n');
// Create events for the next 4 weeks
const today = new Date();
const events: CreateCalendarEventParams[] = [];
for (let week = 1; week <= 4; week++) {
const eventDate = new Date(today);
eventDate.setDate(today.getDate() + (week * 7));
eventDate.setHours(14, 0, 0, 0);
events.push({
title: `Weekly Team Sync - Week ${week}`,
description: 'Recurring weekly team meeting',
startTime: eventDate.toISOString(),
endTime: new Date(eventDate.getTime() + 60 * 60 * 1000).toISOString(),
location: 'Conference Room B',
attendees: ['team@example.com'],
reminder: 30,
});
}
const results = await Promise.allSettled(
events.map((event) => client.createCalendarEvent(event))
);
const created = results.filter((r) => r.status === 'fulfilled' && (r.value as any).success).length;
console.log(`Created ${created}/${events.length} recurring events`);
console.log('');
}
/**
* Example 5: Email with attachments simulation
*/
async function exampleAdvancedEmail(client: OpenClawClient) {
console.log('=== Example 5: Advanced Email ===\n');
const htmlBody = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
.container { max-width: 600px; margin: 0 auto; }
h1 { color: #333; }
.button { background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; }
</style>
</head>
<body>
<div class="container">
<h1>Welcome to OpenClaw</h1>
<p>This is an HTML email example.</p>
<a href="https://example.com" class="button">Click Here</a>
</div>
</body>
</html>
`;
const emailParams: SendEmailParams = {
to: ['recipient1@example.com', 'recipient2@example.com'],
cc: 'manager@example.com',
subject: 'HTML Email from OpenClaw',
body: htmlBody,
html: true,
};
const result = await client.sendEmail(emailParams);
console.log('Email result:', JSON.stringify(result, null, 2));
console.log('');
}
/**
* Example 6: Chained operations
*/
async function exampleChainedOperations(client: OpenClawClient) {
console.log('=== Example 6: Chained Operations ===\n');
// Step 1: Execute command to generate report
console.log('Step 1: Generating report...');
const { taskId: reportTaskId } = await client.executeCommand({
command: './generate-report.sh',
timeout: 300,
async: true,
});
// Step 2: Wait for completion
if (reportTaskId) {
let reportStatus = await client.getTaskStatus({ taskId: reportTaskId });
while (reportStatus.status === 'running' || reportStatus.status === 'pending') {
await new Promise((resolve) => setTimeout(resolve, 2000));
reportStatus = await client.getTaskStatus({ taskId: reportTaskId });
}
if (reportStatus.status === 'completed') {
console.log(' ✓ Report generated');
// Step 3: Create calendar event for review
console.log('Step 2: Scheduling review meeting...');
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(15, 0, 0, 0);
await client.createCalendarEvent({
title: 'Report Review',
description: 'Review the generated report',
startTime: tomorrow.toISOString(),
endTime: new Date(tomorrow.getTime() + 60 * 60 * 1000).toISOString(),
});
console.log(' ✓ Meeting scheduled');
// Step 4: Send notification
console.log('Step 3: Sending notification...');
await client.sendMessage({
platform: 'telegram',
recipient: '@team',
message: 'Report has been generated and review meeting scheduled for tomorrow at 3 PM.',
});
console.log(' ✓ Notification sent');
}
}
console.log('');
}
/**
* Main execution
*/
async function main() {
const client = new OpenClawClient({
apiUrl: process.env.OPENCLAW_API_URL || 'https://api.openclaw.example.com',
apiKey: process.env.OPENCLAW_API_KEY || 'your-api-key',
timeout: 30000,
});
// Run all examples
await exampleErrorHandling(client);
await exampleBatchMessaging(client);
await exampleTaskPolling(client);
await exampleRecurringEvents(client);
await exampleAdvancedEmail(client);
await exampleChainedOperations(client);
client.close();
console.log('All examples completed!');
}
// Run if executed directly
if (require.main === module) {
main().catch(console.error);
}
export {
exampleErrorHandling,
exampleBatchMessaging,
exampleTaskPolling,
exampleRecurringEvents,
exampleAdvancedEmail,
exampleChainedOperations,
};