[PYTHON] Easy with Slack using Bot #NowPlaying

This article is the 17th day article of Fujitsu Cloud Technologies Advent Calendar 2019. Yesterday was @heriet's "textlint PowerPoint (pptx)".

I'm not a technical person but a planning person, so I have a lot of opportunities to make PowerPoint. I'm interested because there are quite a lot of opportunities to be pointed out that the notation fluctuates.

Introduction

By the way, my name is Sasaki. I am usually in charge of planning Nifkura mobile backend.

Do you listen to music at work? I think that there are people who do not listen, and people who cannot actually listen because of the work environment and many telephone calls. Since our company is a company centered on engineers, there are many people who work while wearing headphones and earphones, and I think that there are probably more people who work while listening to music than the general public. .. Today is such a story about music at work.

#NowPlaying

Do you know the hashtag #NowPlaying that is often used on Twitter? This is a hashtag that means "I'm listening to this song right now", which is often used by music lovers and I sometimes use it. There are also some apps that support #NowPlaying posts, such as tweeting song titles / artists with the touch of a button, making it very easy to tweet.

On our Slack, there's a channel just for posting this #NowPlaying, where in-house music lovers get together to post songs they listen to every day at work. (If you come across a situation where someone is listening to a song you like very much, emoji's reaction will quietly play.)

However, there is no app that supports posting like Twitter, and I type the song name / artist name by hand. (Especially, my favorite band called THEE MICHELLE GUN ELEPHANT is really long, so it's going to be ...)

So I decided to make a bot that would automate this task.

Bot flow and configuration

I'm listening to music using Spotify, so I decided to make a bot with the following flow.

Send a reply to Bot → Get the song that Spotify is playing via API → Post the song name and artist name from the acquisition result

The bot runs on Python and uses the following packages:

By the way, as a non-engineer, I tried a lot of unreasonable things, such as looking at the API reference and trying to implement everything with JavaScript (and front end), but I helped my senior engineer. I was taught this composition. Thanks!

How to make

Then, I will explain how to make it. In addition, please set the Bots integration of Slack in advance and make a note of the API token.

Spotify settings

First, follow the steps below to issue the client ID and client secret on Spotify.

  1. Go to here and log in with your Spotify account from "LOG IN"
  2. Click "CREATE AN APP"
  3. About 3 questions will be asked, but enter or select "App / Hardware name", "Summary" and "Creation type" from the top, and click "Next".
  4. Is it for commercial use? A question like this will appear, so click "No"
  5. After agreeing and checking, click "SUBMIT"
  6. As the creation is completed, click "SHOW CLIENT SECRET" and make a note of the client secret that appears and the client ID above it. * Be careful not to leak this key.
  7. Click "EDIT SETTINGS" in the upper right
  8. Enter "http : // localhost: 8888 / callback" in Redirect URIs, click "ADD", then click "SAVE"

Server development

Package introduction

First, introduce slackbot.

$ pip3 install slackbot

Next, we will introduce spotipy.

$  pip install spotipy

Organize directories / create files

Create a project folder somewhere and work in it. Create directories / files so that the hierarchy is as follows.

Project folder
  ├ plugins/
  │    ├ __init__.py
  │    └ my_mention.py
  ├ run.py
  └ slackbot_settings.py

Edit run.py

Open run.py and write the execution script. Run this script when launching the bot.

run.py


# coding: utf-8

from slackbot.bot import Bot

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

if __name__ == "__main__":
    print('slackbot has started')
    main()

Editing slackbot_settings.py

Next, edit the configuration file. Please replace the "API token of Slack's bots integration" with the API token of the bot created on the Slack side.

slackbot_settings.py


# coding: utf-8

API_TOKEN = "API token for Slack's Bots integration"

DEFAULT_REPLY = "This is an unexpected command."

PLUGINS = ['plugins']

my_mention.py

Now, let's make a reply. Replace your Spotify username / client ID / client secret / Slack username. You can find your Spotify user name by visiting here. You can find the confirmation method for your Slack user ID at here.

my_mention.py


import spotipy
import spotipy.util as util
from slackbot.bot import respond_to

@respond_to('NP')
@respond_to('np')
def mention_func(message):
    scope = 'user-read-currently-playing'

    token = util.prompt_for_user_token(username="Spotify username", scope, client_id="Client ID", client_secret="Client secret", redirect_uri="http://localhost:8888/callback")

    spotify = spotipy.Spotify(auth=token)
    current_track = spotify.current_user_playing_track()

    if message.body['user'] == 'Slack user ID':
        if type(current_track) == dict:
            message.send(current_track['item']['name'] + ' - ' + current_track['item']['artists'][0]['name'])
        else:
            message.send('I'm not playing anything')
    else:
        message.send('Who are you?')

Run!

That's all there is to it. Let's do it.

$ python run.py

After that, if you invite to any channel and mention @bot name np, the browser will be launched and you will be asked to authenticate for the first time. After authentication, the screen will transition to a blank screen, so copy the URL of the transition destination and paste it into the terminal.

slack.jpg

By the way, even if another person skips the mention, "Who are you?" Will be replied.

in conclusion

That's why it's now easy to post songs you're listening to on Spotify to Slack.

However, now that the server running the bot requires authentication, and I haven't been able to store the credentials of multiple people, it's only for me. I want to make it usable by various people, so I would like to continue to repair it!

Tomorrow, @aokuma will say, "I want to use Kubernetes in a nice way even with Nifukura!" I'm looking forward to it!

Have a nice Christmas.

Recommended Posts

Easy with Slack using Bot #NowPlaying
Develop slack bot in python using chat.postMessage
Easy Grad-CAM with pytorch-gradcam
Automatic JIRA ticket creation with slack bot ~ slack bot development with python ① ~
Easy way to scrape with python using Google Colab
[Super easy] Let's make a LINE BOT with Python.
Easy debugging with ipdb
Easy TopView with OpenCV
Create a slack bot
When using optparse with iPython
Easy tox environment with Jenkins
Try using PythonTex with Texpad.
Using Graphviz with Jupyter Notebook
[S3] CRUD with S3 using Python [Python]
[Co-occurrence analysis] Easy co-occurrence analysis with Python! [Python]
Lunch invitation bot on Slack
using golang slack editing C2
Using Quaternion with Python ~ numpy-quaternion ~
Try using matplotlib with PyCharm
Games using IMU with SenseHat
Post to slack with Python 3
[Python] Using OpenCV with Python (Basic)
Easy to make with syntax
Easy image classification with TensorFlow
Easy web scraping with Scrapy
Using a printer with Debian 10
Easy HTTP server with Python
Easy proxy login with django-hijack
Try using folium with anaconda
Using OpenCV with Python @Mac
Make Slack chatbot with Errbot
Send using Python with Gmail
I tried using Slack emojinator