在原本的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每次上線的時候都會發送訊息給全部頻道的人。










