Skip to main content

Methods

These are the methods that can be accessed by the CommonJS require() function. You can make use of the these method to perform different kinds of features like setting new agenda, sending emails, etc.

Example


const _ = require("lodash")
const obj = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(obj, 'a[0].b.c', null);
// => 3

Node.js builtin library

LibraryNode.js Documentation
cryptocrypto
httphttp
httpshttps
urlurl
querystringquerystring

3rd party library

LibraryDescription
node-fetchNode-fetch (const fetch = require("node-fetch")) is a library for sending http(s) requests.
momentMoment (const moment = require("moment")) is a library for time related logic. The moment-timezone is also supported.
lodashLodash (const _ = require("lodash")) is a utility library that improves QoL.
xml2jsxml2js (const { parseString } = require("xml2js")) is a utility library that parse xml to javascript object.
uuiduuid (const { v4: uuidv4 } = require("uuid")) is a utility library that generate uuid.
stripestripe (const Stripe = require("stripe")) is Stripe API wrapper.

Custom methods provided by WOZTELL

These methods can be accessed by built-in integration require("woztell-essential-pack")

Example


const { getMember } = require("woztell-essential-pack")
const member = await getMember({
memberId: this.member._id
})


DB Notes

WOZTELL use mongoDB as database. For any DB methods below, please see the mongoDB CRUD Operations documentation for reference. More specifically, you should refer to the mongoDB's "Query Document" section for the filter parameter. For the patch and withModifier parameters, you should refer to mongoDB's "Change a Document" section, where the patch object will be set as $set if withModifier is false, while setting withModifier to true will let you customize the update modifier, or to replace the document.

A findAndModify method is an atomic operation, ie. the "find" and "modify" happens at the same time. It is preferred to doing a "find" operation and a "modify" operation separately. It is used to prevent a critical action from happening more than once, even if the user spams the input or the external service sends multiple events at the same time, accidentally or purposefully. To achieve this, a filter and patch pair should be set so that the same entry won't be found after being modified. The example in findAndModifyMember shows how it works.


withModifier: false
patch = {
key: value
}

update = {
$set: {
key: value
}
}
withModifier: true
patch = {
$addToSet: {
key: value
}
}

update = {
$addToSet: {
key: value
}
}

fetchDataFromDataSource

The method fetchDataFromDataSource() is used to fetch data from data source.



Example
fetchDataFromDataSource({ collectionName: string, dataSourceId: string , filter: object, count: boolean, sortBy: object })

Parameter
NameTypeDescription
collectionNamestringEither collectionName or dataSourceId. Collection name
countbooleanDefault false. Status of this method is performing count feature only
dataSourceIdstringEither collectionName or dataSourceId. Data source ID
filterobjectOptional Filter criteria. Shares the same method as MongoDB query. Please see MongoDB for further reference
sortByobjectOptional Shares the same method as MongoDB query. Please see MongoDB for further reference

Response

[
{
"id": string
// ...
},
// ...
]

fetchDistinctDataFromDataSource

The method fetchDistinctDataFromDataSource() is used to fetch distinct data(i.e. the column of the data source table) from data source.



Example
fetchDistinctDataFromDataSource({ collectionName: string, dataSourceId: string , filter: object, count: boolean, sortBy: object })

Parameter
NameTypeDescription
collectionNamestringEither collectionName or dataSourceId. Collection name
countbooleanDefault false. Status of this method is performing count feature only
dataSourceIdstringEither collectionName or dataSourceId. Data source ID
keystringThe column you wish to fetch from data source
filterobjectOptional Filter criteria. Shares the same method as MongoDB query. Please see MongoDB for further reference

Response

[
value of key,
// ...
]

fetchGeoNearFromDataSource

The method fetchGeoNearFromDataSource() is used to fetch geographical data from data source.



Example
fetchGeoNearFromDataSource({ collectionName: string, data: object, dataSourceId: string })

Parameter
NameTypeDescription
collectionNamestringEither collectionName or dataSourceId. Collection name
dataobjectGeo data
dataSourceIdstringEither collectionName or dataSourceId. Data source ID

