0.3.1 • Published 5 years ago

zoom-bot-sdk v0.3.1

Weekly downloads
1
License
Apache-2.0
Repository
-
Last release
5 years ago

THIS PACKAGE HAS MOVED

Please see the latest official package here, thank you!


Zoom-bot-sdk

This library provide interfaces to quickly build bots and applications for Zoom Messaging framework. All the complexities of oAuth2, sending messages and receiving notifications to and from Zoom client are hidden within the library so that you can focus on building the business logic of your application.

Requirements

This package supports Node v8 and higher.

Installation

npm install zoom-bot-sdk

Features

Zoom connector offers Resource Owner && Authorization Server for you to integrate with zoom client . Each app can connect different user to trigger different actions(You need to install zoom client 4.4 or up to use the actions function in the bot)

Preparatory work

for developer,in marketplace

  • click develop > build app > write app name&&select chat bot >create to create your new app
  • add oauth url in marketplace App Credentials > redirect url for oauth ,just like https://domain/oauth2
  • add webhook in marketplace feature > chat subscription > add command && add bot endpoint url,just like https://domain/webhook
  • zoom openapi site

Example

oauth2 && webhook

const { oauth2, client, setting,log } = require('zoom-bot-sdk');
const db = require('./db');

let oauth2Client = oauth2(
  process.env.zoomClientId,
  process.env.zoomClientSecret,
  process.env.zoomRedirect_uri+'/auth'
);

let zoomBot = client(
  process.env.zoomClientId,
  process.env.zoomVerifyCode,
  process.env.zoomBotJid,
  process.env.app
)
.commands([
  { command: 'meeting', description: 'request a meeting', hint: '<meetingno>' },
  { command: 'config', description: 'get config url', hint: '' }
])
.configurate({help:true,errorHelp:true})//auto create help command after input help in zoom im,and  Command not found after input error command
.defaultAuth(oauth2Client.connect());


//middleware auth

app.post('/auth',
  async function(req,res,next){//inject zoomApp
      let {code}=req.query;
      try{
        let connection=await oauth2Client.connectByCode(code);
        let zoomApp=zoomBot.create({auth:connection});//create a bot instance for this ouath,can use this instance to do any openapi request which built-in access_tokens
        res.locals.zoomApp=zoomApp;
        next();
      }
      catch(e){
        // error handle
      }
  },
  async function(req,res){
      let { zoomApp } = res.locals;
      let tokens = zoomApp.auth.getTokens();
      //save tokens
      try{
          await db.models.zoom.save({access_token:tokens.access_tokens,....});
          res.redirect('page url');
      }
      catch(e){
        //error handle
      }
  });


//middleware for command and sendmessage

app.post('/webhook',
  async function(req,res,next){//inject zoomApp and webhook data
      let {body,headers}=req;
      try{
          let wehookData = await zoomBot.handle({ body, headers });
          //create a app instance
          let zoomApp = zoomBot.create({ auth: oauth2Client.connect() });
          res.locals.zoomApp = zoomApp;
          res.locals.wehookData = wehookData;
          next();
      }
      catch(e){
       //handle error
      }
  },
  async function(req,res){
      let {zoomApp, wehookData}=res.locals;
      //if input 'meeting name no' in zoom im,command is meeting,data is [name,no],type said it is one to one chat or channel.
      let { payload,data,type,command,message } = wehookData;
      let { toJid: to_jid,command,data, userId, accountId: account_id, channelName,name } = payload;
      try{
        await zoomApp.sendMessage({
          to_jid,account_id,body,header //can also use content={body,header} replace
        });
      }
      catch(e){
        //handle error
      }
      res.send();
  })


//trigger zoom openapi which zoom access_token from database

app.post('/meeting',
  async function(req,res,next){//inject zoomApp
      let zoomApp = zoomBot.create({ auth: oauth2Client.connect() });
      res.locals.zoomApp = zoomApp;
      next();
  },
  async function(req,res){
      let {zoomApp}=res.locals;
      let item=db.models.zoom.get({id:...});
      zoomApp.auth.setTokens({
        access_token:item.get('access_token'),
        refresh_token:item.get('refresh_token'),
        expires_in:item.get('expires_in')
      });
      zoomApp.auth.callbackRefreshTokens(async function(tokens){//if request openapi and meeting access_token out of data,zoomApp will try to use your refresh_token to get access_token again,and new tokens will pass in this function,and you can store them in database
      try{ await db.models.zoom.save({id,access_token:tokens.access_token,.....});}
      catch(e){}
      });
      try{
        await zoomApp.request({//request meeting openapi,see https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingcreate for more apis
          url:'/v2/users/userid/meetings',
          method:'post',
          body:{...}
        });
      }
      catch(e){
      //handle error
      }
      res.send();
  });


