LucyDream Telegram Chatbot API Documentation

Overview

The LucyDream Telegram Chatbot API allows registered users to integrate their own Telegram bots with the LucyDream chatbot system. It enables you to send messages, request images, manage chat history, and handle sub-users.

This API is built on REST API endpoints and requires an API key for authentication. It supports interactions with predefined chatbot models (e.g., the default “Lucy Dream” model) and custom user-owned models (see the model creation API documentation for details).

Prerequisites

  • API Key: Obtain your API key from your LucyDream account dashboard. This key authenticates all requests.
  • Base URL: All endpoints are relative to https://my.luydream.ai/wp-json/
  • Telegram Bot Setup: Create a Telegram bot via BotFather and obtain its token. You’ll need to handle Telegram updates (e.g., via webhooks or polling) in your bot code.
  • Programming Language: Examples are provided in Python (using the requests library and python-telegram-bot for Telegram integration). Adapt as needed for other languages.

Important Notes:

  • All requests must include the X-API-Key header.
  • User IDs are in the format user_{wp_user_id} (e.g., user_123).
  • Sub-users are child accounts owned by your main API key user. They allow isolated chat histories for different Telegram users.
  • Rate limits and credit costs apply based on the standard LucyDream rate (e.g., credits will be deducted from your main API user account after 20 free messages limit).

Authentication

Every request requires the X-API-Key header with your valid API key. Invalid or missing keys return a 403 error.

Endpoints

1. Send Message (POST /telegram/v1/send-message)

Send a user’s message to the chatbot and receive a response.

Request

Method: POST

Headers

Content-Type: application/json

X-API-Key: <your_api_key>

Body Parameters (JSON)

The body must be a JSON object with the following required parameters:

ParameterTypeRequiredDescription
messagestringYesThe message to send to the chatbot.
chatbot_modelstringYesThe model ID (e.g., 2195981 for default “Lucy Dream”, or your custom model ID).
user_idstringYesThe sub-user ID.

cURL Example

Send Message:textcurl -X POST https://my.lucydream.ai/wp-json/telegram/v1/send-message \ -H "X-API-Key: your_api_key_here" \ -H "Content-Type: application/json" \ -d '{"message": "Hello!", "chatbot_model": "2195981", "user_id": "user_123"}'

Response

Success (200 OK)

JSON object with the chatbot’s reply (e.g., {“reply”: “Chatbot response here”}).

Errors

400 (invalid params), 403 (unauthorized), 404 (user not found), 500 (internal error).

2. Request Image (POST /telegram/v1/request-image)

Request a generated image from the chatbot (e.g., a “sexy photo” as per system prompt).

Request

Method: POST

Headers

Content-Type: application/json

X-API-Key: <your_api_key>

Body Parameters (JSON)

The body must be a JSON object with the following required parameters:

ParameterTypeRequiredDescription
chatbot_modelstringYesThe model ID (e.g., 2195981 for default “Lucy Dream”, or your custom model ID).
user_idstringYesThe sub-user ID.

cURL Example

Request Image:textcurl -X POST https://my.lucydream.ai/wp-json/telegram/v1/request-image \ -H "X-API-Key: your_api_key_here" \ -H "Content-Type: application/json" \ -d '{"chatbot_model": "2195981", "user_id": "user_123"}'

Response

Success (200 OK)

