A demonstration chatbot showcasing the capabilities of the @green-api/whatsapp-chatbot-js-v2 library, using the API service for WhatsApp green-api.com. This chatbot demonstrates various GREEN-API features including message sending, file handling, polls, contacts, and group management using a state-based architecture.
-
Node.js Installation
- Download and install the latest version of Node.js from the official website
- Verify installation by running:
node -v
-
Project Setup
# Clone the repository git clone https://github.com/green-api/whatsapp-demo-chatbot-js-v2 # Install dependencies cd whatsapp-demo-chatbot-js-v2 npm install
-
GREEN-API Account Setup
- Register at GREEN-API
- Create your first instance and copy its
idInstance
andapiTokenInstance
-
Environment Configuration Create a
.env
file in the project root:INSTANCE_ID=your_instance_id INSTANCE_TOKEN=your_api_token
bot.ts
- Main bot implementationstrings.yml
- Multi-language message strings.env
- Environment configuration
The chatbot uses a state-based architecture with three main states:
-
Start State (
startState
)- Entry point for all conversations
- Handles language selection
- Available languages: EN, KZ, RU, ES, HE, AR
- Transitions to Main state upon language selection
-
Main State (
mainState
)- Central hub for all functionality
- Handles 13 different demo commands
- Processes poll updates
- Manages transitions to Create Group state
-
Create Group State (
createGroupState
)- Handles group creation flow
- Manages bot contact addition
- Sets group avatar and initial message
- Stop commands (
stop
,0
) - Return to language selection - Menu commands (
menu
,меню
) - Return to main menu - Fallback handler for unrecognized messages
This demo bot also showcases how to integrate the @green-api/whatsapp-chatgpt
library as a message processor within a state-based
architecture. The integration is done through a dedicated GPT state that manages the conversation with the GPT model.
const gptBot = new WhatsappGptBot({
idInstance: process.env.INSTANCE_ID!,
apiTokenInstance: process.env.INSTANCE_TOKEN!,
openaiApiKey: process.env.OPENAI_API_KEY!,
model: "gpt-4o",
maxHistoryLength: 15,
systemMessage: "You are a helpful WhatsApp assistant created by GREEN-API. Answer concisely but informatively.",
temperature: 0.7,
});
interface CustomSessionData {
lang?: string;
gptSession?: GPTSessionData;
}
const gptState: State<CustomSessionData> = {
name: "gpt_state",
async onEnter(message, data) {
const lang = data?.lang || "en";
await bot.sendText(message.chatId, strings.chat_gpt_intro[lang]);
// Initialize GPT session with system message
data.gptSession = {
messages: [{role: "system", content: gptBot.systemMessage}],
lastActivity: Date.now(),
};
},
async onMessage(message, data) {
const lang = data?.lang || "en";
const exitCommands = [
"menu", "меню", "exit", "выход", "stop", "стоп", "back", "назад",
"menú", "salir", "parar", "atrás", "תפריט", "יציאה", "עצור", "חזור",
"мәзір", "шығу", "тоқта", "артқа",
];
// Handle exit commands
if (exitCommands.includes(message.text?.toLowerCase() || "")) {
return {state: "main", data};
}
try {
// Process message through GPT
const {response, updatedData} = await gptBot.processMessage(
message,
data.gptSession
);
await bot.sendText(message.chatId, response);
data.gptSession = updatedData;
return undefined;
} catch (error) {
console.error("Error in GPT processing:", error);
await bot.sendText(message.chatId, strings.chat_gpt_error[lang]);
return undefined;
}
}
};
-
State-Based Integration
- GPT functionality is encapsulated in a dedicated state
- Seamless integration with existing bot states
- Clean transition between regular and GPT modes
-
Session Management
- GPT conversation history stored in state data
- Preserved across messages within the same session
- Proper cleanup on state exit
-
Multilingual Support
- Exit commands in multiple languages
- Language-specific error messages
- Select option 14 from the main menu to enter GPT mode
- Chat naturally with the GPT model
- Use any of the exit commands to return to the main menu
- The conversation history is maintained within the session
-
Launch
npm run start
Or to see additional debug information:
npm run start:debug
-
Initialization Process
- Clears webhook queue
- Begins message processing
-
Instance Settings The bot automatically configures these settings:
{ "webhookUrl": "", "webhookUrlToken": "", "outgoingWebhook": "no", "stateWebhook": "no", "incomingWebhook": "yes", "outgoingAPIMessageWebhook": "no", "outgoingMessageWebhook": "no", "pollMessageWebhook": "yes", "markIncomingMessagesReaded": "yes" }
Users first select their preferred language:
1 - English
2 - Kazakh
3 - Russian
4 - Spanish
5 - Hebrew
After language selection, users can test various WhatsApp API features:
-
Text Messages (📩)
- Demonstrates basic text sending
- Shows message formatting options
-
File Sharing (📋)
- PDF document sharing
- Shows file upload capabilities
-
Image Sharing (🖼)
- Image sending with captions
- Demonstrates media handling
-
Audio Messages (🎵)
- Audio file sharing
- Supports multiple formats
-
Video Messages (📽)
- Video file sharing
- Demonstrates large media handling
-
Contact Sharing (👤)
- Contact card creation
- vCard format handling
-
Location Sharing (📍)
- Static location sending
- Includes address and coordinates
-
Polls (📊)
- Poll creation
- Vote handling
- Multiple choice support
-
Avatar Handling (🖼)
- Profile picture retrieval
- Avatar URL handling
-
Link Preview (🔗)
- URL preview toggling
- Link formatting options
-
Group Creation (👥)
- Contact addition flow
- Group picture setting
- Invite link generation
-
Message Quoting (💬)
- Reply to specific messages
-
About Section (ℹ️)
- Library information
- Documentation links
- Support resources
stop
or0
- Return to language selectionmenu
orменю
- Show available options
const startState: State<CustomSessionData> = {
name: "start",
async onEnter(message) {
await bot.sendText(message.chatId, strings.select_language);
},
async onMessage(message, data) {
// Handler implementation
}
};
await bot.sendFileByUrl(message.chatId, {
url: "https://example.com/file.pdf",
fileName: "document.pdf",
caption: "File caption"
});
const group = await bot.api.group.createGroup(
groupName,
[message.chatId]
);
if (group.created) {
await bot.api.group.setGroupPicture(
group.chatId,
"assets/group_avatar.jpg"
);
}
Licensed under Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0).