Onewise Chat API Documentation

Complete guide to integrating with Onewise Chat API. Send messages, receive real-time events, and build powerful chat applications with our comprehensive API.

REST API Server-Sent Events Real-time Node.js

Getting Started

Authentication

All API requests require an access token for authentication. Include your access token in the request headers or query parameters.

Access Token
const accessToken = "*********************************************************************";

Base URLs

Chat API: https://chatapi.onewise.app
Web App: https://web.onewise.app

Send Messages API

POST /api/bot-onews/send

Send a message to a specific chat room or group.

POST
https://chatapi.onewise.app/api/bot-onews/send

Request Headers

Header Value Required
Content-Type application/json โœ…

Request Body

Parameter Type Required Description
accessToken string โœ… Authentication token
roomId string โœ… Target room/group identifier
content object โœ… Message content object
content.text string โœ… Message text content
content.attachments array โŒ Array of file attachments

Example Request

JavaScript (Fetch API)
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

const raw = JSON.stringify({
  "accessToken": "*********************************************************************",
  "roomId": "21aa95e6-5aad-452a-aa64-592881bbc842",
  "content": {
    "text": "Link nhรณm: https://web.onewise.app/c/a59c709c-36f1-444d-88ce-77fc83ae9056",
    "attachments": []
  }
});

const requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow"
};

fetch("https://chatapi.onewise.app/api/bot-onews/send", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.error(error));

Example with Attachments

Message with Files
const messageWithAttachments = {
  "accessToken": "your_access_token",
  "roomId": "room_id",
  "content": {
    "text": "Check out these files!",
    "attachments": [
      {
        "type": "image",
        "name": "screenshot.png",
        "url": "https://example.com/files/screenshot.png",
        "size": 245760
      },
      {
        "type": "document",
        "name": "report.pdf", 
        "url": "https://example.com/files/report.pdf",
        "size": 1048576
      }
    ]
  }
};

Bot Creation API

POST /api/bot/create

Create a new bot that can send and receive messages. Once created, you can interact with the bot directly or add it to groups for multi-user access.

POST
https://chatapi.onewise.app/api/bot/create

Authentication

This endpoint requires Bearer token authentication. Include your JWT token in the Authorization header.

Authorization Header
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Request Headers

Header Value Required
Content-Type application/json โœ…
Authorization Bearer {jwt_token} โœ…
Accept application/json, text/plain, */* โœ…
Origin https://web.onewise.app โœ…

Request Body

Parameter Type Required Description
name string โœ… Display name for the bot
username string โœ… Unique username for the bot (used for identification)

Complete Example Request

JavaScript (Fetch API)
const myHeaders = new Headers();
myHeaders.append("Accept", "application/json, text/plain, */*");
myHeaders.append("Accept-Language", "vi-VN,vi;q=0.9,fr-FR;q=0.8,fr;q=0.7,en-US;q=0.6,en;q=0.5");
myHeaders.append("Access-Control-Allow-Origin", "*");
myHeaders.append("Authorization", "Bearer eyJhbGciOiJIU*********************************************************************");
myHeaders.append("Connection", "keep-alive");
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Origin", "https://web.onewise.app");
myHeaders.append("Sec-Fetch-Dest", "empty");
myHeaders.append("Sec-Fetch-Mode", "cors");
myHeaders.append("Sec-Fetch-Site", "cross-site");
myHeaders.append("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36");
myHeaders.append("sec-ch-ua", "\"Chromium\";v=\"136\", \"Google Chrome\";v=\"136\", \"Not.A/Brand\";v=\"99\"");
myHeaders.append("sec-ch-ua-mobile", "?0");
myHeaders.append("sec-ch-ua-platform", "\"Windows\"");

const raw = JSON.stringify({
  "name": "Binh FPT Notify",
  "username": "binh_notice_bot"
});

const requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow"
};

fetch("https://chatapi.onewise.app/api/bot/create", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.error(error));

Response Format

Success Response
{
  "success": true,
  "bot": {
    "id": "bot_12345",
    "name": "Binh FPT Notify",
    "username": "binh_notice_bot",
    "accessToken": "bot_access_token_here",
    "createdAt": "2024-01-01T12:00:00Z"
  }
}

Bot Usage Workflow

1

Create Bot