JSON object with image details (e.g., {“image_url”: “https://my.lucydream.ai/image.jpg”, “reply”: “I’ve created this image just for you!”}).

Errors

400 (invalid params), 403 (unauthorized), 404 (user not found), 500 (internal error).

3. Get History (GET /telegram/v1/get-history)

Retrieve the chat history for a sub-user and model.

Request

Method: GET

Headers

X-API-Key: <your_api_key>

Body Parameters (JSON)

ParameterTypeRequiredDescription
chatbot_modelstringYesThe model ID (e.g., 2195981 for default “Lucy Dream”, or your custom model ID).
user_idstringYesThe sub-user ID.

cURL Example

Get History:textcurl -X GET "my.lucydream.ai/wp-json/telegram/v1/get-history?chatbot_model=2195981&user_id=user_123" \ -H "X-API-Key: your_api_key_here"

Response

Success (200 OK)

JSON object with history array (e.g., {“success”: true, “chatbot_name”: “Lucy Dream”, “count”: 5, “history”: [{“role”: “user”, “message”: “…”, “timestamp”: “…”, “clean_message”: “…”}, …]}).

Errors

400 (invalid params), 403 (unauthorized), 404 (user not found), 500 (internal error).

4. Create Sub-User (POST /telegram/v1/create-sub-user)

Create a new sub-user under your main account. Useful for mapping Telegram users to isolated LucyDream profiles.

Request

Method: POST

Headers

Content-Type: application/json

X-API-Key: <your_api_key>

Body Parameters (JSON)

ParameterTypeRequiredDescription
usernamestringYesUnique username for the sub-user.
emailstringNoEmail address (auto-generated if omitted).

cURL Example

Create Sub-User:textcurl -X POST https://my.lucydream.ai/wp-json/telegram/v1/create-sub-user \ -H "X-API-Key: your_api_key_here" \ -H "Content-Type: application/json" \ -d '{"username": "new_subuser"}'

Response

Success (200 OK)

JSON object with sub-user details (e.g., {“success”: true, “user_id”: “user_123”, “username”: “subuser1”, “email”: “sub_uuid@telegram.proxy”}). Note: Password is not returned for security.

Errors

400 (username/email exists or invalid).

5. List Sub-Users (GET /telegram/v1/sub-users)

List all sub-users owned by your API key.

Request

Method: GET

Headers

X-API-Key: <your_api_key>

Body Parameters (JSON)

None

cURL Example

Sub-Users:textcurl -X GET https://my.lucydream.ai/wp-json/telegram/v1/sub-users \ -H "X-API-Key: your_api_key_here"

Response

Success (200 OK)

JSON array of sub-users (e.g., [{“user_id”: “user_123”, “username”: “subuser1”, “email”: “sub_uuid@telegram.proxy”}, …]).

Errors

403 (unauthorized).

Integration with Telegram Bot

To integrate, set up a Telegram bot that handles incoming messages and proxies them to the LucyDream API. Use sub-users to keep chats isolated per Telegram user.

Step-by-Step Guide

  1. Create Sub-Users: For each new Telegram user, call /create-sub-user to generate a LucyDream sub-user ID. Store this mapping (e.g., Telegram ID → sub-user ID) in your database.
  2. Handle Messages: When a Telegram user sends a message, proxy it via /send-message.
  3. Handle Image Requests: If the user requests an image (e.g., via command /image), call /request-image.
  4. Load History: On bot start or command (e.g., /history), fetch and display history.
  5. Error Handling: Gracefully handle API errors (e.g., insufficient credits) and inform the user.

Python Example (Using python-telegram-bot)

Install dependencies: pip install python-telegram-bot requests

Python

import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
import requests
import json

# Constants
TELEGRAM_TOKEN = 'your_telegram_bot_token'
API_BASE_URL = 'https://my.lucydream.ai/wp-json/telegram/v1/'
API_KEY = 'your_lucydream_api_key'
DEFAULT_MODEL = '2195981'  # Default Lucy Dream model

# In-memory storage for user mappings (use a database in production)
user_mappings = {}  # {telegram_id: {'sub_user_id': 'user_123', 'model': '2195981'}}

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)

def api_request(endpoint, method='GET', data=None, params=None):
    headers = {'X-API-Key': API_KEY, 'Content-Type': 'application/json'}
    url = API_BASE_URL + endpoint
    if method == 'POST':
        response = requests.post(url, headers=headers, json=data)
    else:
        response = requests.get(url, headers=headers, params=params)
    if response.status_code != 200:
        logger.error(f"API Error: {response.status_code} - {response.text}")
        return None
    return response.json()

async def start(update: Update, context: CallbackContext) -> None:
    user_id = update.effective_user.id
    if user_id not in user_mappings:
        # Create sub-user
        create_data = {'username': f'tg_{user_id}'}
        sub_user = api_request('create-sub-user', 'POST', create_data)
        if sub_user and sub_user.get('success'):
            user_mappings[user_id] = {'sub_user_id': sub_user['user_id'], 'model': DEFAULT_MODEL}
            await update.message.reply_text(f"Welcome! Your profile is set up. Chat with me!")
        else:
            await update.message.reply_text("Error setting up your profile. Try again later.")
    else:
        await update.message.reply_text("Welcome back! Let's chat.")

async def handle_message(update: Update, context: CallbackContext) -> None:
    user_id = update.effective_user.id
    if user_id not in user_mappings:
        await start(update, context)
        return

    message_text = update.message.text
    user_data = user_mappings[user_id]
    send_data = {
        'message': message_text,
        'chatbot_model': user_data['model'],
        'user_id': user_data['sub_user_id']
    }
    response = api_request('send-message', 'POST', send_data)
    if response:
        await update.message.reply_text(response.get('reply', 'No response'))
    else:
        await update.message.reply_text("Error processing message.")

async def request_image(update: Update, context: CallbackContext) -> None:
    user_id = update.effective_user.id
    if user_id not in user_mappings:
        await start(update, context)
        return

    user_data = user_mappings[user_id]
    image_data = {
        'chatbot_model': user_data['model'],
        'user_id': user_data['sub_user_id']
    }
    response = api_request('request-image', 'POST', image_data)
    if response and 'image_url' in response:
        await update.message.reply_photo(photo=response['image_url'], caption=response.get('reply', 'Enjoy!'))
    else:
        await update.message.reply_text("Error generating image.")

async def get_history(update: Update, context: CallbackContext) -> None:
    user_id = update.effective_user.id
    if user_id not in user_mappings:
        await start(update, context)
        return

    user_data = user_mappings[user_id]
    params = {
        'chatbot_model': user_data['model'],
        'user_id': user_data['sub_user_id']
    }
    response = api_request('get-history', 'GET', params=params)
    if response and response.get('success'):
        history_text = "\n".join([f"{item['role']}: {item['clean_message']}" for item in response['history']])
        await update.message.reply_text(history_text or "No history yet.")
    else:
        await update.message.reply_text("Error fetching history.")

def main() -> None:
    application = Application.builder().token(TELEGRAM_TOKEN).build()
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("image", request_image))
    application.add_handler(CommandHandler("history", get_history))
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
    application.run_polling()

