[Python automation] Emoji Slack user icons [SlackAPI]

What I made

I wrote a script that emojis Slack user icons. ↓ Like this, the user's icon can be used as it is for reaction. (** It's convenient to know at a glance who reacted ?? **)

スクリーンショット 2019-11-10 12.41.48.png

If you want to use it quickly, please see the repository. https://github.com/KoseiYoshida/slack_usericon_to_emoji

From now on, I will explain the contents of the script.

Even if you don't look at the explanation, you can see what you are doing by looking at the repository. However, since I made it with great effort, I wrote a commentary article on the script that also serves as my own output.

Assumed reader

Development environment

Please note that the code in this article is abbreviated for explanation **. If you want to see the code that works, please see the repository.

Workflow

  1. Get a Token to access the Slack API
  2. Get user information via API
  3. Download the icon image of all users
  4. Upload the downloaded images at once

1. Get Token

Here, we will acquire the Token required to acquire Slack user information. If you have experience in acquiring Token, you can just look at the OAuthScope registration written at the bottom.

I referred to this article for how to get Token for Slack API. About Slack API Recommended Token

Now, let's actually get the Token.

There are two types of Slack API, recommended Token and legacy Token. In this article, we will proceed with the recommended Token. Legacy Tokens, which are easy to obtain, are fine for those who are troublesome.

For the basic method, see "How to get a Token with GUI" in the link above. After selecting the app name and the workspace to add and creating App, we will add Scope.

スクリーンショット 2019-11-10 13.01.30.png (Permissions is checked in the image, but nothing in the initial state)

If all goes well, you should see something like the one below. スクリーンショット 2019-11-10 13.01.21.png

Now that the settings are complete, press the InstallAppToWorkspace button on the Permission screen. If you follow the instructions and the installation is successful, you should see an OAuthAcessToken!

Now that the Token has been created, we will access the user information.

2. Acquisition of user information

Here, I would like to access the user information using the Token obtained earlier and obtain the URL of the icon image.

When getting user information https://slack.com/api/users.list?token=<token acquired> It seems that you should make a GET request to. By the way, I get it in the form of json and make it easy to handle.

USERLIST_GETURL_BASE = 'https://slack.com/api/users.list?token='
TOKEN = <Obtained token>

def get_userslist_json():
    #Specify header so that it can be obtained in json format
    headers = {'content-type': 'application/json'}
    res = requests.get(USERLIST_GETURL_BASE + TOKEN, headers)
    users_list = res.json()
    #The actual data is'members'It is in. So throw away the rest
    users_list = users_list['members']
    return users_list

The only item you need in the response is'members', so let's throw away the others.

In the acquired list, one element is information (dictionary type) for one user. ↓ Information for one user. It is a dictionary type and various items are lined up.

{'id': 'UQ412C941',
  'team_id': 'TBASP22UV',
  'name': 'koseiasengineer',
  'deleted': False,
  'color': 'e7392d',
  'real_name': 'Pig',
  'tz': 'Asia/Tokyo',
  'tz_label': 'Japan Standard Time',
  'tz_offset': 32400,
  'profile': {'title': '',
   'phone': '',
   'skype': '',
   'real_name': 'Pig',
   'real_name_normalized': 'Pig',
   'display_name': 'Pig Taro',
   'display_name_normalized': 'Pig Taro',
   'status_text': '',
   'status_emoji': '',
   'status_expiration': 0,
   'avatar_hash': '1b04567a2fd5',
   'image_original': 'https://avatars.slack-edge.com/2019-11-09/815178912706_1b04567a2fd5434e2659_original.png',
   'is_custom_image': True,
   'first_name': 'Pig',
   'last_name': '',
   'image_24': 'https://avatars.slack-edge.com/2019-11-09/815178912706_1b04567a2fd5434e2659_24.png',
   'image_32': 'https://avatars.slack-edge.com/2019-11-09/815178912706_1b04567a2fd5434e2659_32.png',
   'image_48': 'https://avatars.slack-edge.com/2019-11-09/815178912706_1b04567a2fd5434e2659_48.png',
   'image_72': 'https://avatars.slack-edge.com/2019-11-09/815178912706_1b04567a2fd5434e2659_72.png',
   'image_192': 'https://avatars.slack-edge.com/2019-11-09/815178912706_1b04567a2fd5434e2659_192.png',
   'image_512': 'https://avatars.slack-edge.com/2019-11-09/815178912706_1b04567a2fd5434e2659_512.png',
   'image_1024': 'https://avatars.slack-edge.com/2019-11-09/815178912706_1b04567a2fd5434e2659_1024.png',
   'status_text_canonical': '',
   'team': 'TBASP22UV'},
  'is_admin': False,
  'is_owner': False,
  'is_primary_owner': False,
  'is_restricted': False,
  'is_ultra_restricted': False,
  'is_bot': False,
  'is_app_user': False,
  'updated': 1573257843,
  'has_2fa': False}

