0.1.2 • Published 4 years ago

lmapis v0.1.2

Weekly downloads
-
License
ISC
Repository
-
Last release
4 years ago

Lakeel Messenger APIs

npm Status ts Status

Table of Contents

Getting Started

This package is built for Lakeel Messenger API ver1.0 in TypeScript. Any questions regarding set up and API management, please visit here. Detailed documentation is also up on the website above.

This API simplifies the process of setting up headers and string manipulations required for executing Lakeel Messenger API. Authentication set up is only needed once, and the type checks are featured to reduce any invalid requests to the server. Response type is not modified but passed as Promise object for easier error handling.

Install

npm

npm install --save lakeel-messenger-apis

And start using the API:

const lakeel = require("lakeel-messenger-apis");

const messenger = new lakeel.LM("apikey", "secretkey", "example.hostname.com");

Usage

JID is a unique identification code given to every user and room. Most functions require to input a JID and invalid code will result in an error.

All functions use the asynchronous method to process data and return value of these functions are in Promise object. Use then() and catch() to process their callbacks.

Send/Receive messages

Send

This function will send a message to the specified JID. If the API account is a bot, it must already exist in the room to post messages. Otherwise, use a user API to send messages to rooms without joining.

The API account status will change to online during the process.

messenger.sendMessage("target_JID", "Hello World!");

Request

TypeParameterContentRequired
stringjidTarget JID
stringmessageMessage to send

Response

TypeNameContent
stringtimestampTime of message sent in ISO 8601 format
stringmessageIdMessage ID

Receive

This function will download sent messages between an API account and a target user or room. The messages are marked as read once downloaded.

Optional settings
force: False (default) will download new messages since the last time this function is called. Setting it True will result in downloading any past 1000 messages.
include: False (default) will not download messages sent by this account.

messenger.receiveMessage("target_JID", true, false);

Request

TypeParameterContentRequired
stringjidTarget JID
boolforceSetting for only receiving new messages
boolincludeInclude messages sent by youself

Response

TypeNameContent
arraymessagesMessage Objects

Message Object

TypeNameContentRequired
stringtypeMessage type"text" : normal message"broadcast" : broadcast message"file" : file messageSystem message"system.replyrequest" : reply request"system.chatmail.success" : successful transmission of chat mail"system.chatmail.failure" : failed to send chat mail"system.room.enter" : participate in room"system.room.invite" : inviting room"system.room.refuse" : room refusal"system.room.disinvite" : room invitation cancellation"system.room.leave" : room exit"system.room.rename" : room name change"system.room.invite.failure" : invitation failed
User ObjectuserUser Object
stringbodyMessage
stringtimestampTime of message sent in ISO 8601 format
stringmessageIdMessage ID
File ObjectfileFile Object

User Object

TypeParameterContentRequired
stringjidTarget JID
stringnameUser name
Organization ObjectorganizationOrganization Object

Organization Object

TypeParameterContentRequired
stringidOrganization ID
stringnameOrganization name

File Object

TypeParameterContentRequired
stringidFile ID
stringnameFile name

Send message with buttons

If the API account is set as a bot, it must already exist in the room to post messages. Otherwise, use a user API to send messages to rooms without joining.

The API account status will change to online during the process.

An array of button objects are required. Use the button() function to create the objects.

let button1 = lakeel.button("message", "Clicked!", "Button One", "success");
...

messenger.sendButton("target_JID", "It's a message!", "horizontal", [button1, button2...]);

Request

TypeParameterContentRequired
stringjidTarget JID
stringmessageMessage to send
stringtypeButton arrangement"horizonta""vertical""dropdown"
arraybuttonsButton objects

Response

TypeNameRequired
stringtimestampTime of message sent in ISO 8601 format
stringmessageIdMessage ID

Button Object

TypeNameContentRequired
stringtypeButton types"message""message_argument""dialog""url""postback""postback_argument""password"
stringvalueValue sent on click
stringlabelButton label
stringstyleButton color"default""info""success""danger"
stringhintTips displayed in the input dialog※Valid only when type is "message_argument" or "postback_argument"
stringtokenValue added to the request header sent by the postback※Valid only when type is "postback", "postback_argument" or "password"
stringdataValue added to the request body sent by the postback※Valid only when type is "postback"

Send carousel message

Send a carousel message to a specified user or room.

If the API account is set as a bot, it must already exist in the room to post messages. Otherwise, use a user API to send messages to rooms without joining.

The API account status will change to online during the process.

An array of panel objects are required. Use the panel() function to create the objects. The panel itself will act as a button, and its behaviour is defined by a panel button object using panelButton(). Within the panel, custom buttons can be placed using an array of the button objects.

let button1 = lakeel.button("message", "Button Clicked!", "Button One");
var panelButton1 = lakeel.panelButton("message", "Panel Clicked!");
var panel = lakeel.panel("It's a panel!", panelButton1, [button1...]);

