@gamastudio/sendwave-provider
v0.0.22
Published
Librería para interactuar con Sendwave usando configuración dinámica.
Maintainers
Readme
📖 Sendwave Provider
A dynamic library for integrating and managing Sendwave instances for WhatsApp bot development.
🚀 Installation
npm install @gamastudio/sendwave-provider🔧 Basic Usage
Creating a Provider Instance
import { createSendWaveProvider } from "@gamastudio/sendwave-provider";
const provider = createSendWaveProvider({
name: "MyBot",
apiKey: "your-api-key-here",
port: 3000,
});
// Initialize the provider
await provider.initAll(provider.globalVendorArgs.port);
await provider.initVendor();Complete Configuration Options
import { createSendWaveProvider, type GlobalVendorArgs } from "@gamastudio/sendwave-provider";
const config: Partial<GlobalVendorArgs> = {
name: "MyBot", // Instance identifier
apiKey: "your-api-key", // Sendwave API key
port: 3000, // HTTP server port
delay: 1000, // Default delay between messages (ms)
linkPreview: true, // Enable/disable link previews
message: {
mergeMessage: false, // Enable message buffering
timeMergeMessage: 3, // Buffer timeout in seconds
},
queueFlow: {
enabled: true, // Enable queue flow system
warningTimeout: 30 * 60 * 1000, // 30 minutes before warning
endTimeout: 2 * 60 * 1000, // 2 minutes after warning to end session
warningMessage: "⏳ You seem to be inactive. Are you still there?",
},
};
const provider = createSendWaveProvider(config);📤 Sending Messages
Text Messages
await provider.sendText({
from: "573123456789",
text: "Hello! Welcome to our service.",
});Interactive Lists
await provider.sendList({
from: "573123456789",
list: {
title: "Select an option",
description: "Choose from the following options:",
button: "View Menu",
content: ["🛒 Catalog", "🎁 Promotions", "📞 Support"],
footerText: "Powered by Sendwave", // Optional
},
});
// Advanced list with sections
await provider.sendList({
from: "573123456789",
list: {
title: "Product Categories",
description: "Browse our products by category",
button: "Select Category",
content: [
{
title: "Electronics",
rows: [
{ title: "Smartphones", description: "Latest models available" },
{ title: "Laptops", description: "Gaming and office laptops" },
],
},
{
title: "Clothing",
rows: [
{ title: "Men's Fashion" },
{ title: "Women's Fashion" },
],
},
],
},
});Media Messages
// Images
await provider.sendImage({
from: "573123456789",
url: "https://example.com/image.jpg",
text: "Check out this product!",
});
// Videos
await provider.sendVideo({
from: "573123456789",
url: "https://example.com/video.mp4",
text: "Product demonstration",
});
// Documents
await provider.sendFile({
from: "573123456789",
url: "https://example.com/catalog.pdf",
fileName: "Product Catalog 2024.pdf",
text: "Here's our complete catalog",
});
// Voice Messages
await provider.sendVoice({
from: "573123456789",
url: "https://example.com/audio.mp3",
});Button Messages
await provider.sendButton({
from: "573123456789",
title: "Customer Support",
body: "How can we help you today?",
description: "Choose one of the options below",
footer: "We're here to help!",
buttons: [
{ type: "reply", text: "Technical Support" },
{ type: "reply", text: "Billing Questions" },
{ type: "url", text: "Visit Website" },
],
});🔄 Queue Flow System
The Queue Flow system automatically manages user sessions, handling timeouts and inactive users to optimize bot performance. Just enable it in the configuration and everything works automatically.
Enable Queue Flow (100% Automatic)
const provider = createSendWaveProvider({
name: "MyBot",
apiKey: "your-key",
queueFlow: {
enabled: true, // 🚀 That's it! Everything else is automatic
warningTimeout: 30 * 60 * 1000, // 30 minutes (optional)
endTimeout: 2 * 60 * 1000, // 2 minutes (optional)
warningMessage: "⏳ You seem inactive. Still there?", // (optional)
},
});✨ What happens automatically when enabled:
- User timeouts are reset on every message (no code needed)
- Warning messages are sent after inactivity period
- Users are automatically removed from queue after timeout
END_FLOWevent is triggered for BuilderBot integration- No additional code required in your flows!
Queue Flow Methods
// Reset user timeout (called automatically on user messages)
provider.resetUserTimeout("573123456789", "John Doe");
// Clear user timeout manually
provider.clearUserTimeout("573123456789");
// Force remove user from system
provider.forceClearUser("573123456789");
// Check if user is ignored
const isIgnored = provider.isUserIgnored("573123456789");
// Get system statistics
const stats = provider.getQueueFlowStats();
console.log(stats); // { activeTimeouts: 5, ignoredUsers: 2, config: {...} }Queue Flow Events
// Listen to user inactivity events
provider.onQueueFlowEvent('userInactive-573123456789', (data) => {
if (data.isActive) {
console.log(`Warning sent to ${data.from}`);
} else {
console.log(`User ${data.from} removed due to inactivity`);
}
});
// Remove event listeners
provider.offQueueFlowEvent('userInactive-573123456789');🤖 BuilderBot Integration
Flow Implementation Examples
import { addKeyword, EVENTS, utils } from "@builderbot/bot";
import { SendWaveProvider as Provider } from "@gamastudio/sendwave-provider";
// Welcome Flow
export const flowWelcome = addKeyword<Provider>(EVENTS.WELCOME)
.addAnswer([
"¡Hello! I'm *Max*, your virtual assistant. 😊",
"Welcome to our service.",
])
.addAction(async (_, { gotoFlow }) => await gotoFlow(flowMainMenu));
// End Flow (integrates with Queue Flow system)
export const flowEnd = addKeyword<Provider>(utils.setEvent("END_FLOW"))
.addAction(async (ctx, { endFlow, provider }) => {
// Clean up user from queue flow system
provider.forceClearUser(ctx.from);
endFlow("Chat closed due to inactivity. Write again if you need help!");
});
// Customer Support Flow
export const flowSupport = addKeyword<Provider>("SUPPORT")
.addAction(async (ctx, { blacklist, endFlow, provider }) => {
// Add to blacklist and clean queue
blacklist.add(ctx.from);
provider.forceClearUser(ctx.from);
return endFlow(
"An agent will contact you shortly. Thanks for your patience! 👨💻"
);
});
// Interactive Menu Flow
export const flowMainMenu = addKeyword<Provider>("MAIN_MENU")
.addAction(async (ctx, { provider }) => {
await provider.sendList({
from: ctx.from,
list: {
button: "View Menu",
title: "",
description: "Select an option from the menu. Let's get started! 👇",
content: ["🛒 Catalog", "🎁 Promotions", "📞 Support"],
},
});
})
.addAction({ capture: true }, async (ctx, { gotoFlow, fallBack }) => {
const option = ctx.body.trim();
switch (option) {
case "🛒 Catalog":
await gotoFlow(flowCatalog);
break;
case "🎁 Promotions":
await gotoFlow(flowPromotions);
break;
case "📞 Support":
await gotoFlow(flowSupport);
break;
default:
fallBack("I didn't understand that option. Please select from the list.");
break;
}
});Delayed Response Handling (100% Automatic)
The Queue Flow system automatically handles users who take time to respond with zero configuration needed:
// ✅ AUTOMATIC PROCESS:
// 1. User sends message -> timeout resets automatically
// 2. After 30 minutes of inactivity -> warning message sent automatically
// 3. After 2 more minutes -> user session ends with END_FLOW event automatically
// 4. User is cleaned from queue automatically
// 🎯 ONLY THING YOU NEED: Handle the END_FLOW event in your flows
export const flowEnd = addKeyword<Provider>(utils.setEvent("END_FLOW"))
.addAction(async (ctx, { endFlow }) => {
// This runs automatically when user is inactive for too long
endFlow("Session ended due to inactivity. Contact us again anytime!");
// ✨ Queue cleanup happens automatically, no code needed!
});🎯 Event System
// Connection events
provider.on('ready', (isReady: boolean) => {
console.log('Connection status:', isReady ? 'Connected' : 'Disconnected');
});
provider.on('auth_failure', (error) => {
console.error('Authentication failed:', error);
});
// Message events
provider.on('message', (ctx) => {
console.log(`Message from ${ctx.from}: ${ctx.body}`);
});
provider.on('user-message', (data) => {
console.log(`User message: ${data.body}`);
// Timeout automatically resets here if queue flow is enabled
});🛠️ Development Scripts
| Script | Description |
| --------------- | ------------------------------------------------ |
| npm run dev | Run library in development mode with auto-reload |
| npm run build | Compile TypeScript and resolve path aliases |
| npm run test | Run basic test file |
📦 Package Structure
When you install @gamastudio/sendwave-provider:
- Compiled code in
/builddirectory - TypeScript declarations (
.d.ts) included - Main entry point:
build/index.js - Full TypeScript support with path aliases resolved
📋 Requirements
- Node.js 18+
- npm or pnpm
- TypeScript 5+
- Valid Sendwave API credentials
🔥 Important Notes
This library is in beta state and subject to internal changes.
Recommendations:
- Use in testing or controlled environments initially
- Update beta versions as new releases become available
- Monitor the queue flow system performance with your user base
🏗️ Architecture
- Provider Layer: Main SendWaveProvider class extending BuilderBot
- Core Layer: Message processing and webhook handling
- Sender Layer: Message sending functionality with media support
- Queue Flow: Advanced user session management with timeout handling
- Utils: Media detection, message parsing, and flow utilities
📜 License
ISC License © 2025 - Ameth Galarcio
