[Slack api + Python] I tried to summarize the methods such as status confirmation and message sending

The requests to be handled are as follows.

-chat.postMessage (Official Document) -users.profile.set (Official Document) -users.setPresence (Official Document) -users.getPresence (Official Document) -users.list (Official Document)

You can also refer to other requests in the Official Documents.

Assumptions, environment

Create Class Slack Functions.

** Two types of OAuth tokens ** slackapi->YourApp -> Install app When you open, you will find two tokens.

The tokens required differ depending on the type of request, so I wanted to be able to simplify that as well.

The location to define is arbitrary, but this time I stored it in ".env".

.env


SLACK_OAUTH_TOKEN='xoxp-{YOUR_TOKEN}'
SLACK_USER_TOKEN='xoxb-{YOUR_TOKEN}'

You need to import ** dotenv ** when using it in a python file.

slackapi_functions.py


from dotenv import load_dotenv
import os

load_dotenv()

slack_oauth_token = os.environ['SLACK_OAUTH_TOKEN']
slack_user_token = os.environ['SLACK_USER_TOKEN']

Also import to use slackapi!

slackapi_functions.py


import requests #To send a request
import json #Receive the response as Json.
from slack import WebClient #Slackapi Web Client

Class Slack Functions Initialization

slackapi_functions.py


class SlackFunctions:
    def __init__(self):
        self._headers = {'Content-Type': 'application/json'}

chat.postMessage

slackapi_functions.py


def post_message(self, channel, message):
        params = {"token": slack_user_token,
                  "channel": channel, "text": message}

        r = requests.post('https://slack.com/api/chat.postMessage',
                          headers=self._headers, params=params)

This is a request to send a message. Send to \ # general → post_message (" # general "," hello! ")` ` Send to user by DM → post_message ("{USERS_ID} "," Wake UP! ")` ``

users.profile.set

slackapi_functions.py


def profile_set(self, text, emoji):
        params = {
            "token": slack_oauth_token,
            "profile": json.dumps({
                "status_text": text,
                "status_emoji": emoji
            })
        }

        r = requests.post('https://slack.com/api/users.profile.set', 
                          params=params)

A request to set custom status text and emoji. Since there are status_text and status_emoji in the variable called profile, you can use it as it is when setting only those two.

users.setPresence

slackapi_functions.py


def set_presence(self, status): # statue: 'away' OR 'auto'
        params = {
            "token": slack_user_token,
            "presence": status
        }

        r = requests.post('https://slack.com/api/users.setPresence', 
            params=params)

This is a request as to whether it is actually active or away. You can force it to be away``, but you cannot force it to be` `active. So the only argument to presence is `" away "``` or `" auto "```.

users.getPresence

slackapi_functions.py


def get_presence(self, user):
        params = {"token": slack_user_token, "user":user}
        r = requests.post('https://slack.com/api/users.getPresence',
                          headers=self._headers, params=params)
        return r.json()

A request that returns the user's status (active or away). I wanted to use the status that came back, so I gave it a return price.

users.list

slackapi_functions.py


def users_list(self):
        params = {"token": slack_user_token}
        r = requests.post('	https://slack.com/api/users.list',
                          headers=self._headers, params=params)

        return r.json()

It is a request to return information of all users (including BOT and plug-in application) in workspace. Since there is a lot of information, I made it a function that returns after processing the response.

def users_list(self):
        params = {"token": slack_user_token}
        r = requests.post('	https://slack.com/api/users.list',
                          headers=self._headers, params=params)

        rjson = r.json()

        id_list = []
        name_list = []
        for i in range(0, len(rjson["members"])):
            id_list.append(rjson["members"][i]["id"])
            name_list.append(rjson["members"][i]["profile"]["display_name"])
        return id_list, name_list

How to use

First, import `` `slackapi_functions.py```

your_slackapp.py


import slackapi_functions
SF = slackapi_functions.SlackFunctions()

After that, you can use it with the Class name and Function name!

your_slackapp.py


SF.post_message("#international-team", "Hello, this is your app!")
SF.change_status_message("I am focused!", :computer:)
SF.set_presence('away')
user_status = SF.get_presence(YOUR_ID)
accounts_info = SF.users_list()

Recommended Posts

[Slack api + Python] I tried to summarize the methods such as status confirmation and message sending
I tried to summarize the string operations of Python
[First COTOHA API] I tried to summarize the old story
I tried to implement the mail sending function in Python
I tried to enumerate the differences between java and python
[Linux] I tried to summarize the command of resource confirmation system
[Updated as appropriate] I tried to organize the basic visualization methods
I tried to summarize everyone's remarks on slack with wordcloud (Python)
[Qiita API] [Statistics • Machine learning] I tried to summarize and analyze the articles posted so far.
I tried to summarize Python exception handling
Python3 standard input I tried to summarize
I tried to summarize the graphical modeling.
I tried to touch the COTOHA API
[Python] I tried to summarize the set type (set) in an easy-to-understand manner.
I tried to summarize until I quit the bank and became an engineer
I tried to get the authentication code of Qiita API with Python.
I tried to summarize various sentences using the automatic summarization API "summpy"
I tried to verify and analyze the acceleration of Python by Cython
I tried to get the movie information of TMDb API with Python
I tried to touch the API of ebay
LeetCode I tried to summarize the simple ones
[Python] Throw a message to the slack channel
I tried to automate internal operations with Docker, Python and Twitter API + bonus
[Python] I tried to get the type name as a string from the type function
I tried to summarize how to use matplotlib of python
I tried to notify the update of "Become a novelist" using "IFTTT" and "Become a novelist API"
I tried to summarize the basic form of GPLVM
I tried to touch the CSV file with Python
I tried to solve the soma cube with python
I tried to automate the article update of Livedoor blog with Python and selenium.
I tried to score the syntax that was too humorous and humorous using the COTOHA API.
I tried to summarize four neural network optimization methods
[Python] I tried to graph the top 10 eyeshadow rankings
I tried to summarize how to use pandas in python
At this time, I tried various Python virtual environments such as Anaconda and pyenv.
I tried to solve the problem with Python Vol.1
I tried to compare the processing speed with dplyr of R and pandas of Python
[Python] I tried to summarize the array, dictionary generation method, loop method, list comprehension notation
I tried hitting the API with echonest's python client
I tried to automatically post to ChatWork at the time of deployment with fabric and ChatWork Api
I tried to summarize what python strong people are doing in the competition professional neighborhood
I tried to create a RESTful API by connecting the explosive Python framework FastAPI to MySQL.
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
I also tried to imitate the function monad and State monad with a generator in Python
I tried to find the entropy of the image with python
I tried to simulate how the infection spreads with Python
I tried to create API list.csv in Python from swagger.yaml
I tried various methods to send Japanese mail with Python
I tried follow management with Twitter API and Python (easy)
I tried to summarize the code often used in Pandas
I tried to illustrate the time and time in C language
I tried programming the chi-square test in Python and Java.
I tried to display the time and today's weather w
[Python] I tried to visualize the follow relationship of Twitter
I tried to summarize the commands often used in business
[Machine learning] I tried to summarize the theory of Adaboost
I want to know the features of Python and pip
[Python] I tried collecting data using the API of wikipedia
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried changing the python script from 2.7.11 to 3.6.0 on windows10
I tried to divide the file into folders with Python