** It seems that the icon image is placed in'image_original','image_ '. ** ** It seems that there are various names, but ** the name that you usually see as a Slack user is in'display_name' **.

real_name

Now that I know where the icon image is, I will download it.

3. Download user icon

I found out the location of the icon image from the user information obtained via SlackPI, so I will download it. It is assumed that the saved name of the image = the name of Emoji.

Basically, you just get the image and save it, but there is a problem.

So, we will solve these problems.

Repel bots and users who belonged to the past

Looking at the user information obtained earlier, items such as'is_bot'and'is_deleted' are prepared. Use these items to repel.


#It is assumed that the argument member will contain one user's information (dictionary type).
def is_target_member(member):

    if member['is_bot']:
        return False

    #The SlackBot that participates by default'is_bot'Is False for some reason, so it is rejected by name
    if member['name'] == 'slackbot':
        return False

   if member['deleted'] == 'True':
        return False

    return True

For some reason, the'is_bot'flag of SlackBot, which is from the beginning when Workspace is created, is False, so it is forcibly repelled by name.

Romaji Japanese

It seems that Japanese (Kanji, Katakana, Hiragana) can be converted to Romaji with a package called "pykakasi". (Reference, Installation and use of the pykakasi module that converts Japanese characters to Romaji) By the way, I also put in "mojimoji" which converts full-width-> half-width.

$ pip install git+https://github.com/miurahr/pykakasi
$ pip install mojimoji

It will be romanized like this.

from pykakashi import kakashi
import mojimoji

def fix_name_style(name):
        
    jpn2romaji = kakasi()
    jpn2romaji.setMode('J', 'a')
    jpn2romaji.setMode('K', 'a')
    jpn2romaji.setMode('H', 'a')
    k2r_conv = jpn2romaji.getConverter()
    fixed_name = k2r_conv.do(name)

    fixed_name = mojimoji.zen_to_han(fixed_name)

    #Dots and spaces will lead to errors, so delete them
    fixed_name = fixed_name.replace(".", "")
    fixed_name = fixed_name.replace(' ', '')

    return fixed_name

Download summary

Now that the problem has been resolved, it's time to download it. I wrote a function for downloading images, and the whole picture looks like this. (↓ is the code to get a grasp of the processing flow. Please see the repository for the one that works properly.)


def download_file(self, url, dst_path):
    with urllib.request.urlopen(url) as web_file, open(dst_path, 'wb') as local_file:
        local_file.write(web_file.read())

save_directory_name = 'temp' #Any name is fine
members_list = get_userslist_json()

for member in members_list:
    #Repel bots and unsubscribed users
    if not is_target_member(member):
        continue

    member_prof = member['profile']

    name = member_prof['display_name'].lower()
    name = fix_name_style(name)

    # 'image_original'Contains the url of the icon image
    image_url = member_prof['image_original']
    _, ext = os.path.splitext(image_url)

    saved_file_path = './' + save_directory_name + os.sep + name + ext
    download_file(image_url, saved_file_path)

4. Add emoji

To add the saved image as an emoji, please use this "slack-emojinator". https://github.com/smashwilson/slack-emojinator I think it's okay if you follow the instructions in README.md. (If you like the explanation in Japanese, here I tried using Slack emojinator)

By the way, the addition of emoji by "slack-emojinator", Since the Slack API does not have an API for adding emoji, it seems that Session is forcibly created using cookies.

"slack-emojinator" is used by calling it from the command line. If you want to do everything from image download to upload automatically, please refer to the following repository. https://github.com/KoseiYoshida/slack_usericon_to_emoji

Summary

Get Slack user icon-> Automated emoji conversion in Python. You can easily execute it by cloning the repository, so please use it.

Sorry for the dirty code because I'm new to Python and APIs. Masakari is welcome.

Recommended Posts

[Python automation] Emoji Slack user icons [SlackAPI]
UI Automation in Python
Slack chatbot creation Python