Skip to content

Best Practices ​

Guidelines and recommendations for building robust, secure, and performant chat bots on the Sociogram platform.

Error Handling ​

Always implement proper error handling for both API calls and webhook processing:

javascript
async function sendMessageWithRetry(uid, message, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await bot.sendMessage(uid, message);
    } catch (error) {
      if (attempt === maxRetries) {
        console.error('Failed to send message after retries:', error);
        throw error;
      }
      console.warn(`Attempt ${attempt} failed, retrying...`);
      await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
    }
  }
}

Rate Limiting ​

Implement client-side rate limiting to respect the platform's limits:

javascript
class RateLimitedBot extends SociogramBot {
  constructor(token, baseUrl) {
    super(token, baseUrl);
    this.messageQueue = [];
    this.isProcessing = false;
  }

  async sendMessage(uid, message) {
    return new Promise((resolve, reject) => {
      this.messageQueue.push({ uid, message, resolve, reject });
      this.processQueue();
    });
  }

  async processQueue() {
    if (this.isProcessing || this.messageQueue.length === 0) return;

    this.isProcessing = true;

    while (this.messageQueue.length > 0) {
      const { uid, message, resolve, reject } = this.messageQueue.shift();

      try {
        const result = await super.sendMessage(uid, message);
        resolve(result);
      } catch (error) {
        reject(error);
      }

      // Wait 1 second between messages to respect rate limits
      if (this.messageQueue.length > 0) {
        await new Promise((resolve) => setTimeout(resolve, 1000));
      }
    }

    this.isProcessing = false;
  }
}

Security Considerations ​

  1. Token Security: Never expose your bot token in client-side code or public repositories
  2. Webhook Verification: Always verify the X-App-Key header in webhook requests
  3. Input Validation: Validate all user input before processing
  4. HTTPS: Always use HTTPS for your webhook endpoint

Performance Optimization ​

  1. Async Processing: Process webhooks asynchronously to avoid timeouts
  2. Database Caching: Cache user data and conversation state
  3. Message Queuing: Implement message queuing for high-traffic scenarios
  4. Monitoring: Add logging and monitoring for bot performance