Response

[
{
"id": string
},
// ...
]

countDataSource

The method countDataSource() is used to count the information about the present channel.



Example
countDataSource({ collectionName: string, dataSourceId: string, filter: object })

Parameter
NameTypeDescription
collectionNamestringEither collectionName or dataSourceId. Collection name
dataSourceIdstringEither collectionName or dataSourceId. Data source ID
filterobjectOptional Filter criteria. Shares the same method as MongoDB query. Please see MongoDB for further reference

Response

400 // A number

patchDataToDataSource

The method patchDataToDataSource() can be used to patch data to data source. In this call, the patch object will be formatted in this way in the data source table: each object becomes a new row; object key becomes column and object value becomes the value.



Example
patchDataToDataSource({ collectionName: string, dataSourceId: string, filter: object, patch: object, options: object, multi: boolean, withModifier: boolean })

Parameter
NameTypeDescription
collectionNamestringEither collectionName or dataSourceId. Collection Name
dataSourceIdstringEither collectionName or dataSourceId. Data Soruce ID
filterobjectOptional Filter criteria. Shares the same method as MongoDB query. Please see MongoDB for further reference
multibooleanOptional Whether update multiple fields
optionsobjectOptions for the request
patchobjectThe field and data that needs to be patched
withModifierbooleanDefault false Status the method contains modifier

Response

{
"matched": number
"modified": number
"inserted": number
"deleted": number
}

findAndModifyDataFromDataSource

The method findAndModifyDataFromDataSource() is used to find and modify a data entry in a Data Source.


Parameter

NameTypeDescription
dataSourceIdstringData Source ID
filterobjectFilter to find the data entry
patchobjectObject to be patched to the data entry
withModifierbooleanDefault false. see DB Notes for more details
sortByobjectOptional. Order to sort the data entries. Note: only the first data entry after sorting is found and modified by this method.
optionobjectOptional. Use { "new": true } to get the modified data entry. Please refer to mongoDB's Collection Methods for other options.

Example

findAndModifyDataFromDataSource({
dataSourceId: "a12345678901234567890123_coupon",
filter: {
location: "HK",
memberId: null,
},
patch: {
memberId: "m12345678901234567890123",
deliveredAt: 1601481600000,
},
withModifier: false,
sortBy: {
priority: 1,
},
option: {
new: true,
}
})

Response

NameTypeDescription
oknumber1 for successful call
valueobjectThe data entry object found. If option.new is true, the modified data entry will be returned. Otherwise, the original data entry will be returned. Return null if no matched data entry is found.
{
ok: 1,
value: {
_id: "d12345678901234567890123",
location: "HK",
couponCode: "1234",
priority: 0,
memberId: "m12345678901234567890123",
deliveredAt: 1601481600000,
createdAt: 1577808000000,
updatedAt: 1601481600000
}
}


upsertDataToDataSource

The method upsertDataToDataSource() will upsert data entries in the Data Source. If _id exists in the data object, it will be upserted in the Data Source, ie. if a data entry with the same _id exists, the entry will be updated, else, a new data entry will be inserted. Otherwise, a new data entry will be inserted.


Parameter

NameTypeDescription
dataSourceIdstringData Source ID
dataobject or [object]Data to be updated or inserted

Example

upsertDataToDataSource({
dataSourceId: "a12345678901234567890123_coupon",
data: [{
_id: "d12345678901234567890123", // exists in Data Source
location: "HK",
couponCode: "0123",
priority: 1,
}, {
_id: "d12345678901234567890124", // not exists in Data Source
location: "KLN",
couponCode: "0124",
priority: 2,
}, {
location: "NT",
couponCode: "0125",
priority: 3,
}]
})

Response

NameTypeDescription
resultobjectResult object

Result

NameTypeDescription
_docsIdsobjectDocsIds object
matchednumberNumber of matched entries
modifiednumberNumber of modified entries
insertednumberNumber of inserted entries
deletednumber0

DocsIds