if __name__ == '__main__':
    main()

Error Handling

  • 403 Forbidden: Invalid/missing API key or unauthorized access.
  • 400 Bad Request: Invalid parameters or format.
  • 404 Not Found: User/model not found.
  • 500 Internal Server Error: Server-side issue — contact support. Check response bodies for detailed messages (e.g., {“code”: “rest_forbidden”, “message”: “Invalid API key”}).

Best Practices

  • Security: Store API keys securely; never expose them in client-side code.
  • Sub-Users: Create one per Telegram user for privacy and isolated histories.
  • Polling vs. Webhooks: For production, use Telegram webhooks to handle updates efficiently.
  • Credits: Monitor usage—messages/images deduct credits after free limits.
  • Support: If issues arise, email admin@lucydream.ai with logs.

Disclaimer

By using the LucyDream Telegram API and implementing the provided chatbot integration, you acknowledge and agree that LucyDream.ai, its affiliates, and its developers shall not be held responsible or liable for any violations of regional, national, or international laws, regulations, or Telegram’s Terms of Service that may arise from your use of this API or the resulting Telegram bot. This includes, but is not limited to, issues related to content generation, data privacy, user interactions, or any prohibited activities under applicable laws or Telegram policies.

You are solely responsible for ensuring that your implementation complies with all relevant laws, Telegram’s guidelines, and ethical standards in your jurisdiction. LucyDream.ai provides this API as a tool for integration purposes only and disclaims all warranties, express or implied, regarding its use. We recommend consulting legal experts to verify compliance before deployment.

If you do not agree with this disclaimer, do not use the API or integrate the chatbot.

This documentation is up-to-date as of December 25, 2025. For changes, check our website. Happy integrating! 🚀