let buttonMsg = messenger.sendCarousel("target_JID", "It's a message!", [panel]);

Request

TypeParameterContentRequired
stringjidTarget JID
stringmessageMessage to send
arraypanelsPanel Objects

Response

TypeNameContent
stringtimestampTime of message sent in ISO 8601 format
stringmessageIdMessage ID

Panel Object

TypeNameContentRequired
stringbodyBody message for a panel
objectpanelButtonPanel Button Object
arraybuttonsButton Objects
stringimageUrlImage URL
stringtitlePanel Title
stringtypePanel arrangement"horizonta""vertical""dropdown"

Panel Button Object

TypeNameContentRequired
stringtypePanel Button types"message""message_argument""dialog""url""postback""postback_argument""password"
stringvalueValue sent on click
stringlabelButton label
stringhintTips displayed in the input dialog※Valid only when type is "message_argument" or "postback_argument"
stringtokenValue added to the request header sent by the postback※Valid only when type is "postback", "postback_argument" or "password"
stringdataValue added to the request body sent by the postback※Valid only when type is "postback"

Button Object

TypeNameContentRequired
stringtypeButton types"message""message_argument""dialog""url""postback""postback_argument""password"
stringvalueValue sent on click
stringlabelButton label
stringstyleButton color"default""info""success""danger"
stringhintTips displayed in the input dialog※Valid only when type is "message_argument" or "postback_argument"
stringtokenValue added to the request header sent by the postback※Valid only when type is "postback", "postback_argument" or "password"
stringdataValue added to the request body sent by the postback※Valid only when type is "postback"

File

Send file

Send a file to a specified user or room.

If the API account is set as a bot, it must already exist in the room to send files. Otherwise, use a user API to send files to rooms without joining.

The API account status will change to online during the process.

The file path must include the target file name and its file extension.

messenger.sendFile("target_JID", "file_path/abc.jpg");

Request

TypeParameterContentRequired
stringjidTarget JID
stringfilePathFile Path

Response

TypeNameContent
stringtimestampTime of message sent in ISO 8601 format
stringfileIdFile ID

Receive file

Download a file sent in a chat using File ID.

File ID can be obtained from receiveMessage() function or from the sendFile() receipt. This function will return a File object containing a filename and binary data.

let receive = messenger.receiveFile("target_JID", "file_id");

Request

TypeParameterContentRequired
stringjidTarget JID
stringfileIdFile ID

Response

TypeNameContent
stringfileNameFile Name
BufferbodyFile in binary data

Make File

Input the response of receiveFile() function and an output file path. This will rebuild the file from downloaded binary data.

messenger.makeFile("./output", receive);

Request

TypeParameterContentRequired
stringfilePathFile Path
File ObjectfileFile Object

Response

TypeNameContent
stringmessageCompletion message "OK"

Get talks

Get your own talk. (Up to 1000 cases)

If the force parameter is not specified or set to false, only the talks updated since the last call of this function is downloaded.

messenger.getTalks(false);

Request

TypeParameterContentRequired
boolforceInclude updated talks

Response

TypeNameContent
arraytalksTalk Objects
integertotalUnreadCountTotal number of unread messages

Talk Object

TypeNameContent
stringjidTarget JID
stringtypeType"chat""room""invitation"
stringlastUpdateTimeLast update data
stringnameName
integerunreadCountUnread messages

Presence

Get a presence of a specified user.

messenger.getPresence("target_JID");

Request

TypeParameterContentRequired
stringjidTarget JID

Response

TypeNameContent
stringpresencePresence state"Online": Presence"Away": Leave temporarily"Do Not Disturb": Busy"ExtendedAway": Extended Away"Mobile": Logged in from mobile device"Offline": Not logged in
stringimageUrlThe URL of the image showing the state of presence

Room

Get room

Get information about a specified room.

messenger.getRoom("target_roomJID");

Request

TypeParameterContentRequired
stringjidTarget room JID

Response

TypeNameContent
stringnameRoom name
Owner ObjectownerOwner Object
arrayusersUser Objects
boolcanWithdrawWhether user can withdraw from this room.true: possiblefalse: impossioble

Owner Object

TypeNameContentRequired
stringjidOwner JID

User Object

TypeNameContentRequired
stringjidUser JID
stringstatusStatus for room"enter": participating"leave": withdraw"invite": inviting"refuse": participation refused"disinvite": invitation canceled

Create room

Use to create a room with specified owner and users.

Use makeOwner() and makeUser() to create Owner and User objects.

※ Do not include the owner in the User array

let owner = lakeel.makeOwner("owner_JID");
let user1 = lakeel.makeUser("user_JID");

messenger.createRoom(owner, [user1...], "Room One", true);

Request

TypeParameterContentRequired
Owner ObjectownerOwner Object
arrayusersUser Objects
stringnameRoom name
boolcanWithdrawWhether user can withdraw from this room.true: possiblefalse: impossioble

Response