// and also,you can use zoomBot.on('command',function(){}), oauth2Client.on('tokens',function(){}) to do same things

sometimes,request maybe error,can retry via some condition,support request,getUser,sendMessage api to retry.

// if first sendMessage error,can trigger it again after timeout over,and max no is 3,condition of trigger as follows
setting.retry({
  sendMessage:{
    no:3,
    timeout(no,lg){return Math.random() * (10000 - 5000) + 5000;},
    condition(backMsg,ind){//backMsg is https response message,ind is the retry no
      if(typeof backMsg==='object'&&backMsg.code&&backMsg.code.toString()==='7010'){
          return true;
        }
    }
});

if you want all command case no sensitive

setting.caseSensitive(false);

if you want to debug your app

setting.debug(true);

DEBUG=http node index.js //now we only support http debug

what is connection

connection is a auth instance , we can create connection by oauth2Client.connectByCode(code) , oauth2Client.connectByRefresh(refreshcode) , oauth2Client.connectByTokens(tokens) tokens is from your db store , oauth2Client.connect() if you only need sendmessage to zoom im and you have know the relevant account_id and to_jid (these two datas you can get from webhook event payload or getUser)

after you create connection,you need bind it with your client instance ,just like let app=zoomBot.create({auth: oauth2Client.connect()}),the app instance which you can trigger the action

each user can create different connection,you can store some connections by own business demand

what is zoomBot

you can use zoomBot to configurate your commands,create account app, check command, parse webhook data and so on

zoomBot instance represents an bot on the marketplace , and after you use let app=zoomBot.create({auth: oauth2Client.connect()}) , you get a account instance which name app , you can use the account app to do the action ,just like get account id, sub user id , channel id in your current account , each app represents a new account.you can store you account app by own business demand

this lib integrate help command

after you bind webhook , then you write help in zoom im, and lib will auto send default content(which you configure in commands([])) to im

and if you send message in im which is not config in commands,you can use zoomBot.configurate({errorHelp:true}) and will send help content after write the command which in commands config.

Usage

global

const { oauth2, client, setting } = require('zoom-bot-sdk');
// setting.setUrl('https://dev.zoom.us'); default is https://api.zoom.us . dev.zoom.us if for test

oauth2 with zoom

init oauth instance

// const {oauth2} =require('zoom-bot-sdk');
const oauth2Client=oauth2(Your Client Id,Your Client Secret,Your redirect url);




//update tokens to database by api

oauth2Client.callbackNewTokens(function(tokens){//when use code->accesstoken and accesstoken created.
  // db.save(tokens);
});

oauth2Client.callbackRefreshTokens(function(tokens){//when access_token out of date,and refresh token get new access_token
  // db.save(tokens);
});


//or you can use event model to update tokens as follows

/*
interface ClientTokens{
access_token:string;
token_type:string;
refresh_token:string;
expire_in:number;
scope:string
}
*/
//trigger when get new tokens
oauth2Client.on('tokens',(tokens)=>{
//store tokens to db,or other handles
});

/*
interface ClientTokens{
access_token:string;
token_type:string;
refresh_token:string;
expire_in:number;
}

interface Err{
    type:string;//temporary support value:(token|clientToken)
    message:any;
}
*/
oauth2Client.on('error',(err)=>{

});

create auth connection

//If you just have a sendmessage action requirement , no need for get access_token,you can just use let connection= oauth2Client.connect();

let connection = await oauth2Client.connectByCode(code);
let connection = await oauth2Client.connectByRefresh(refresh_token);
let connection = oauth2Client.connectByTokens(tokens);
// if you just need to trigger sendMessage action,and you already have account_id and group_jid from your db,you can just to use oauth2Client.connect(),and then you can use sendMessage action only
let connection = oauth2Client.connect(); //not auto request tokens

connection api

let tokens = await connection.requestTokensByRefresh(refresh_token);
let tokens = await connection.requestTokens(code);
let clientTokens = await connection.requestClientTokens();
let ifExpired = connection.expired(); //check access_token whether expired or not
let ifClientExpired = connection.expiredClient(); //check client access_token whether expired or not
let tokens = connection.getTokens();
let clientTokens = connection.getClientTokens();
connection.setTokens(tokens); //if you want to update tokens temporary

zoom client action && message

create zoombot instance and config command&&version for help command

// const {client}=require('zoom-bot-sdk');
//you can get verification token and robot_jid in zoom marketplace features.
/*
   Interface CommandObj{
      command:string;//your command name
      description:string;//your description of command
      hint?:string;//your command arguments
   }

   opts:CommandObj|Array<CommandObj>
*/
let zoomBot=client(your clientid,your Verification Token,your robot_jid)
.command(opts).defaultAuth(oauth2Client.connect());//you must to config a default auth for default help command,just use oauth2Client.connect()


//if you want to config help mode,help:true will auto send help content to zoom im after you input help in im,errorHelp:true will auto send help content to zoom im when you input in im which is not in your commands config.
zoomBot= zoomBot.configurate({help:true,errorHelp:true}); //default help:true,errorHelp:false


//you can check command to see whether it is in commands config , and then manual trigger help
let ifInCommands=zoombot.checkCommands(commandString);
if(!ifInCommands){await zoombot.triggerHelp(account_id,to_jid);}

create one business instance with oauth2 connection in zoombot

//if use auth argument no need to import tokens argument
//access_token will auto be requested when judge expired
const userApp = zoomBot.create({
  auth: connection
});

use business instance to handle action(for now,only support getUser,sendMessage three action,and you can also use request to request any api which not need to inject token auth)

use request to request any zoom open api

/*

interface Option{
  url:string; //  /v2/groups or http://api.zoom.use...,
  path:string; //   /v2/groups
  method:string; //get ,post,delete..., default is get
  body:object;  // the data you want to send by post,application/json is most openapis zoom zpi used
  query:object; // url query
  form:object; //if you want to send data by x-www-form-urlencodeed
  formData:object;// if you want to send data by formdata
  timeout:number;
  header:object //will default integrate Authorization:.. for headers,you can overwrite it
}

type:string // can use access or credential,default is access which is access_token type
opt:Option

*/

await userApp.request(opt, type);

get user

//if email is empty ,will return userId corresponds to the current access_token ,if send specific email,will return the corresponding sub-account under account 。
/*
   interface UserInfo{
       id:string;//user id
       account_id:string;
       email:string;
       [propName: string]: any;
   }
   email?:string
*/

let userInfo = await userApp.getUser(email);

sendMessage

/*
    body example:
    {
      'type': 'message',
      'text': 'this is sendmessage info',
      'style': { 'color': '#000000', 'bold': true, 'itatic': false }
    }

    header example:
    { 'text': 'kogss' }

    Body:Array<Msg>|Msg;

    Interface Header{
        text:String;
        style:Style;
    }

    Interface Settings{
       default_sidebar_color:'string';// just like #778614 color value,to set message sidebar color
    }
    Interface Option{
        account_id:String;//account_id from getUser action userInfo
        to_jid:String;//from im payload
        body:Body;// send one or multiple message
        header:Header;
        settings:Settings;//optional,main configure sidebar style
    }

    or

    Interface Option{
        account_id:String;//account_id from getUser action userInfo
        to_jid:String;//from im payload
        content:{Body,Header,otherProps of sendmessage openapi}
        settings:Settings;//optional,main configure sidebar style
    }

*/

let backInfo = await userApp.sendMessage(option);

message event

handle request and get webhookData

//err is object type,{type:'format|verify|triggerHelp|triggerNoMatchCommand',errorMessage}; if err===null,will hint no error

/*
     interface Payload{
            robotJid:String;
            userJid:String;
            toJid:String,
            accountId:String,
            userId:String,
            name:String,
            timestamp:Number,
            cmd:String
        }

//support multiple async function
//when have command : /zoom create foxjiang 2019-08-08

//in action event type

    Interface WebhookData{
      type:string;//one or group which come from im user type
      payload:Payload;
      info:{original:Original,current:Current};//see the info below for details
      action:String;//button or dropdown or edit or field_edit
   }

//in notification event type
   Interface WebhookData{
      type:string;//one or group which come from im user type
      payload:Payload;
      message:string;//origin content from im ,just like 'create foxjiang 2019-08-08'
      data:Array<string>;//just like ['foxjiang','2019-08-08']
      command:string;//notification,just like create
   }
*/

expressApp.get('/someapi', async function(req, res, next) {
  let { body, headers } = req;
  try{
    let webhookData=await zoomBot.handle({ body, headers });
    //handle your logic with webhookData
  }
  catch(e){
    console.log(e);
  }
  res.send('some res');
});

listen message model

//event data type is same with WebhookData
zoomBot.on('actions', function(event) {
  // handle your logic
});

zoomBot.on('commands', function(event) {
  // handle your logic
});

action info format

button info

info:{
original:{"head":{"text":"reply from userName dev-lambda-bot-deploy"},"body":[{"type":"section","footer_icon":"https://platform.slack-edge.com/img/default_application_icon.png","footer":"some footer","sidebar_color":"#222222","sections":[{"type":"message","text":"section1"},{"type":"actions","limit":2,"items":[{"text":"button8888","style":"Danger","value":"button2"},{"text":"button3888","style":"Disabled","value":"button3"}]}]}]},
current:{"text":"button8888","value":"button2"}
}

dropdown info

info:{
original:{"head":{"text":"reply from userName dev-lambda-bot-deploy"},"body":[{"type":"select","text":"My Dropdown","style":{"color":"#987654","bold":false,"itatic":true},"selected_item":{"text":"t3","value":"v3"},"select_items":[{"text":"t1","value":"v1"},{"text":"t2","value":"v2"},{"text":"t3","value":"v3"},{"text":"t4","value":"v4"}]}]},
current:[{"value":"v4"}]
}

edit info

info:{
original:{"head":{"text":"reply from userName dev-lambda-bot-deploy"},"body":[{"type":"message","editable":true,"text":"sunday","style":{"color":"#000000"}}]},
current:{"origin":"sunday","target":"what's your name"}
}

body type

We will support more message body after the new zoom client release

//notification message
  {
            "type":"message",
            "text":"this is first message.",
            "style":{
               "color":"#FFFFFF",
               "bold":true,
               "itatic":false
            }
         }
//link message
 {
            "type":"message",
            "text":"zoom.us",
            "link":"https://zoom.us"
 }

//section message,can integration with button,footer,and so on,sidebar_color can't use in type message slack
{
        "type": "section",
        "footer_icon": "https://platform.slack-edge.com/img/default_application_icon.png",
        "footer": "some footer",
        "sidebar_color": "#222222",
        "sections": [
            {
                "type": "message",
                "text": "section1"
            },
            {
                "type": "actions",
                "limit": 3,
                "items": [
                    {
                        "text": "button8888",
                        "style": "Danger",
                        "value": "button2"
                    },
                    {
                        "text": "button3888",
                        "style": "Disabled",
                        "value": "button3"
                    },
                    {
                        "text": "button488",
                        "value": "button4"
                    }
                ]
            }
        ]
  }

//field message


{
              "type": "fields",
              "items": [
                  {
                      "key": "name",
                      "value": "lee yang",
                      "isName": true,
                      "short": true
                  },
                  {
                      "key": "zoom",
                      "value": "zoom.us",
                      "link": "https://zoom/us",
                      "short": true
                  }
              ]
   }

//attachment message

{
              "type": "attachments",
              "resource_url": "https://docs.google.com/document/d/test/edit?usp=drive_web",
              "img_url": "https://avatars1.githubusercontent.com/u/7495313?v=4",
              "size": 3000,
              "information": {
                  "title": {
                      "text": "test csv"
                  }
              }
 }


//edit message

{
            "type":"message",
            "editable": true,
            "text":"sunday",
            "style":{
                "color":"#000000"
            }
}

header type

{"text":"your header text"}
or
{"text":"your header text",
        "style":{
        "color":"#000000",
        "bold":true,
        "itatic":false
        }
}
// and you can also add sub head message

{"text":"your header text",
 "sub_head":{
        "text":"String",
        "style":{
            "color":"String",
            "bold":boolean,
            "itatic":boolean
        }
  }
}
0.3.1

5 years ago

0.3.0

5 years ago

0.2.9

5 years ago

0.2.8

5 years ago

0.2.7

5 years ago

0.2.6

5 years ago

0.2.5

5 years ago

0.2.4

5 years ago

0.2.3

5 years ago

0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.17

5 years ago

0.1.16

5 years ago

0.1.15

5 years ago

0.1.12

5 years ago

0.1.11

5 years ago

0.1.10

5 years ago

0.1.9

5 years ago

0.1.8

5 years ago

0.1.6

5 years ago

0.1.5

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago