Yaltopia-Homes-TGClient/docs/WEBHOOK_INTEGRATION_GUIDE.md
2026-01-08 19:06:12 +03:00

5.8 KiB

🔗 Webhook Integration Guide

📋 Current Status: Optimized Mode (No Backend Required)

Your bot currently uses optimized polling mode which works perfectly without any backend integration. It checks for new listings every 6 hours and sends notifications to users.

🚀 Future Webhook Integration (When Backend is Ready)

Step 1: Enable Webhook Mode

# Change in .env file
NOTIFICATION_MODE=full  # Instead of 'optimized'
WEBHOOK_PORT=3001
WEBHOOK_HOST=your-domain.com

Step 2: Backend Integration Required

Your backend will need to send HTTP POST requests to the bot when:

New Listing Created:

// Backend code example
const notifyBot = async (listing) => {
  try {
    await fetch('http://your-bot-server:3001/webhook/new-listing', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        id: listing.id,
        title: listing.title,
        type: listing.type,        // "RENT" or "SALE"
        price: listing.price,      // Number
        subcity: listing.subcity,  // "Bole", "Kirkos", etc.
        houseType: listing.houseType, // "Apartment", "Villa", etc.
        status: listing.status,    // "ACTIVE", "DRAFT"
        createdAt: listing.createdAt
      })
    });
    console.log('Bot notified of new listing');
  } catch (error) {
    console.error('Failed to notify bot:', error);
  }
};

// Call this after creating a listing
const newListing = await createListing(data);
await notifyBot(newListing);

Listing Updated:

// When listing is updated (price change, status change, etc.)
const notifyBotUpdate = async (listing) => {
  await fetch('http://your-bot-server:3001/webhook/update-listing', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(listing)
  });
};

Step 3: Benefits After Integration

Feature Current (Optimized) With Webhook
Notification Speed Up to 6 hours 2-5 seconds
User Experience Good Excellent
Server Load Low Very Low
Setup Complexity Simple Requires backend

🛠️ Backend Requirements

When to Send Webhooks:

  1. New listing created with status "ACTIVE"
  2. Listing updated (price, location, type changes)
  3. Listing status changed to "ACTIVE"
  4. Don't send for "DRAFT" listings
  5. Don't send for deleted listings

Webhook Payload Format:

{
  "id": "listing-uuid",
  "title": "2BR Apartment in Bole",
  "type": "RENT",
  "price": 50000,
  "subcity": "Bole", 
  "houseType": "Apartment",
  "status": "ACTIVE",
  "createdAt": "2026-01-08T10:00:00Z",
  "updatedAt": "2026-01-08T10:00:00Z"
}

Error Handling:

const notifyBotWithRetry = async (listing, maxRetries = 3) => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch('http://bot:3001/webhook/new-listing', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(listing),
        timeout: 5000
      });
      
      if (response.ok) {
        console.log('Bot notified successfully');
        return;
      }
    } catch (error) {
      console.log(`Webhook attempt ${i + 1} failed:`, error.message);
      if (i < maxRetries - 1) {
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); // Exponential backoff
      }
    }
  }
  console.error('Failed to notify bot after all retries');
};

🔄 Migration Plan (Future)

Phase 1: Preparation (Now)

  • Keep optimized mode
  • Webhook code ready in bot
  • Documentation prepared

Phase 2: Backend Development

  • Add webhook calls to backend
  • Test webhook endpoints
  • Implement error handling

Phase 3: Integration

  • Change NOTIFICATION_MODE=full
  • Test real-time notifications
  • Monitor webhook performance

Phase 4: Optimization

  • Fine-tune webhook reliability
  • Add webhook authentication
  • Implement webhook queuing

🧪 Testing Webhook (When Ready)

Manual Test:

# Test new listing webhook
curl -X POST http://your-bot:3001/webhook/new-listing \
  -H "Content-Type: application/json" \
  -d '{
    "id": "test-123",
    "title": "Test Property",
    "type": "RENT",
    "price": 45000,
    "subcity": "Bole",
    "houseType": "Apartment",
    "status": "ACTIVE",
    "createdAt": "2026-01-08T10:00:00Z"
  }'

Expected Response:

{
  "success": true,
  "message": "Listing processed successfully",
  "listingId": "test-123"
}

📊 Monitoring Webhooks

Health Check:

curl http://your-bot:3001/webhook/health

Status Check:

curl http://your-bot:3001/status

🔒 Security Considerations (Future)

Authentication:

// Add API key authentication
const WEBHOOK_API_KEY = process.env.WEBHOOK_API_KEY;

app.use('/webhook', (req, res, next) => {
  const apiKey = req.headers['x-api-key'];
  if (apiKey !== WEBHOOK_API_KEY) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  next();
});

IP Whitelisting:

const ALLOWED_IPS = ['your.backend.ip', '127.0.0.1'];

app.use('/webhook', (req, res, next) => {
  const clientIP = req.ip;
  if (!ALLOWED_IPS.includes(clientIP)) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  next();
});

💡 Summary

Current Setup: Perfect for now! Your bot works great with optimized polling.

Future Integration: When your backend is ready, simply:

  1. Add webhook calls to backend
  2. Change NOTIFICATION_MODE=full
  3. Restart bot
  4. Enjoy real-time notifications!

The webhook infrastructure is already built and ready - you just need to flip the switch when your backend supports it! 🚀