My Calendar

2018年6月21日 星期四

Node.js 開發Slack Bot - 2

       Node.js開發Slack Bot - 1已經有一個連接到Slack的Chat Bot, 現在實作當Bot上線後會發送"Hello"給有邀請Bot的全部頻道。

在原本的index.js新增getAllChannels() function
function getAllChannels()
{
   return web.channels.list().then((resp)=>{
      return resp;
   }).catch((error) => {console.log(error);});
}

在connected event呼叫getAllChannels和判斷Bot在哪一個頻道。

slack.on('connected', () => {

  let user= {"user":slack.activeUserId};

  (async() =>{
             
    let userInfo = await getUserInfo(user);
    let teamInfo = await getTeamInfo();
    let allChannels = await getAllChannels();
    let channels = [];
    for (let id in allChannels.channels) {
          let channel = allChannels.channels[id];
          if(channel.is_member)
            channels.push(channel);
    }  

    let channelNames = channels.map((channel) => {
                          return channel.name;
                        }).join(', ');         

    console.log(`Connected to ${teamInfo.team.name} as ${userInfo.user.name}`);
    console.log(`Currently in: ${channelNames}`);
  })();

});

切換Terminal會看到以下類似的輸出,這時候已經知道Bot在哪一個頻道,開始發送"Hello"給這些頻道的所有人。

Connected to Deikhoong as helloBot
Currently in : bot-test

獲取頻道中的全部人
我們已經有了channels這個物件,那需要得到頻道中的人就變得非常簡單。
channels.forEach((channel) => {
     console.log('Members of this channel: ', channel.members);
});

結果如下,
Connected to Deikhoong as hellobot
Currently in: bot-test
Members of this channel:  [ 'U1GUZL79C', 'UBGN5T9K2' ]

發現channels.members回傳的不是member的物件而是member id, 這會讓我們很難辨識.我們在改寫這段程式碼使用直接的getUserInfo()獲得 user的名稱。
let members=[];
channels.forEach(async (channel) => {
     for (let id in channel.members) {
        let memberId = channel.members[id];      
        user= {"user":memberId};
        let member= await getUserInfo(user);
        members.push(member);
     }
     let memberNames = members.map((member) => {
              return member.user.name;
      }).join(', ');
     console.log('Members of this channel: ', memberNames);
});

已經可以看到user的名稱
Connected to Deikhoong as hellobot
Currently in: bot-test
Members of this channel: tan.deik.hoong, hellobot

發送訊息到頻道
透過RTMClient.sendMessage發送訊息給頻道。

slack.on('connected', () => {

  let user= {"user":slack.activeUserId};

  (async() =>{
             
    let userInfo = await getUserInfo(user);
    let teamInfo = await getTeamInfo();
    let allChannels = await getAllChannels();
    let channels = [];
    for (let id in allChannels.channels) {
          let channel = allChannels.channels[id];
          if(channel.is_member)
            channels.push(channel);
    }  

    let channelNames = channels.map((channel) => {
                          return channel.name;
                        }).join(', '); 


    console.log(`Connected to ${teamInfo.team.name} as ${userInfo.user.name}`);
    console.log(`Currently in: ${channelNames}`);

    let members=[];
    channels.forEach(async (channel) => {
         for (let id in channel.members) {
            let memberId = channel.members[id];      
            user= {"user":memberId};
            let member= await getUserInfo(user);
            members.push(member);
         }
         let memberNames = members.map((member) => {
              return member.user.name;
          }).join(', ');
        console.log('Members of this channel: ', memberNames);
        //send message to channel
        slack.sendMessage(`Hello ${memberNames}!`, channel.id);
    });

  })();

});

Bot每次上線的時候都會發送訊息給全部頻道的人。

1 則留言:

  1. You should see how my pal Wesley Virgin's story begins in this shocking and controversial VIDEO.

    You see, Wesley was in the army-and soon after leaving-he unveiled hidden, "mind control" secrets that the CIA and others used to get whatever they want.

    THESE are the EXACT same tactics lots of celebrities (notably those who "come out of nothing") and elite business people used to become wealthy and successful.

    You've heard that you use less than 10% of your brain.

    That's really because most of your brainpower is UNTAPPED.

    Maybe this conversation has even occurred IN YOUR own head... as it did in my good friend Wesley Virgin's head about 7 years ago, while driving an unlicensed, trash bucket of a car with a suspended license and $3.20 on his banking card.

    "I'm very frustrated with going through life paycheck to paycheck! When will I get my big break?"

    You took part in those questions, ain't it so?

    Your success story is going to happen. Go and take a leap of faith in YOURSELF.

    UNLOCK YOUR SECRET BRAINPOWER

    回覆刪除