The story of creating a bot that displays active members in a specific channel of slack with python

Introduction

Use slack's API to display active members in a specific channel of slack in python by skipping specific mentions on slackbot.

Execution result スクリーンショット 2019-12-22 16.31.44.png

It is like this. Since it contains personal information, I hide some of it. Let's do it! !!

Directory structure

├───.gitignore                                 
├───.env                                
├───requirements.txt             
├───Procfile           
│───plugins
│   └───my_mention.py                          #This file is mainly used.
│    └───__init__.py
│───run.py                  
│───settings.py           
│───slackbot_settings.py
└───README.md                      

code

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 = 'Let's decide the members!'
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

Summary

It's pretty easy to do. Let's make effective use of slackbot! !!

Recommended Posts

The story of creating a bot that displays active members in a specific channel of slack with python
The story of creating Botonyan that returns the contents of Google Docs in response to a specific keyword on Slack
The story of making a module that skips mail with python
The story of making a university 100 yen breakfast LINE bot with Python
Create a BOT that displays the number of infected people in the new corona
[Python] Leave only the elements that start with a specific character string in the array
Get the number of specific elements in a python list
The story of making a question box bot with discord.py
A story that struggled to handle the Python package of PocketSphinx
The story of making a standard driver for db with python.
A function that measures the processing time of a method in python
The story of creating a site that lists the release dates of books
I made a slack bot that notifies me of the temperature
A story that didn't work when I tried to log in with the Python requests module
The story of blackjack A processing (python)
A story that visualizes the present of Qiita with Qiita API + Elasticsearch + Kibana
The story of a Parking Sensor in 10 minutes with GrovePi + Starter Kit
Receive a list of the results of parallel processing in Python with starmap
The story of creating a store search BOT (AI LINE BOT) for Go To EAT in Chiba Prefecture (1)
Create a bot that posts the number of people positive for the new coronavirus in Tokyo to Slack
[Python] Get the files in a folder with Python
Make a copy of the list in Python
The story of reading HSPICE data in Python
The one that displays the progress bar in Python
[Python] Throw a message to the slack channel
The story that fits in with pip installation
A story that turned light blue in 4 months after starting AtCoder with python
Around the authentication of PyDrive2, a package that operates Google Drive with Python
The story of Django creating a library that might be a little more useful
The story of making a Line Bot that tells us the schedule of competitive programming
How to get a list of files in the same directory with python
The story of creating a store search BOT (AI LINE BOT) for Go To EAT in Chiba Prefecture (2) [Overview]
A story that reduces the effort of operation / maintenance
[Python] A program that counts the number of valleys
How to identify the element with the smallest number of characters in a Python list?
Introducing the book "Creating a profitable AI with Python" that allows you to learn machine learning in the shortest course
[Python] A program that finds the shortest number of steps in a game that crosses clouds
Make a BOT that shortens the URL of Discord
[Python] Change the text color and background color of a specific keyword in print output
A memo that implements the job of loading a GCS file into BigQuery in Python
The story of FileNotFound in Python open () mode ='w'
A story that struggled with the common set HTTP_PROXY = ~
A memo that I touched the Datastore with python
Lambda expression (correction) that creates an index (dictionary with members as keys) of the members of the object being collected in python
A story that analyzed the delivery of Nico Nama.
A story about trying to introduce Linter in the middle of a Python (Flask) project
A reminder about the implementation of recommendations in Python
[Python] A program that compares the positions of kangaroos.
Add a function to tell the weather of today to slack bot (made by python)
Now in Singapore The story of creating a LineBot and wanting to do a memorable job
A server that returns the number of people in front of the camera with bottle.py and OpenCV
Create a bot that only returns the result of morphological analysis with MeCab on Discord
The story of creating a "spirit and time chat room" exclusively for engineers in the company
Get the value of a specific key up to the specified index in the dictionary list in Python
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
Recursively get the Excel list in a specific folder with python and write it to Excel.
[Note] A shell script that checks the CPU usage of a specific process in a while loop.
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
[Python] Extracts data frames that do not match a specific column with other data frames of Pandas
Try scraping the data of COVID-19 in Tokyo with Python
Find out the apparent width of a string in python