How to Build an AI Chatbot for an IM Platform with an Open-Source Architecture
Learn how to deploy an AI chatbot on an instant messaging platform by separating protocol integration from business logic. This guide covers OneBot communication options, Docker Compose orchestration, LLM configuration, deployment, security, operations, troubleshooting, and compliance considerations. All configuration values are examples and must be adjusted to match the documentation of the projects and images you use.
Running an AI chatbot on an instant messaging platform is usually less difficult because of the model itself than because of platform integration, protocol changes, and deployment consistency. A reliable design should isolate platform-specific communication from chatbot business logic and standardize deployment so that environments can be reproduced.
This guide presents a practical architecture based on common open-source components. All configuration values are examples. Image names, environment variables, and service-specific settings must be adjusted according to the documentation for the projects you choose.
1. Separate the Protocol Layer from the Business Layer
IM platforms often use private communication protocols and may update them regularly. AI business logic also changes frequently—for example, when switching models, adding plugins, or adjusting prompts. If both responsibilities run in the same process, every protocol change may require changes to business code, increasing maintenance costs.
A common approach is to split the system into two layers.
1.1 Protocol Layer
The protocol adapter communicates directly with the IM platform server. Its responsibilities typically include:
- Logging in to the account
- Maintaining long-lived connections
- Sending and receiving messages
- Handling disconnections and reconnections
The adapter should follow the platform’s request-frequency rules, reconnect in an orderly way after an interruption, and avoid aggressive retries that could trigger suspicious-login restrictions.
This layer should focus on message transport and format conversion. It should not store business state, allowing application developers to work without dealing with low-level protocol details.
1.2 Business Logic Layer
The business layer contains the chatbot’s core functionality. It identifies user intent, manages multi-turn conversations, and calls large language models.
A mature business framework commonly provides the following capabilities:
- Multiple model providers: A unified interface can connect to different models. Switching models should mainly require changing the API key, base URL, and model name.
- Context management: Conversation history should be isolated by user or session. Store context in the business layer’s data directory, define a retention period such as seven days, and run scheduled cleanup tasks. This prevents conversations from different users from being mixed and avoids retaining outdated private data indefinitely.
- Plugin support: Message events can trigger features such as weather queries and retrieval-augmented generation (RAG). Long-running plugins should run asynchronously so that they do not block message processing.
1.3 Communication: Forward and Reverse WebSocket
The two layers need an agreed communication protocol. OneBot is a common bot communication standard that defines event reporting and API call formats. It supports HTTP, forward WebSocket, and reverse WebSocket connections. The main difference is which side initiates the connection.
| Method | Connection initiator | Business layer responsibility | Container networking considerations |
|---|---|---|---|
| HTTP | Each side initiates its own requests | Provide an HTTP endpoint to receive events | Both services must be able to access the other service’s port |
| Forward WebSocket | Business layer connects to the protocol layer | Configure the protocol layer’s WebSocket address | The protocol layer must expose a WebSocket port for the business layer |
| Reverse WebSocket | Protocol layer connects to the business layer | Listen on a WebSocket port | The business layer must listen on a port that the protocol layer can access |
Reverse WebSocket is often convenient in containerized deployments. The protocol adapter acts as a client and actively connects to the listening address of the business service. The protocol layer does not need to expose a port externally; the two services can communicate over an internal network.
Pay close attention to the connection direction: the protocol layer connects to the business layer. Do not reverse their roles when configuring the services.
2. Orchestrate Both Services with Containers
2.1 Why Use Orchestration?
Docker Compose, or a similar orchestration tool, allows you to define the protocol layer, business layer, network, and data volumes in one file. A single command can then start the services in the intended dependency order.
Using the same configuration in testing and production also reduces problems caused by differences between environments.
2.2 Example Compose File
version: '3.8'services:protocol-adapter:image: registry.example.com/protocol-adapter:latest # Placeholder; replace with the actual imagerestart: unless-stoppedenvironment:- BOT_ACCOUNT=${BOT_ACCOUNT}- REVERSE_WS_URL=ws://ai-bot-framework:3001/onebot/v11/ws- ACCESS_TOKEN=${WS_ACCESS_TOKEN}- TZ=Asia/Shanghaivolumes:- ./adapter_data:/app/datadepends_on:- ai-bot-frameworknetworks:- bot-netdeploy:resources:limits:cpus: "1.0"memory: 512Mlogging:driver: json-fileoptions:max-size: "10m"max-file: "3"ai-bot-framework:image: registry.example.com/ai-bot:latestrestart: unless-stoppedenvironment:- REVERSE_WS_LISTEN=0.0.0.0:3001- ACCESS_TOKEN=${WS_ACCESS_TOKEN}- LLM_API_KEY=${LLM_API_KEY}- LLM_BASE_URL=${LLM_BASE_URL}- TZ=Asia/Shanghaiports:- "127.0.0.1:8080:8080"volumes:- ./bot_data:/app/datanetworks:- bot-netdeploy:resources:limits:cpus: "1.0"memory: 1Glogging:driver: json-fileoptions:max-size: "10m"max-file: "3"networks:bot-net:driver: bridge
The main settings work as follows:
depends_onstarts the business layer before the protocol layer. It controls startup order only; it does not guarantee that the business service has completed initialization.REVERSE_WS_URLpoints to the business service name and port on the internal container network. The service nameai-bot-frameworkcan be resolved only within thebot-netnetwork.- The business layer’s Web UI is bound to
127.0.0.1on the host, so it cannot be accessed directly from outside. For remote administration, use a reverse proxy with authentication. - Account credentials and secrets are loaded from a
.envfile rather than written directly into the Compose file. ACCESS_TOKENauthenticates the connection between the two layers and prevents unauthorized programs from pretending to be the protocol adapter.- Environment variable names must follow the documentation for the image you use.
registry.example.comis a placeholder, so this example cannot run without modification.
3. Connect a Large Language Model
3.1 Check the Required Settings
Before connecting to an LLM provider, verify these four items:
- API key: Obtain it from the provider’s console and store it only in the
.envfile. - Base URL: Follow the provider’s documentation. Some services require a version path such as
/v1. - Model name: Use the exact model name provided by the service. Differences in version names can also affect output quality.
- Timeouts and retries: Start with a timeout of approximately 30 seconds and adjust it based on actual response times. Keep retries to no more than two whenever possible; otherwise, one failure could result in multiple billable requests.
3.2 API Compatibility
Many providers offer APIs compatible with the OpenAI request format, but differences may exist in areas such as streaming output, function calling, and system messages.
After switching models, send a test message first. Then verify that multi-turn conversations and plugin calls work as expected.
4. Deployment Procedure
Before deployment, make sure that:
- Docker and the Compose plugin are installed on the host.
- The required images can be pulled successfully.
- You have an IM account for the bot and are authorized to use it.
1. Create the deployment files
Create a deployment directory, save the Compose configuration as docker-compose.yml, and create a .env file in the same directory:
BOT_ACCOUNT=your_bot_accountWS_ACCESS_TOKEN=generate_a_long_random_stringLLM_API_KEY=your_provider_api_keyLLM_BASE_URL=your_provider_base_url
Restrict access to the environment file:
chmod 600 .env
Make sure .env is excluded from source control.
2. Start the services
docker compose up -d
3. Complete account login
View the protocol adapter logs and scan the QR code displayed in the output:
docker compose logs -f protocol-adapter
4. Open the Web UI
Open http://127.0.0.1:8080 to access the Web UI, configure the model, and send a test message.
If the server is remote, create an SSH port-forwarding tunnel from your local machine:
ssh -L 8080:127.0.0.1:8080 username@server-address
You can then access the Web UI through a local browser.
5. Operations and Security
- Backups:
adapter_datacontains login state and should be treated as sensitive data. Stop the protocol container before backing it up, encrypt the backup, and restrict its access. Back upbot_dataregularly, preferably daily, because it may contain conversation records and configuration. - Logs: Do not log complete message contents, API keys, or access tokens. The
max-sizeandmax-filesettings enable log rotation and help prevent the disk from filling up. - Secrets: Store secrets in environment variables or a dedicated secret-management tool. Rotate them regularly and revoke them immediately if they are exposed.
- Resources: The limits in the example—one CPU core, 512 MB, and 1 GB of memory—are starting points, not universal requirements. Adjust them according to actual usage and concurrency after deployment.
- Alerts: Monitor the protocol adapter’s health, as well as model API error and timeout rates. Notify the responsible operator when abnormal conditions occur.
6. Troubleshooting
| Symptom | Possible cause | Troubleshooting method |
|---|---|---|
| QR code is not displayed | The protocol adapter has not finished starting, or the log level is too low | Check the protocol-adapter logs and confirm that the service has started |
| The business layer receives no events | The reverse WebSocket URL, port, or token does not match | Check REVERSE_WS_URL, the listening port, and ACCESS_TOKEN; test connectivity from a temporary container on the same network |
| Container time is incorrect | No time zone is configured | Set TZ in the environment variables |
| Permission errors in a data directory | The host directory owner differs from the user running inside the container | Change the directory owner to the container’s runtime user and restart the service |
| Port 8080 cannot be accessed | The port is already in use, or the service is bound only to 127.0.0.1 |
Change the host port mapping; for remote access, use SSH port forwarding |
| Model requests time out | Unstable networking, provider throttling, or insufficient account balance | Check the provider’s status and account balance, then adjust the timeout if appropriate |
| The account disconnects frequently | Invalid login state, excessive activity, or platform restrictions | Reduce message frequency, stop abnormal operations, and scan the login QR code again if necessary |
7. Compliance and Risk Considerations
- Read the IM platform’s terms of service and developer rules before going live. Automated activity may result in account restrictions or suspension. This architecture does not guarantee long-term account availability.
- Use only accounts that you own or are authorized to operate. Do not use the bot for harassment, bulk messaging, or attempts to bypass platform risk controls.
- The bot may receive and store user messages. Inform users about this processing, comply with applicable privacy requirements, define a data-retention period, and provide a way to request deletion.
