The mechanism that corresponds to Hubot's hubot-script is called a plugin in Errbot.
Here has third-party plugins, I'm going to make it because it's a big deal.
The plugin requires two files.
The plug file is a ** plugin metadata file **. It describes the Python version specification, the explanation when executing the help command, and so on.
A python module is a ** plugin entity **. Write the logic here.
hello.plug
[Core]
Name = Hello
Module = hello
[Python]
Version = 2+
[Documentation]
Description = Hello plugin
hello.py
# -*- coding:utf8 -*-
from __future__ import division, print_function, absolute_import
from errbot import BotPlugin, botcmd
class Hello(BotPlugin):
@botcmd
def hello(self, msg, args):
return 'Hello world!'
The entity class of plugin inherits from BotPlugin. It does various processing at the time of initialization, but I will omit it this time.
The name of the method decorated with the botcmd
decorator becomes the command as it is.
! hello
is the command as it is.The method that becomes the bot command requires two arguments.
If the method decorated to botcmd
returns a string, it will speak as it is.
It's easy and nice.
weather.py
# -*- coding:utf8 -*-
from __future__ import division, print_function, absolute_import
from errbot import BotPlugin, botcmd
import requests
from xml.etree import ElementTree
class Weather(BotPlugin):
WEATHER_HACK_AREA_URL = \
'http://weather.livedoor.com/forecast/rss/primary_area.xml'
WEATHER_HACK_API_URL = \
'http://weather.livedoor.com/forecast/webservice/json/v1?'
@botcmd
def weather(self, msg, args):
#Find the city specified in the argument
city_id = self.find_city_id(args)
if city_id is None:
return u'{}Is an unidentified area'.format(args)
resp = requests.get(
self.WEATHER_HACK_API_URL,
{'city': city_id}
)
wt_json = resp.json()
return u'{}: {}Is{}'.format(
wt_json['title'],
wt_json['forecasts'][0]['dateLabel'],
wt_json['forecasts'][0]['telop']
)
def find_city_id(self, city_name):
"""Find a city that returns the weather with Livedoor's API
"""
resp = requests.get(self.WEATHER_HACK_AREA_URL)
tree = ElementTree.fromstring(resp.content)
cities = {
elm.attrib['title']: elm.attrib['id']
for elm in tree.findall('.//city')
}
return cities.get(city_name, None)
At this point, args is roughly regarded as the city name and the weather is returned, "If you throw multiple cities by space division, divide them and return the weather of each city together." It is also possible. If you use ArgumentParser, you can handle arguments flexibly, so it seems that there are various possibilities.
Recommended Posts