{"id":28171207,"url":"https://github.com/green-api/whatsapp-chatgpt-js","last_synced_at":"2026-03-02T17:05:15.023Z","repository":{"id":293402739,"uuid":"914275601","full_name":"green-api/whatsapp-chatgpt-js","owner":"green-api","description":"This is a library for creating WhatsApp bot with OpenAI GPT integration, built on GREEN-API.","archived":false,"fork":false,"pushed_at":"2025-05-05T08:28:33.000Z","size":58,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-05-15T06:49:09.974Z","etag":null,"topics":["openai","openai-chatgpt","whatsapp","whatsapp-api","whatsapp-bot","whatsapp-chat","whatsapp-chatbot","whatsapp-js"],"latest_commit_sha":null,"homepage":"https://green-api.com/en","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/green-api.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-01-09T09:31:31.000Z","updated_at":"2025-05-05T08:28:36.000Z","dependencies_parsed_at":"2025-05-15T06:49:15.813Z","dependency_job_id":"1c2394a2-d9eb-4129-b400-6d7418a73eab","html_url":"https://github.com/green-api/whatsapp-chatgpt-js","commit_stats":null,"previous_names":["green-api/whatsapp-chatgpt-js"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-chatgpt-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-chatgpt-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-chatgpt-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-chatgpt-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/green-api","download_url":"https://codeload.github.com/green-api/whatsapp-chatgpt-js/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254394692,"owners_count":22063985,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["openai","openai-chatgpt","whatsapp","whatsapp-api","whatsapp-bot","whatsapp-chat","whatsapp-chatbot","whatsapp-js"],"created_at":"2025-05-15T18:16:19.876Z","updated_at":"2026-03-02T17:05:14.784Z","avatar_url":"https://github.com/green-api.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# WhatsApp GPT Bot Library\n\nA modern, state-based WhatsApp bot library with OpenAI GPT integration, built on top of GREEN-API and\n@green-api/whatsapp-chatbot-js-v2.\n\n## Features\n\n- OpenAI GPT model integration for intelligent responses\n- Support for multiple GPT models (GPT-3.5, GPT-4, GPT-4o)\n- Multimodal capabilities with image processing support\n- Voice message transcription\n- Comprehensive message handling for various WhatsApp media types\n- Middleware architecture for customizing message and response processing\n- Built-in conversation history management\n- State-based conversation flow inherited from base library\n- TypeScript support\n\n## Installation\n\n```bash\nnpm install @green-api/whatsapp-chatgpt\n```\n\nThe dependencies (`openai` and `@green-api/whatsapp-chatbot-js-v2`) will be installed automatically.\n\n## Quick Start\n\n```typescript\nimport { WhatsappGptBot } from '@green-api/whatsapp-chatgpt';\n\n// Initialize the bot\nconst bot = new WhatsappGptBot({\n    idInstance: \"your-instance-id\",\n    apiTokenInstance: \"your-token\",\n    openaiApiKey: \"your-openai-api-key\",\n    model: \"gpt-4o\",\n    systemMessage: \"You are a helpful assistant.\"\n});\n\n// Start the bot\nbot.start();\n```\n\n# Usage Patterns\n\nThis library supports two distinct usage patterns depending on your needs:\n\n## 1. Standalone Bot\n\nYou can run the bot as a standalone service that listens for and processes WhatsApp messages automatically:\n\n```typescript\nconst bot = new WhatsappGptBot({\n    idInstance: \"your-instance-id\",\n    apiTokenInstance: \"your-token\",\n    openaiApiKey: \"your-openai-api-key\",\n    model: \"gpt-4o\",\n    systemMessage: \"You are a helpful assistant.\"\n});\n\n// Start listening for webhooks and processing messages\nbot.start();\n```\n\n## 2. Message Processor\n\nAlternatively, you can use the bot as a message processing utility within your own bot or application:\n\n```typescript\nconst gptBot = new WhatsappGptBot({\n    idInstance: \"your-instance-id\",\n    apiTokenInstance: \"your-token\",\n    openaiApiKey: \"your-openai-api-key\",\n    model: \"gpt-4o\",\n    systemMessage: \"You are a helpful assistant.\"\n});\n\n// No need to call start() - just use processMessage when needed\nconst {response, updatedData} = await gptBot.processMessage(message, sessionData);\n\n// Handle the response in your own way\nawait yourBot.sendText(message.chatId, response);\n\n// Store the updated session data in your own state system\nyourSessionData.gptSession = updatedData;\n```\n\n### Integration Example\n\nHere's how to integrate the GPT bot into your own state-based bot:\n\n```typescript\ninterface CustomSessionData {\n    lang?: string;\n    gptSession?: GPTSessionData;  // Store GPT session data\n}\n\nconst gptState: State\u003cCustomSessionData\u003e = {\n    name: \"gpt_state\",\n    async onEnter(message, data) {\n        // Initialize GPT session\n        data.gptSession = {\n            messages: [{role: \"system\", content: gptBot.systemMessage}],\n            lastActivity: Date.now()\n        };\n        await bot.sendText(message.chatId, \"Chat with GPT started!\");\n    },\n    async onMessage(message, data) {\n        // Process messages using GPT bot\n        const {response, updatedData} = await gptBot.processMessage(\n                message,\n                data.gptSession\n        );\n\n        await bot.sendText(message.chatId, response);\n        data.gptSession = updatedData;\n\n        return undefined;  // Stay in current state\n    }\n};\n```\n\nThis flexibility allows you to either run the bot independently or integrate its GPT capabilities into a larger system\nwhile maintaining full control over the conversation flow and state management.\n\nKey points about these patterns:\n\n1. **Standalone Bot**\n    - Uses internal state management\n    - Handles webhooks automatically\n    - Better for simple, single-purpose GPT chatbots\n    - Requires calling `bot.start()`\n\n2. **Message Processor**\n    - No internal state management needed\n    - No webhook handling\n    - Perfect for integration into existing bots\n    - Uses only the GPT processing capabilities\n    - More flexible and controllable\n    - Never call `start()` - just use `processMessage()`\n\n## Core Components\n\n### Bot Configuration\n\nComplete configuration options for the WhatsappGptBot:\n\n```typescript\ninterface GPTBotConfig extends BotConfig {\n    /** OpenAI API key */\n    openaiApiKey: string;\n\n    /** Model to use for chat completion (default: gpt-4o) */\n    model?: OpenAIModel;\n\n    /** Maximum number of messages to keep in conversation history (default: 10) */\n    maxHistoryLength?: number;\n\n    /** System message to set assistant behavior */\n    systemMessage?: string;\n\n    /** Temperature for response generation (default: 0.5) */\n    temperature?: number;\n\n    /** Default reply when an error occurs */\n    errorMessage?: string;\n\n    // All configuration options from the base WhatsAppBot are also available\n    // See @green-api/whatsapp-chatbot-js-v2 for additional options\n}\n```\n\n### WhatsappGptBot\n\nMain class for creating and managing your OpenAI-powered WhatsApp bot:\n\n```typescript\nconst bot = new WhatsappGptBot({\n    // Required parameters\n    idInstance: \"your-instance-id\",\n    apiTokenInstance: \"your-token\",\n    openaiApiKey: \"your-openai-api-key\",\n\n    // Optional GPT-specific parameters\n    model: \"gpt-4o\",\n    maxHistoryLength: 15,\n    systemMessage: \"You are a helpful assistant specializing in customer support.\",\n    temperature: 0.7,\n    errorMessage: \"Sorry, I couldn't process your request. Please try again.\",\n\n    // Optional parameters from base bot\n    defaultState: \"greeting\",\n    sessionTimeout: 300,\n    // See base library documentation for more options\n});\n```\n\n## Message Handling\n\nThe bot automatically handles different types of WhatsApp messages and converts them into a format understood by\nOpenAI's models.\n\n### Supported Message Types\n\n- **Text**: Regular text messages\n- **Image**: Photos with optional captions (supported in vision-capable models)\n- **Audio**: Voice messages with automatic transcription\n- **Video**: Video messages with captions\n- **Document**: File attachments\n- **Poll**: Poll messages and poll updates\n- **Location**: Location sharing\n- **Contact**: Contact sharing\n\n### Message Handler Registry\n\nThe bot uses a registry of message handlers to process different message types:\n\n```typescript\n// Access the registry\nconst registry = bot.messageHandlers;\n\n// Create a custom message handler\nclass CustomMessageHandler implements MessageHandler {\n    canHandle(message: Message): boolean {\n        return message.type === \"custom-type\";\n    }\n\n    async processMessage(message: Message): Promise\u003cany\u003e {\n        // Process the message\n        return \"Processed content\";\n    }\n}\n\n// Register the custom handler\nbot.registerMessageHandler(new CustomMessageHandler());\n\n// Replace an existing handler\nbot.replaceHandler(TextMessageHandler, new CustomTextHandler());\n```\n\n## Middleware System\n\nThe middleware system allows for customizing message processing before sending to GPT and response processing before\nsending back to the user.\n\n### Adding Message Middleware\n\n```typescript\n// Process messages before sending to GPT\nbot.addMessageMiddleware(async (message, messageContent, messages, sessionData) =\u003e {\n    // Add custom context to the conversation\n    if (message.type === \"text\" \u0026\u0026 message.chatId.endsWith(\"@c.us\")) {\n        // Add user information from a database\n        const userInfo = await getUserInfo(message.chatId);\n\n        // Modify the current message content\n        const enhancedContent = `[User: ${userInfo.name}] ${messageContent}`;\n\n        return {\n            messageContent: enhancedContent,\n            messages\n        };\n    }\n\n    return {\n        messageContent,\n        messages\n    };\n});\n```\n\n### Adding Response Middleware\n\n```typescript\n// Process GPT responses before sending to user\nbot.addResponseMiddleware(async (response, messages, sessionData) =\u003e {\n    // Format or modify the response\n    const formattedResponse = response\n            .replace(/\\bGPT\\b/g, \"Assistant\")\n            .trim();\n\n    // You can also modify the messages that will be saved in history\n    return {\n        response: formattedResponse,\n        messages\n    };\n});\n```\n\n## Session Data\n\nThe GPT bot extends the base session data with conversation-specific information:\n\n```typescript\ninterface GPTSessionData {\n    /** Conversation history */\n    messages: ChatCompletionMessageParam[];\n\n    /** Timestamp of last activity */\n    lastActivity: number;\n\n    /** Custom user state data */\n    userData?: Record\u003cstring, any\u003e;\n\n    /** Context for the current conversation */\n    context?: {\n        /** Tags or metadata for the conversation */\n        tags?: string[];\n\n        /** Custom context variables */\n        variables?: Record\u003cstring, any\u003e;\n    };\n}\n```\n\nYou can access and modify this data in your middleware:\n\n```typescript\nbot.addMessageMiddleware(async (message, content, messages, sessionData) =\u003e {\n    // Set context variables\n    if (!sessionData.context) {\n        sessionData.context = {variables: {}};\n    }\n\n    sessionData.context.variables.lastInteraction = new Date().toISOString();\n\n    return {messageContent: content, messages};\n});\n```\n\n## Utilities\n\nThe library provides several utility functions for common tasks:\n\n### Media Handling\n\n```typescript\nimport { Utils } from '@green-api/whatsapp-chatgpt';\n\n// Download media from a URL\nconst tempFile = await Utils.downloadMedia(\"https://example.com/image.jpg\");\n\n// Transcribe audio\nconst openai = new OpenAI({apiKey: \"your-openai-api-key\"});\nconst transcript = await Utils.transcribeAudio(\"/path/to/audio.ogg\", openai);\n\n// Clean up after processing\nfs.unlinkSync(tempFile);\n```\n\n### Conversation Management\n\n```typescript\nimport { Utils } from 'whatsapp-gpt-bot';\n\n// Trim conversation history\nconst trimmedMessages = Utils.trimConversationHistory(\n        messages,\n        10,  // max messages\n        true  // preserve system message\n);\n\n// Estimate token usage\nconst estimatedTokens = Utils.estimateTokens(messages);\n```\n\n## Supported OpenAI Models\n\nThe library supports a variety of OpenAI models:\n\n### GPT-4 Models\n\n- gpt-4\n- gpt-4-turbo\n- gpt-4-turbo-preview\n- gpt-4-1106-preview\n- gpt-4-0125-preview\n- gpt-4-32k\n\n### GPT-4o Models\n\n- gpt-4o (default)\n- gpt-4o-mini\n- gpt-4o-2024-05-13\n\n### GPT-3.5 Models\n\n- gpt-3.5-turbo\n- gpt-3.5-turbo-16k\n- gpt-3.5-turbo-1106\n- gpt-3.5-turbo-0125\n\n### o1 Models\n\n- o1\n- o1-mini\n- o1-preview\n\n### Image-Capable Models\n\nThe following models can process images:\n\n- gpt-4o\n- gpt-4o-mini\n- gpt-4-vision-preview\n- gpt-4-turbo\n- gpt-4-turbo-preview\n\n## Advanced Configuration\n\n### Custom State Handling\n\nSince the library is built on @green-api/whatsapp-chatbot-js-v2, you can use all the state features of the base library:\n\n```typescript\n// Add custom state\nbot.addState({\n    name: \"collect_info\",\n    async onEnter(message) {\n        await bot.sendText(message.chatId, \"Please provide your name.\");\n    },\n    async onMessage(message, data = {}) {\n        // Store the name and process with GPT\n        const openai = bot.getOpenAI();\n        const completion = await openai.chat.completions.create({\n            model: \"gpt-3.5-turbo\",\n            messages: [\n                {role: \"system\", content: \"Generate a personalized greeting.\"},\n                {role: \"user\", content: `My name is ${message.text}`}\n            ]\n        });\n\n        await bot.sendText(message.chatId, completion.choices[0]?.message.content || \"Hello!\");\n        return \"main_chat\"; // Transition to main chat state\n    }\n});\n```\n\n### Advanced Message Processing\n\n```typescript\n// Get OpenAI client for custom API calls\nconst openai = bot.getOpenAI();\n\n// Check if current model supports images\nif (bot.supportsImages()) {\n    // Handle image-based workflow\n}\n```\n\n## Demo Bot Example\n\nSee [our demo chatbot](https://github.com/green-api/whatsapp-demo-chatgpt-js) for a comprehensive demo chatbot, which\nshowcases many features:\n\n```typescript\nimport {\n    GPTSessionData,\n    ImageMessageHandler,\n    ProcessMessageMiddleware,\n    ProcessResponseMiddleware,\n    WhatsappGptBot,\n    OpenAIModel,\n} from \"@green-api/whatsapp-chatgpt\";\nimport * as dotenv from \"dotenv\";\nimport { Message } from \"@green-api/whatsapp-chatbot-js-v2\";\nimport { ChatCompletionMessageParam } from \"openai/resources/chat/completions\";\nimport OpenAI from \"openai\";\n\ndotenv.config();\n\n// Custom image handler that provides enhanced descriptions\nclass EnhancedImageHandler extends ImageMessageHandler {\n    async processMessage(message: Message, openai: OpenAI, model: OpenAIModel): Promise\u003cany\u003e {\n        const result = await super.processMessage(message, openai, model);\n\n        if (typeof result === \"string\") {\n            return result.replace(\n                    \"[The user sent an image\",\n                    \"[The user sent an image. Tell them that you are not the model they should be using\"\n            );\n        }\n\n        return result;\n    }\n}\n\n// Middleware examples\n\n// Logging middleware\nconst loggingMessageMiddleware: ProcessMessageMiddleware = async (\n        message, messageContent, messages, _\n) =\u003e {\n    console.log(`[${new Date().toISOString()}] User (${message.chatId}): `,\n            typeof messageContent === \"string\"\n                    ? messageContent\n                    : JSON.stringify(messageContent));\n\n    return {messageContent, messages};\n};\n\n// Initialize the bot\nconst bot = new WhatsappGptBot({\n    idInstance: process.env.INSTANCE_ID || \"\",\n    apiTokenInstance: process.env.INSTANCE_TOKEN || \"\",\n    openaiApiKey: process.env.OPENAI_API_KEY || \"\",\n    model: \"gpt-4o\",\n    systemMessage: \"You are a helpful WhatsApp assistant created by GREEN-API\",\n    maxHistoryLength: 15,\n    temperature: 0.5,\n    handlersFirst: true,\n    clearWebhookQueueOnStart: true,\n});\n\n// Command handlers\nbot.onText(\"/help\", async (message, _) =\u003e {\n    const helpText = `*WhatsAppGPT Demo Bot*\\n\\nAvailable commands:\\n- /help - Show this help message\\n- /clear - Clear conversation history`;\n    await bot.sendText(message.chatId, helpText);\n});\n\n// Register middleware\nbot.addMessageMiddleware(loggingMessageMiddleware);\n\n// Replace default handlers\nbot.replaceHandler(ImageMessageHandler, new EnhancedImageHandler());\n\n// Start the bot\nbot.start();\n```\n\nThis demo bot includes:\n\n- Custom message handlers\n- Various middleware implementations\n- Command handlers\n- Custom type handlers\n- Error handling\n\n## Additional Examples\n\n### Multi-Language Support Bot\n\n```typescript\nimport { WhatsappGptBot } from '@green-api/whatsapp-chatgpt';\nimport { detectLanguage } from './language-detector';\n\nconst bot = new WhatsappGptBot({\n    idInstance: \"your-instance-id\",\n    apiTokenInstance: \"your-token\",\n    openaiApiKey: \"your-openai-api-key\",\n    model: \"gpt-4o\"\n});\n\n// Add language detection middleware\nbot.addMessageMiddleware(async (message, content, messages, sessionData) =\u003e {\n    // Only process text messages\n    if (message.type !== 'text' || !message.text) {\n        return {messageContent: content, messages};\n    }\n\n    // Detect language\n    const language = await detectLanguage(message.text);\n\n    // Store language in session\n    if (!sessionData.context) {\n        sessionData.context = {variables: {}};\n    }\n    sessionData.context.variables.language = language;\n\n    // Update system message with language instruction\n    const languageInstruction = `User is writing in ${language}. Reply in the same language.`;\n\n    // Find system message\n    const systemIndex = messages.findIndex(m =\u003e m.role === 'system');\n\n    if (systemIndex \u003e= 0) {\n        // Update existing system message\n        const updatedMessages = [...messages];\n        const currentContent = updatedMessages[systemIndex].content;\n        if (typeof currentContent === 'string' \u0026\u0026 !currentContent.includes('User is writing in')) {\n            updatedMessages[systemIndex].content = `${currentContent} ${languageInstruction}`;\n        }\n        return {messageContent: content, messages: updatedMessages};\n    } else {\n        // Add new system message\n        return {\n            messageContent: content,\n            messages: [\n                {role: 'system', content: languageInstruction},\n                ...messages\n            ]\n        };\n    }\n});\n\n// Start the bot\nbot.start();\n```\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgreen-api%2Fwhatsapp-chatgpt-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgreen-api%2Fwhatsapp-chatgpt-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgreen-api%2Fwhatsapp-chatgpt-js/lists"}