After studying Python3, I made a Slackbot

Introduction

As the title says, I made a bot for Slack after studying Python. Since other people have written in the article, it will be a level to leave in my own memorandum. It doesn't describe how to register Slack and how to use Heroku until you start using Bot. Since the source code is posted, please point out any mistakes in the way of writing the source code.

specification

Using the Gurunavi API, enter a search word in slack and return the hit URL. If you type "rice Shinagawa yakitori", the URL of a restaurant that looks like a yakitori restaurant in Shinagawa will be returned.

Environment etc.

Constitution

slackbot/  ├ plugins/  │ └ slackbot_restapi.py  │ └ restapi.py  │ └ gnaviapi.py  │   └ run.py  └ slackbot_settings.py └ Procfile (File for Heroku) └ runtime.txt (File for Heroku)

Implementation

run.py and slackbot_settings.py

run.py


"""Slack Bot Program."""
# coding: utf-8

from slackbot.bot import Bot

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

if __name__ == '__main__':
    main()

slackbot_settings.py


"""
Configuration file for slackbot
"""
API_TOKEN = 'YOUR_API_TOKEN'

DEFAULT_REPLY = 'What are you talking about?'

PLUGINS = ['plugins']

As written in here. Run run.py and Slackbot will start working.

slackbot_restapi.py

plugins/slackbot_restapi.py


"""
Plugin Program
"""
from requests.exceptions import RequestException
from slackbot.bot import listen_to
from plugins.gnaviapi import GnaviApi

@listen_to('rice')
def search_restraunt(message):
    """
Search Gurunavi based on the received message and return the URL
    """
    gnavi = GnaviApi('https://api.gnavi.co.jp/RestSearchAPI/20150630/')
    key = 'YOUR_API_KEY'

    search_word = message.body['text'].split()

    if len(search_word) == 3:
        params = {
            'keyid': key,
            'format': 'json',
            'address': search_word[1],
            'freeword': search_word[2]
        }
        try:
            gnavi.api_request(params)
            for rest_url in gnavi.url_list():
                message.send(rest_url)
        except RequestException:
            message.send('I didn't get into Gurunavi, so look for it again later ...( ´Д`)y━ ・~~')
            return
        except Exception as other:
            message.send(''.join(other.args))
            return
    else:
        message.send('↓ I want you to search like this ...( ̄Д ̄)No')
        message.send('Rice place keyword (characters are separated by spaces)')
        message.send('Example) Rice Shinagawa Yakitori')

It picks up and processes the content typed in Slack. The subtle addiction here was that I didn't know how to pick up the Message entered in Slack. After a little research,

message.body['text']

I found that I can get it with. Split the picked up message with split () and use the location and freeword as API parameters.

restapi.py and gnaviapi.py

I made it by studying Python classes and inheritance. In restapi.py, it is a class that just throws a Request and takes a Response. gnaviapi.py adds a method that creates and returns a list of URLs only from Response. List comprehension is convenient, isn't it? It was something fresh.

plugins/restapi.py


"""
REST API CLASS
"""
# -*- coding: utf-8 -*-
import requests
from requests.exceptions import RequestException

class RestApi():
    """
    REST API CLASS
    """
    def __init__(self, url):
        self.url = url
        self.response_data = None

    def api_request(self, search_dict):
        """
API call
        """
        try:
            self.response_data = requests.get(self.url, params=search_dict)
        except RequestException:
            raise Exception('API access failed')

plugins/gnaviapi.py


"""
Gurunavi API
"""
# -*- coding: utf-8 -*-
from plugins.restapi import RestApi

class GnaviApi(RestApi):
    """
Gurunavi API class
    """
    def __init__(self, url):
        super().__init__(url)

    def url_list(self):
        """
Create a list of restaurant URLs from Response and return it.
        """
        json_data = self.response_data.json()
        if 'error' in json_data:
            raise Exception('I couldn't find it with that keyword ...(´ ・ ω ・ `)')

        return [rest_data['url'] for rest_data in json_data['rest']]

Execution result

It is like this.

スクリーンショット 2017-05-16 1.45.09.png

At the end

It seems easy to extend so that you can search with other APIs such as ATND and dots. I think I spent more time struggling to use Heroku than implementing it in python.

Recommended Posts

After studying Python3, I made a Slackbot
I made a python text
Continuation ・ I tried to make Slackbot after studying Python3
I made a Line-bot using Python!
I made a fortune with Python.
I made a daemon with Python
I made a payroll program in Python!
I made a Hex map with Python
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a neuron simulator with Python
〇✕ I made a game
I made a python dictionary file for Neocomplete
I made a competitive programming glossary with Python
I made a weather forecast bot-like with Python.
I made a GUI application with Python + PyQt5
I made a Twitter fujoshi blocker with Python ①
[Python] I made a Youtube Downloader with Tkinter.
I made a Caesar cryptographic program in Python.
I made a bin picking game with Python
I made a Mattermost bot with Python (+ Flask)
I made a Python Qiita API wrapper "qiipy"
I made a Twitter BOT with GAE (python) (with a reference)
I made a login / logout process using Python Bottle.
I made a Christmas tree lighting game with Python
I made blackjack with python!
I made a net news notification app with Python
I made a VM that runs OpenCV for Python
I made a Python module to translate comment outs
I made a Python3 environment on Ubuntu with direnv.
I made a LINE BOT with Python and Heroku
[Python] I made a classifier for irises [Machine learning]
I made a prime number generation program in Python 2
I made a python library to do rolling rank
I made a discord bot
I made blackjack with Python.
I made wordcloud with Python.
I implemented a Vim-like replacement command in Slackbot #Python
I made a simple typing game with tkinter in Python
I made a package to filter time series with python
[VSCode] I made a user snippet for Python print f-string
I made a quick feed reader using feedparser in Python
I made a simple book application with python + Flask ~ Introduction ~
I made a puzzle game (like) with Tkinter in Python
I made a Chatbot using LINE Messaging API and Python
I made a C ++ learning site
I made a CUI-based translation script (2)
I made a wikipedia gacha bot
I made my own Python library
I made a CUI-based translation script
[Python] Generate a password with Slackbot
[Python] I made a Line bot that randomly asks English words.
I made a simple circuit with Python (AND, OR, NOR, etc.)
I made a library to easily read config files with Python
Studying python
I made a package that can compare morphological analyzers with Python
Python> I made a test code for my own external file
I made a Nyanko tweet form with Python, Flask and Heroku
I made a lot of files for RDP connection with Python
[Python] I made an image viewer with a simple sorting function.