Skip to content

--

Demo Bot Example#

See our demo chatbot for a comprehensive demo chatbot, demonstrating many features:

import {
GPTSessionData,
ImageMessageHandler,
ProcessMessageMiddleware,
ProcessResponseMiddleware,
WhatsappGptBot,
OpenAIModel,
} from "@green-api/whatsapp-chatgpt";
import * as dotenv from "dotenv";
import { Message } from "@green-api/whatsapp-chatbot-js-v2";
import { ChatCompletionMessageParam } from "openai/resources/chat/completions";
import OpenAI from "openai";

dotenv.config();

// Custom image handler with enhanced descriptions
class EnhancedImageHandler extends ImageMessageHandler {
async processMessage(message: Message, openai: OpenAI, model: OpenAIModel): Promise<any> {
const result = await super.processMessage(message, openai, model);

if (typeof result === "string") {
return result.replace(
"[The user sent an image",
"[The user sent an image. Let them know that you are not the model they should use"
);
}

return result;
}
}

// Middleware examples

// Logging middleware
const loggingMessageMiddleware: ProcessMessageMiddleware = async (
message, messageContent, messages, _
) => {
console.log(`[${new Date().toISOString()}] User (${message.chatId}): `,
typeof messageContent === "string"
? messageContent
: JSON.stringify(messageContent));

return {messageContent, messages};
};

// Initialize the bot
const bot = new WhatsappGptBot({
idInstance: process.env.INSTANCE_ID || "",
apiTokenInstance: process.env.INSTANCE_TOKEN || "",
openaiApiKey: process.env.OPENAI_API_KEY || "",
model: "gpt-4o",
systemMessage: "You are a useful WhatsApp assistant created by GREEN-API",
maxHistoryLength: 15,
temperature: 0.5,
handlersFirst: true,
clearWebhookQueueOnStart: true,
});

// Command handlers
bot.onText("/help", async (message, _) => {
const helpText = `*WhatsAppGPT Demo Bot*\n\nAvailable commands:\n- /help - Show this help message\n- /clear - Clear the chat history`;
await bot.sendText(message.chatId, helpText);
});

// Register middleware
bot.addMessageMiddleware(loggingMessageMiddleware);

// Replace default handlers
bot.replaceHandler(ImageMessageHandler, new EnhancedImageHandler());

// Start the bot
bot.start();

This demo bot includes:

  • Custom message handlers
  • Various middleware implementations
  • Command handlers
  • Custom type handlers
  • Error handling

More examples#

Multilingual bot#

import { WhatsappGptBot } from '@green-api/whatsapp-chatgpt';
import { detectLanguage } from './language-detector';

const bot = new WhatsappGptBot({
idInstance: "your-instance-id",
apiTokenInstance: "your-token",
openaiApiKey: "your-openai-api-key",
model: "gpt-4o"
});

// Add language detection middleware
bot.addMessageMiddleware(async (message, content, messages, sessionData) => {
// Process only text messages
if (message.type !== 'text' || !message.text) {
return {messageContent: content, messages};
}

// Detect language
const language = await detectLanguage(message.text);

// Store language in session
if (!sessionData.context) {
sessionData.context = {variables: {}};
}
sessionData.context.variables.language = language;

// Update system message with language instruction
const languageInstruction = `User writes in ${language}. Reply in the same language.`;

// Find system message
const systemIndex = messages.findIndex(m => m.role === 'system');

if (systemIndex >= 0) {
// Update an existing system message
const updatedMessages = [...messages];
const currentContent = updatedMessages[systemIndex].content;
if (typeof currentContent === 'string' && !currentContent.includes('User writes to')) {
updatedMessages[systemIndex].content = `${currentContent} ${languageInstruction}`;
}
return {messageContent: content, messages: updatedMessages};
} else {
// Add a new system message
return {
messageContent: content,
messages: [
{role: 'system', content: languageInstruction},
...messages
]
};
}
});

// Start the bot
bot.start();