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.
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.
slackbot/ ├ plugins/ │ └ slackbot_restapi.py │ └ restapi.py │ └ gnaviapi.py │ └ run.py └ slackbot_settings.py └ Procfile (File for Heroku) └ runtime.txt (File for Heroku)
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.
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']]
It is like this.
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