NameTypeDescription
updated[string]Array of _id of updated entries
inserted[string]Array of _id of inserted entries
upserted[string]Array of _id of inserted entries with _id provided
{
result: {
_docsIds: {
updated: ["d12345678901234567890123"],
inserted: ["d12345678901234567890125"],
upserted: ["d12345678901234567890124"]
},
matched: 1
modified: 1
inserted: 2
deleted: 0
}
}


newAgenda

The method newAgenda() can be used to create new agenda. Please refer to here for reference on the Agenda system.


Parameter

NameTypeDescription
memberIdstringWOZTELL Member ID
treeIdstringTree ID
nodeCompositeIdstringNode Composite ID
nextRunAtnumberOverride pattern. Either nextRunAt or pattern is required. Timestamp for executing the agenda (Unix epoch time in milliseconds). The moment.js library can be used, eg. moment().add(5, "minutes").valueOf() gives the timestamp of 5 minutes from now.
patternstringEither nextRunAt or pattern is required. CRON Pattern of the agenda. If you wish to check the CRON pattern, you can use Crontab Guru
runUntilnumberRequired if pattern is used. The agenda will be executed following the pattern until the runUntil timestamp.
prioritynumberOptional. The priority of the agenda. Agenda with the smaller priority number will be executed first.
metaobjectOptional. The data associated with the agenda. This object can be accessed by this.agendaMeta when the agenda is executed.
replacebooleanDefault false. Set as true to replace agendas of the same member with the same tag.
tagstringRequired if replace is true. Agenda tag

Example

newAgenda({
memberId: "m12345678901234567890123",
treeId: "t12345678901234567890123",
nodeCompositeId: "abcdefghijklmnop",
nextRunAt: 1609430400000,
priority: 1,
meta: {
testing: true
},
replace: true,
tag: "testing-agenda"
})

Response

The agenda object created will be returned.

{  
_id: "ag2345678901234567890123",
app: "a12345678901234567890123",
channel: "c12345678901234567890123",
member: "m12345678901234567890123",
tree: "t12345678901234567890123",
nodeCompositeId: "abcdefghijklmnop",
nextRunAt: 1609430400000,
priority: 1,
meta: {
testing: true
},
tag: "testing-agenda",
completed: false,
}


updateAgenda

The method updateAgenda() can update the agenda in the database.



Example
updateAgenda({ memberId: string, meta: object, nextRunAt: number, nodeCompositeId: string, priority: number, pattern: string, replace: boolean, runUntil: number, tag: string, treeId: string })

ParameterTypeDescription
memberIdstringWOZTELL Member ID
metaobjectThe data wish to send inside the agenda
nodeCompositeIdstringNode Composite ID
nextRunAtnumberTime for running the next agenda in milliseconds. This property will override the pattern property
patternstringCRON Pattern of the agenda. If you wish to check the CRON pattern, you can use Crontab Guru
prioritynumberThe priority of the agenda
runUntilnumberTimestamp for running the agenda until it stops
replacebooleanDefault false. Whether the input is replaced
treeIdstringTree ID
tagstringMember tag

Response

{
"_docsIds": {
"updated": array<string>
},
"_docs": array<object>
"modified": number
}

deleteMemberAgenda

The method deleteMemberAgenda() is used to delete member agenda by WOZTELL member ID.



Example
deleteMemberAgenda({ memberId: string, tag: string })

Parameter
NameTypeDescription
memberIdstringWOZTELL Member ID
tagstringSpecific agenda name

Response

{
"clientMutationId": string
}

sendEmail

The method sendEmail() can be used to send email through Amazon SES service from no-reply@sanuker.com. This method returns nothing from our API.



Example

const params = {
Destination: {
CcAddresses: ["sample@sanuker.com", "sample2@sanuker.com"],
ToAddresses: ["sameple3@sanuker.com", "sameple4@sanuker.com"]
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: "HTML_FORMAT_BODY"
},
Text: {
Charset: "UTF-8",
Data: "TEXT_FORMAT_BODY"
}
},
Subject: {
Charset: 'UTF-8',
Data: 'Test email'
}
}
}