Use the bot creation API to generate a new bot with a unique username and display name.

2

Get Access Token

Save the bot's access token from the creation response - you'll need this for sending messages.

3

Start Conversation

Users can message the bot directly, or add the bot to group chats for multi-user access.

4

Get Room ID

Extract the roomId from incoming messages (works for both private chats and group chats).

5

Send & Receive

Use the same send/receive APIs with the obtained roomId for seamless communication.

Integration Example

Complete Bot Integration
// Step 1: Create the bot
async function createBot() {
  const response = await fetch("https://chatapi.onewise.app/api/bot/create", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer your_jwt_token"
    },
    body: JSON.stringify({
      "name": "My Notification Bot",
      "username": "my_notify_bot"
    })
  });
  
  const botData = await response.json();
  return botData.bot.accessToken;
}

// Step 2: Listen for incoming messages
const createSSEClient = require('sse-client-auth-onewise');

function startBotListener(botAccessToken) {
  const sseClient = createSSEClient({
    url: 'https://chatapi.onewise.app/bot-listen',
    accessToken: botAccessToken,
    onMessage: (data) => {
      try {
        const message = JSON.parse(data);
        const roomId = message.roomId; // Extract roomId for responses
        
        console.log(`๐Ÿ“ฉ Received in room ${roomId}: ${message.text}`);
        
        // Auto-respond to messages
        if (message.text.toLowerCase().includes('hello')) {
          sendBotMessage(botAccessToken, roomId, "Hello! How can I help you?");
        }
      } catch (error) {
        console.error('Error parsing message:', error);
      }
    },
    onError: (error) => {
      console.error('โŒ Bot listener error:', error);
    }
  });
}

// Step 3: Send messages as the bot
async function sendBotMessage(accessToken, roomId, text) {
  const response = await fetch("https://chatapi.onewise.app/api/bot-onews/send", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      accessToken: accessToken,
      roomId: roomId,
      content: {
        text: text,
        attachments: []
      }
    })
  });
  
  return response.json();
}

// Initialize the bot
async function initializeBot() {
  try {
    const botToken = await createBot();
    console.log('โœ… Bot created successfully');
    
    startBotListener(botToken);
    console.log('๐ŸŽง Bot is now listening for messages');
    
    // Bot is ready - users can now message it or add it to groups
  } catch (error) {
    console.error('โŒ Failed to initialize bot:', error);
  }
}

SSE Client Library

sse-client-auth-onewise

npm v1.0.0 MIT

A lightweight SSE client for Node.js with built-in authentication support. Perfect for receiving real-time chat messages and events.

โœจ Features

๐Ÿ”
Authentication Support

Automatic handling of accessToken and roomId

๐Ÿš€
Simple API

Easy integration with just a few lines of code

๐Ÿ“ก
Real-time Events

Efficient SSE connection management

๐Ÿ”„
Auto Reconnection

Automatic reconnection on connection loss

Installation

npm
npm install sse-client-auth-onewise

Quick Start

Basic Usage
const createSSEClient = require('sse-client-auth-onewise');

// Create SSE client with authentication
const sseClient = createSSEClient({
  url: 'https://chatapi.onewise.app/bot-listen',
  accessToken: 'your_access_token_here',
  roomId: 'room_123', // optional
  onMessage: (data) => {
    console.log('๐Ÿ“ฉ Received message:', data);
  },
});

// The client will automatically connect and start listening for events

API Reference

Option Type Required Description
url string โœ… The SSE server endpoint URL
accessToken string โœ… Authentication token sent as query parameter
roomId string โŒ Optional room/channel identifier
onMessage function โœ… Callback function to handle incoming messages
onError function โŒ Optional callback for error handling
onOpen function โŒ Optional callback when connection opens

Complete Example

Full Configuration
const sseClient = createSSEClient({
  url: 'https://chatapi.onewise.app/bot-listen',
  accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
  roomId: 'chat-room-456',
  onMessage: (data) => {
    try {
      const parsed = JSON.parse(data);
      console.log('๐Ÿ“ฆ Parsed data:', parsed);
      
      // Handle message content
      if (parsed.text) {
        console.log('๐Ÿ’ฌ Message:', parsed.text);
      }
      
      // Handle attachments
      if (parsed.attachments && parsed.attachments.length > 0) {
        console.log('๐Ÿ“Ž Attachments:', parsed.attachments.length);
        parsed.attachments.forEach((attachment, index) => {
          console.log(`  ${index + 1}. ${attachment.name || attachment.url}`);
        });
      }
    } catch (error) {
      console.log('๐Ÿ“ Raw message:', data);
    }
  },
  onError: (error) => {
    console.error('โŒ SSE Error:', error);
  },
  onOpen: () => {
    console.log('โœ… SSE Connection established');
  }
});

