- Updated: March 17, 2026
- 7 min read
Advanced Custom OpenClaw Agent for Moltbook: Adding Persistence and External API Integration
Answer
To give your OpenClaw agent on Moltbook true persistence and the ability to call any external API, you add a lightweight SQLite store, install the UBOS SQLite plugin, and wrap the external service in a Moltbook plugin. The following step‑by‑step guide shows exactly how to do it, provides ready‑to‑run code snippets, and explains how to publish the advanced agent on the host OpenClaw on UBOS platform.
1. Introduction
In the UBOS homepage we introduced a minimal custom‑agent that could respond to simple prompts. That prototype demonstrated how Moltbook’s Web app editor on UBOS lets you stitch together a language model, a few intents, and a tiny UI.
The next logical step for production‑grade bots is stateful persistence (so the agent remembers user preferences, conversation history, or transaction IDs) and external API integration (to fetch weather, process payments, or query a CRM). This article expands the basic guide by showing you how to:
- Install and configure the SQLite plugin for durable storage.
- Create a Moltbook plugin that wraps any RESTful API.
- Combine both features into a single, reusable OpenClaw agent.
- Test, debug, and finally publish the agent on UBOS.
2. Prerequisites
Before you start, make sure you have the following:
- A UBOS platform overview account with admin rights.
- Access to a Moltbook workspace where you can create plugins and agents.
- Basic knowledge of JavaScript/Node.js – the language used for Moltbook plugins.
- UBOS pricing plans that include the SQLite add‑on (the free tier already supports it).
- An external API you want to call (we’ll use the free OpenWeatherMap API as an example).
3. Adding SQLite Persistence
3.1 Install the SQLite plugin
UBOS ships a ready‑made Chroma DB integration that can be swapped for SQLite with a single command in the plugins panel.
ubos plugins add sqlite --version 1.2.0
After the command finishes, a new sqlite.db file appears in your workspace’s /data folder.
3.2 Configure a memory store
Create a memoryStore.js file that abstracts CRUD operations. This keeps your agent code clean and testable.
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('data/sqlite.db');
module.exports = {
getUser: (userId) => new Promise((resolve, reject) => {
db.get('SELECT * FROM users WHERE id = ?', [userId], (err, row) => {
if (err) return reject(err);
resolve(row);
});
}),
setUser: (user) => new Promise((resolve, reject) => {
const { id, name, preferences } = user;
db.run(
`INSERT INTO users (id, name, preferences) VALUES (?, ?, ?)
ON CONFLICT(id) DO UPDATE SET name = ?, preferences = ?`,
[id, name, JSON.stringify(preferences), name, JSON.stringify(preferences)],
(err) => {
if (err) return reject(err);
resolve();
}
);
})
};
The first time the agent runs, you’ll need to create the users table. Add a one‑time migration script:
db.run(`
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
name TEXT,
preferences TEXT
)
`);
3.3 Sample usage in the agent
Inside your OpenClaw agent’s handler.js, import the store and persist a user’s favorite city:
const store = require('./memoryStore');
async function handleMessage(context) {
const { userId, text } = context;
const user = await store.getUser(userId) || { id: userId, preferences: {} };
if (/set city (.+)/i.test(text)) {
const city = text.match(/set city (.+)/i)[1];
user.preferences.city = city;
await store.setUser(user);
return `Got it! I’ll remember that your favorite city is ${city}.`;
}
// other intents …
}
4. Integrating External APIs via Moltbook Plugins
4.1 Choose an API
For this guide we’ll call the OpenWeatherMap API to fetch current weather for the city stored in the user’s preferences. The same pattern works for payment gateways, CRM endpoints, or any JSON‑based service.
4.2 Create a Moltbook plugin wrapper
In the plugins folder, add weatherPlugin.js:
const fetch = require('node-fetch');
const API_KEY = process.env.OPENWEATHER_API_KEY; // store securely in UBOS env
module.exports = {
/**
* Returns a short weather summary for a given city.
* @param {string} city
* @returns {Promise}
*/
getWeather: async (city) => {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&appid=${API_KEY}&units=metric`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Weather API error: ${response.statusText}`);
}
const data = await response.json();
const { temp, weather } = data.main ? data : { temp: null, weather: [] };
const description = weather[0]?.description || 'unknown';
return `Current temperature in ${city} is ${temp}°C with ${description}.`;
}
};
Remember to add OPENWEATHER_API_KEY in the About UBOS environment settings page.
4.3 Sample request/response in the agent
Extend handler.js to call the plugin when the user asks for the weather:
const weather = require('./weatherPlugin');
async function handleMessage(context) {
const { userId, text } = context;
const user = await store.getUser(userId) || { id: userId, preferences: {} };
// Existing city‑set intent …
if (/what(?:'s| is) the weather/i.test(text)) {
const city = user.preferences.city;
if (!city) {
return "I don’t know your favorite city yet. Tell me with ‘set city <city name>’.";
}
try {
const forecast = await weather.getWeather(city);
return forecast;
} catch (e) {
console.error(e);
return "Sorry, I couldn’t fetch the weather right now.";
}
}
// other intents …
}
5. Full Example: Advanced Agent Code
Below is a consolidated agent.js that brings persistence and API calls together. You can copy‑paste this into your Moltbook project and start testing immediately.
const store = require('./memoryStore');
const weather = require('./weatherPlugin');
module.exports = {
async handle(context) {
const { userId, text } = context;
const user = await store.getUser(userId) || { id: userId, preferences: {} };
// 1️⃣ Set favorite city
if (/set city (.+)/i.test(text)) {
const city = text.match(/set city (.+)/i)[1];
user.preferences.city = city;
await store.setUser(user);
return `✅ City saved: ${city}`;
}
// 2️⃣ Ask for weather
if (/weather|forecast/i.test(text)) {
const city = user.preferences.city;
if (!city) return "🤔 I don’t know your city yet. Use ‘set city ’.";
try {
const reply = await weather.getWeather(city);
return `🌤️ ${reply}`;
} catch (err) {
console.error(err);
return "❌ Failed to retrieve weather.";
}
}
// 3️⃣ Fallback
return "I can store your favorite city and give you the current weather. Try ‘set city London’.";
}
};
Deploy this file via the Workflow automation studio and bind it to the OpenClaw trigger you created in the basic guide.
6. Testing & Debugging
UBOS provides a live log console that streams stdout and stderr. Open it from the UBOS partner program dashboard.
- Run
/set city Parisin your OpenClaw chat – you should see a “✅ City saved” response. - Follow with
/weather– the bot returns a weather string. - If the API call fails, check the log for the exact error (e.g., missing
OPENWEATHER_API_KEY).
For deeper inspection, you can query the SQLite file directly:
sqlite3 data/sqlite.db "SELECT * FROM users;"
7. Publishing the Agent
Once you’re satisfied with local testing, push the agent to production:
- Commit your changes in the Moltbook Git view.
- Navigate to the Enterprise AI platform by UBOS and select “Deploy New Agent”.
- Choose the OpenClaw runtime, attach the SQLite add‑on, and set the environment variable
OPENWEATHER_API_KEY. - Click “Deploy”. UBOS builds a Docker image, runs migrations, and exposes the agent at a public endpoint.
- Test the live endpoint via the AI Chatbot template or your own UI.
After deployment, you can monitor usage through the UBOS portfolio examples dashboard, which shows request latency, error rates, and storage growth.
8. Conclusion & Next Steps
You now have a fully functional OpenClaw agent that remembers user preferences with SQLite and enriches conversations with real‑time data from an external API. This pattern is reusable for countless scenarios:
- Persisting e‑commerce carts and calling a payment gateway.
- Storing support tickets and integrating a CRM API.
- Saving user‑generated prompts and fetching AI‑generated images via the AI Image Generator template.
For further enhancements, consider:
- Adding a AI Email Marketing workflow that sends daily weather summaries.
- Integrating ElevenLabs AI voice integration to read the forecast aloud.
- Using the UBOS templates for quick start to spin up a dashboard that visualizes stored user data.
Happy building! If you run into any roadblocks, the UBOS partner program community is a great place to ask questions and share your custom agents.
9. Ready to Deploy?
The final step is to host OpenClaw on UBOS using the instructions above. Once live, your agent will be accessible to any user, any device, and any channel you connect via Moltbook.