sendEmail(params)
ParameterTypeDescription
destinationobjectThe email address you want to send and CC to.
messageobjectThe subject and message(in either HTML or Text format) you want to have in the email.

uploadFileToS3

The method uploadFileToS3() can upload file to our S3 server. Please note that this method return nothing.



Example
stripe({ url: string, options: object, channel: object, filename: string, contentType: string })
ParameterTypeDescription
urlstringURL of the file
optionsobjectOption of the request
channelstringChannel Object
filenamestringName of the file
contentTypestringContent type of the file

getMember

The method getMember() is used to get the information about the present member from its WOZTELL member ID.



Example
getMember({ memberId: string })

Parameter
NameTypeDescription
memberIdstringWOZTELL Member ID

Response

{
"_id": string
"_version": number
"app": string
"botId": string
"botMeta": object
"channel": string
"createdAt": timestamp
"etag": string
"externalId": string
"firstName": string
"gender": string
"meta": object
"platform": string
"profile": object
"tags": array<object>
"updatedAt": timestamp
}

patchMembers

The method patchMembers() can be used to patch data to members.



Example
patchMembers({ channel: object, memberId: string, filter: object, patch: object, withModifier: boolean })

Parameter
NameTypeDescription
channelobjectChannel object
filterobjectOptional Filter criteria. Shares the same method as MongoDB query. Please see MongoDB for further reference
memberIdstringWOZTELL Member ID
patchobjectThe field and data that needs to be patched
withModifierbooleanDefault false Status the method contains modifier

Response

{  
"result": {
"_id": string
"createdAt": timestamp
"updatedAt": timestamp
"profile": object
// ...
}
}

findAndModifyMember

The method findAndModifyMember() is used to find and modify a member.


Parameter

NameTypeDescription
filterobjectFilter to find the member
patchobjectObject to be patched to the member
withModifierbooleanDefault true. see DB Notes for more details
sortByobjectOptional. Order to sort the members. Note: only the first member after sorting is found and modified by this method.
optionobjectOptional. Use { "new": true } to get the modified member. Please refer to mongoDB's Collection Methods for other options.

Example

findAndModifyMember({
filter: {
firstName: "John",
"meta.checked": false,
},
patch: {
"meta.checked": true,
},
withModifier: false,
sortBy: {
_id: -1,
},
option: {
new: true,
}
})

Response

NameTypeDescription
oknumber1 for successful call
memberobjectThe Member object found. If option.new is true, the modified member will be returned. Otherwise, the original member will be returned. Return null if no matched member is found.
{
ok: 1,
member: {
_id: "m12345678901234567890123",
app: "a12345678901234567890123",
channel: "c12345678901234567890123",
externalId: "1234567890",
firstName: "John",
lastName: "Doe",
botMeta: {
liveChat: false,
subscribe: true,
tempData: {},
nodeCompositeId: "abcdefghijklmnop",
tree: "t12345678901234567890123"
},
meta: {
checked: true,
},
platform: "custom",
tags: [],
createdAt: 1577808000000,
updatedAt: 1601481600000
}
}


updateMember

The method updateMember() can the update member's information in the database.



Example
updateMember({ member: object })

ParameterTypeDescription
memberobjectMember object

Response

{
"_docsIds": {
"updated": array<string>
},
"_docs": object
"modified": number
}

getChannel

The method getChannel() is used to get the information about the present channel.



Example
getChannel({ channelId: string })

Parameter
NameTypeDescription
channelIdstringThe channel ID that you have

Response

{
"_id": string,
"app": string,
// ...
}

redirectMemberToNode

The method redirectMemberToNode() is used to redirect a member to a node. The node will then be executed for the member according to the redirectOptions. For usage in WOZTELL API, you may also refer to the WOZTELL API documentation.


Parameter

NameTypeDescription
memberIdstringWOZTELL Member ID
channelIdstringChannel ID of the Member
treeIdstringTree ID
nodeCompositeIdstringNode composite ID
redirectOptionsobjectOptional. RedirectOptions Object
metaobjectOptional. The data associated with the node. This object can be accessed by this.agendaMeta when the node is executed.

