1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

KIT DeveloperAdvent Calendar 2019

Day 23

pythonでslackの特定チャンネル内にいるactiveメンバーを表示させるBotを作成した話

Posted at

はじめに

pythonでslackの特定チャンネル内にいるactiveメンバーをslackのAPIを用いて、slackbotに特定のメンションを飛ばして表示させます。

実行結果
スクリーンショット 2019-12-22 16.31.44.png

こんな感じです。個人情報含まれているので一部隠してます。
それではやっていきましょう!!

ディレクトリ構成

├───.gitignore                                 
├───.env                                
├───requirements.txt             
├───Procfile           
│───plugins
│   └───my_mention.py                          #このファイルを主に使用します。
│    └───__init__.py
│───run.py                  
│───settings.py           
│───slackbot_settings.py
└───README.md                      

コード

my_mention.py

from slackbot.bot import respond_to
import requests
import random
import sys
sys.path.append('..')

import settings
CHANNEL_ID = settings.CHANNEL_ID
SLACK_API_TOKEN = settings.SLACK_API_TOKEN

@respond_to('')
def main(message):
    url = 'https://slack.com/api/channels.info?token={0}&channel={1}&pretty=1'.format(SLACK_API_TOKEN, CHANNEL_ID)
    response = requests.get(url).json()
    channel_info = response["channel"]
    member_id = channel_info["members"]
    member_id_list = [id for id in member_id]
    name_active_dict = member(member_id_list)
    active_member = []

    for key, value in name_active_dict.items():
        if value == 'active':
            active_member.append(key)

    active_member = random.sample(active_member, len(active_member))
    member_text = ''

    for i, active_name in enumerate(active_member):
        member_text = member_text + '{} : {}\n'.format(i+1, active_name)
            
    message.reply(member_text)


def member(member_id_list):
    member_dict = {}
    user_list = []
    is_active_list = []

    for name_id in member_id_list:
        user_url = 'https://slack.com/api/users.info?token={0}&user={1}&pretty=1'.format(SLACK_API_TOKEN, name_id)
        active_user_url = 'https://slack.com/api/users.getPresence?token={0}&user={1}&pretty=1'.format(SLACK_API_TOKEN, name_id)

        user_response = requests.get(user_url).json()
        active_user_response = requests.get(active_user_url).json()

        user_list.append(user_name(user_response))
        is_active_list.append(is_active_user(active_user_response))

    for user, active in zip(user_list, is_active_list):
        member_dict[user] = active
    
    return member_dict


def user_name(user_response_json):
    user = user_response_json["user"]
    user_profile = user["profile"]
    name = user_profile["real_name"]
    return name


def is_active_user(active_user_response_json):
    is_active = active_user_response_json["presence"]
    return is_active

slackbot_settings.py

import settings

API_TOKEN = settings.API_TOKEN
DEFAULT_REPLY = 'メンバーを決めよう!'
PLUGINS = ['plugins']

settings.py

import os
from os.path import join, dirname
from dotenv import load_dotenv

dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)

SLACK_API_TOKEN = os.environ.get("SLACK_API_TOKEN")
API_TOKEN = os.environ.get('API_TOKEN')
CHANNEL_ID = os.environ.get('CHANNEL_ID')

run.py

from slackbot.bot import Bot

def main():
    bot = Bot()
    bot.run()

if __name__ == '__main__':
    main()

Procfile

worker: python run.py

runtime.txt

python-3.6.0

requirements.txt

slackbot==0.5.3

まとめ

結構簡単にできますね。皆さんもslackbot有効活用していきましょう!!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?