Message Format

Basic Message Structure

Messages are sent and received in JSON format with the following structure:

Message Object
{
  "text": "Hello everyone! ๐Ÿ‘‹",
  "attachments": [],
  "sender": "user_123",
  "timestamp": "2024-01-01T12:00:00Z",
  "messageId": "msg_456",
  "type": "message"
}

Message with Attachments

With Files
{
  "text": "Check out these files!",
  "attachments": [
    {
      "type": "image",
      "name": "screenshot.png",
      "url": "https://example.com/files/screenshot.png",
      "size": 245760
    },
    {
      "type": "document", 
      "name": "report.pdf",
      "url": "https://example.com/files/report.pdf",
      "size": 1048576
    }
  ],
  "sender": "user_789",
  "timestamp": "2024-01-01T12:05:00Z",
  "messageId": "msg_789"
}

Attachment Types

Type Description Example Extensions
image Image files .jpg, .png, .gif, .webp
video Video files .mp4, .avi, .mov, .webm
audio Audio files .mp3, .wav, .ogg, .m4a
document Document files .pdf, .doc, .txt, .xlsx
other Other file types Any other extension

System Messages

User Events
// User joined
{
  "text": "User John joined the conversation",
  "attachments": [],
  "type": "system",
  "timestamp": "2024-01-01T12:10:00Z"
}

// User left
{
  "text": "User John left the conversation", 
  "attachments": [],
  "type": "system",
  "timestamp": "2024-01-01T12:15:00Z"
}

Usage Examples

Group Chat Integration

Group Chat Handler
const groupChatClient = createSSEClient({
  url: 'https://chatapi.onewise.app/bot-listen',
  accessToken: 'your-access-token',
  roomId: 'team-developers',
  onMessage: (data) => {
    try {
      const messageData = JSON.parse(data);
      
      // Handle different message types
      switch (messageData.type) {
        case 'message':
          console.log(`๐Ÿ‘ค ${messageData.sender}: ${messageData.text}`);
          
          // Display attachments if any
          if (messageData.attachments.length > 0) {
            messageData.attachments.forEach(attachment => {
              console.log(`๐Ÿ“Ž ${attachment.type}: ${attachment.name}`);
            });
          }
          break;
          
        case 'user_joined':
          console.log(`โœ… ${messageData.user} joined the group`);
          break;
          
        case 'user_left':
          console.log(`โŒ ${messageData.user} left the group`);
          break;
      }
    } catch (error) {
      console.error('Failed to parse group message:', error);
    }
  }
});

Private Chat Handler

Private Messages
const privateChatClient = createSSEClient({
  url: 'https://chatapi.onewise.app/bot-listen',
  accessToken: 'private-token',
  roomId: 'user_123_456', // Private room between users
  onMessage: (rawData) => {
    try {
      const message = JSON.parse(rawData);
      const { text, attachments, sender, timestamp } = message;
      
      console.log(`๐Ÿ’ฌ [${new Date(timestamp).toLocaleTimeString()}] ${sender}:`);
      console.log(`   ${text}`);
      
      // Handle media attachments
      if (attachments && attachments.length > 0) {
        console.log(`๐Ÿ“Ž Attachments:`);
        attachments.forEach((file, index) => {
          const fileType = file.type || 'unknown';
          const fileName = file.name || `attachment_${index + 1}`;
          const fileSize = file.size ? ` (${(file.size / 1024).toFixed(1)}KB)` : '';
          
          console.log(`   ${index + 1}. [${fileType.toUpperCase()}] ${fileName}${fileSize}`);
        });
      }
      
    } catch (parseError) {
      // If not JSON, might be plain text message
      console.log(`๐Ÿ“ Raw message: ${rawData}`);
    }
  },
  onError: (error) => {
    console.error('โŒ Private chat connection error:', error);
  }
});