TypeNameContent
stringtimestampTime of message sent in ISO 8601 format
stringroomJidRoom JID

User Object

TypeNameContentContent
stringjidUser JID

Edit room

Edit an existing room.

There are two statuses for User object. Set as "enter" when adding a new user and "leave" when withdrawing an existing member.
When changing the owner, be sure to designate the member whose status is "enter".

Use makeOwner() and makeUser() to create Owner and User objects.

Previously makeUser() did not require a user status when creating a room. However, user status is required when editing room.

let owner = lakeel.makeOwner("owner_JID");
let user1 = lakeel.makeUser("user_JID", "enter");
let user2 = lakeel.makeUser("user_JID", "leave");

let room = messenger.editRoom("target_roomJID", owner, [user1, user2], "New Name", true);

Request

TypeParameterContentRequired
stringjidTarget room JID
Owner ObjectownerOwner Object
arrayusersUser Objects
stringnameRoom name
boolcanWithdrawWhether users can withdraw from this room.true: possiblefalse: impossioble

Response

TypeNameContent
stringtimestampTime of message sent in ISO 8601 format
stringroomJidRoom JID

User Object

TypeNameContentRequired
stringjidUser JID
stringstatusStatus for room"enter": participating"leave": withdraw

User

Account lock status

Update an account lock status of a specified user.

messenger.changeLock("target_JID", true);

Request

TypeParameterContentRequired
stringjidTarget JID
boollockedLock statustrue: Lockfalse: Unlock

Response

TypeNameContent
stringmessageCompletion message "OK"

Change password

Change a password of a specified user.

messenger.changePassword("target_JID", "newpass", true);

Request

TypeParameterContentRequired
stringjidTarget JID
stringpasswordNew password
boolforcedSet whether to change the password the next time you sign in forcibly.true : forcefalse : Don’t force.If not specified, false is set.

Response

TypeNameContent
stringmessageCompletion message "OK"

Reset password

Reset an existing password of a specified user to a character string created with random number.

messenger.resetPassword("target_JID");

Request

TypeParameterContentRequired
stringjidTarget JID

Response

TypeNameContent
stringpassword8 digit new password

Browserify

How to use it in HTML and web page using Browserify

Install Browserify globally

npm install -g browserify

Create an empty project and install Lakeel Messenger APIs.

Make sure "lakeel-messenger-apis" exists in your node_module folder.

Create a main.js at the project directory.

//main.js
'use strict';
console.log("Module Loaded");
const lakeel = require('lakeel-messenger-apis');

window.lakeel = lakeel;

Save and run

browserify main.js -o bundle.js

Now take the bundle.js and place it in your web folder. Import and done.

Sample

//index.html
<script type="text/javascript" src="bundle.js"></script>
<script type="text/javascript">
    const apiKey = "api";
    const secretKey = "secret";
    const hostname = "example.hostname.com";
    const messenger = new lakeel.LM(apiKey, secretKey, hostname);
    const jid ="target@example.hostname.com";
</script>

<form>
<h1>Message test</h1><br>
<input type="text" value="Hi" id="msg"><br>
<input type="submit" onclick="messenger.sendMessage(jid,document.getElementById('msg').value)">
</form>

Error handling

Errors can be caught using catch().

Sample

Failed to send a message.

const send = messenger.sendMessage("target_JID", "Hi!")

.then((success) => console.log("Success"))
.catch((err) => console.log(err));

Error response is in the following format

{
    "error": {
        "code": 400,
        "message": "Missing parameters.",
        "function": "sendMessage",
        "err": Error
    }
}
{
    "error": {
        "code": 400,
        "message": "Posted data has problems.",
        "invalidData": {
            "users": [
                {
                    "jid": "userxxx@example.lakeel.com",
                    "cause": "Non-existent user."
                },
                {
                    "jid": "useryyy@example.lakeel.com",
                    "cause": "Duplicated user."
                }
            ]
        }
    }
}

Help

Bugs

Known bugs

  • Error 503 page is returned when calling a receieveFile with an invalid file ID
  • Editing room does not return room JID after a successful process

Example

What does it do?

  • Sends an image
  • Downloads the sent image
  • Rebuilds the downloaded data to an output folder as an image

All using a Promise chain

const lakeel = require('lakeel-messenger-apis');

const apiKey = "api";
const secretKey = "secret";
const hostname = "example.hostname.com";
const img = "cat.jpg";
const messenger = new lakeel.LM(apiKey, secretKey, hostname);

const jid ="target@example.hostname.com";

//Send the file
messenger.sendFile(jid, img)
.then((data) => {
    let fileId = data['fileId']; //Extract the file ID
    return messenger.receiveFile(jid, fileId); //Download the image
})
.then((result) => {
    //Rebuild the image to the output folder
    return messenger.makeFile("./output", result);
})
.fnally(() => {
    console.log("Success :)");
})
.catch((err) => {
    console.log("Something went wrong :( " , err);
});

Author

Kamata Takashi

License

ISC