RedirectOptions

NameTypeDescription
runPreActionbooleanDefault true. Whether the Pre Actions of the node is exectued.
sendResponsebooleanDefault true. Whether the Responses of the node is sent.
runPostActionbooleanDefault true. Whether the Post Actions of the node is exectued.

Example

redirectMemberToNode({
memberId: "m12345678901234567890123",
channelId: "c12345678901234567890123",
treeId: "t12345678901234567890123",
nodeCompositeId: "abcdefghijklmnop",
redirectOptions: {
runPreAction: false,
sendResponse: true,
runPostAction: true
},
meta: {
testing: true
}
})

Response

NameTypeDescription
oknumber1 for successful call
memberstringWOZTELL Member ID
sendResults[object]Array of NodeSendResult Object. The first entry represents the send results of the node. Any subsequence entries represent the send results of the nodes redirected from the original node.

NodeSendResult

NameTypeDescription
oknumber1 for successful call
memberstringWOZTELL Member ID
result[object]Array of SendResult Object. Each entry represents the send result of a response in the node.

SendResult

NameTypeDescription
resultobjectPlatform specific result to the actual send request. The example below shows the result from Facebook.
messageEventobjectMessage Event object. Please refer here for more details.
chatIdstringWOZTELL Chat ID
{
ok: 1,
member: "m12345678901234567890123",
sendResults: [
{
ok: 1,
member: "m12345678901234567890123",
result: [
{
result: {
recipient_id: "1234567812345678",
message_id: "xxxxxxxxxxxxxxxx"
},
messageEvent: {
from: "8765432187654321",
to: "1234567812345678",
data: {
url: "https://s3.ap-southeast-1.amazonaws.com/radiate-admin/59bba4275a304100055da5bc/hello-min.gif",
attachment_id: "2345678923456789",
transform: ""
},
type: "IMAGE",
timestamp: 1604160000000,
messageId: "xxxxxxxxxxxxxxxx"
},
chatId: "ch2345678901234567890123"
},
{
result: {
recipient_id: "1234567812345678",
message_id: "xxxxxxxxxxxxxxxx"
},
messageEvent: {
from: "8765432187654321",
to: "1234567812345678",
data: {
text: "Hello, I am WOZTELL the Dog ๐Ÿถ ",
transform: ""
},
type: "TEXT",
timestamp: 1604160000001,
messageId: "xxxxxxxxxxxxxxxx"
},
chatId: "ch2345678901234567890124"
},
{
result: {
recipient_id: "1234567812345678",
message_id: "xxxxxxxxxxxxxxxx"
},
messageEvent: {
from: "8765432187654321",
to: "1234567812345678",
data: {
transform: "",
quickReplies: [
{
content_type: "text",
title: "Yes โค๏ธ",
payload: "ONBOARDING"
},
{
content_type: "text",
title: "No โ˜ ๏ธ",
payload: "MAIN_MENU"
}
],
text: "My master Sanuker can help you make bots on different platforms with my help, would you like to make one?"
},
type: "QUICK_REPLIES",
timestamp: 1604160000002,
messageId: "xxxxxxxxxxxxxxxx"
},
chatId: "ch2345678901234567890125"
}
]
}
]
}


sendResponse

The method sendResponse() can send response in different channels.



Example
sendResponse({ channel: object, channelId: string, memberId: string, response: object })

ParameterTypeDescription
channelobjectChannel object
channelIdstringChannel ID
memberobjectMember object
memberIdarrayA set of WOZTELL member IDs
responseobjectResponse object. The structure of the response object can be referred to the Message Event documentation for further reference.

Response

// Facebook
{
"result": object
"messageEvent": object
}

// WhatsApp
{
"result": object
"messageEvent": object
}

// Slack
{
"ok": boolean
"channel": string
"ts": timestamp
"message": object
}

// Teams
{
"result": object
"messageEvent": object
}

// Webchat
{
"result": object
"messageEvent": object
}

// WeChat
{
"msgType": string
"url: string
"image": object
"text": object
"video": object
"title": string
"description": string
"news" string
}