Create an account at http://openweathermap.org/ and get API_KEY on the api_keys screen.
The explanation of how to get the bot token is given in the slack api manual.
Reference URL: https://api.slack.com/bot-users
In this program, the latitude and longitude are specified and the temperature in the corresponding area is acquired.
In bot.py, the process of actually getting the temperature and tweeting it on the slack channel is described. Open Weather Map, slack token, etc. are set in settings.py.
norths_weather_bot
├── bot.py
└── settings.py
bot.py
#/usr/bin/env python2.7
#-*- coding: utf-8 -*-
import json
import urllib
import urllib2
import settings
class Weather(object):
"""
"""
def __init__(self):
"""
"""
params = {'appid' : settings.OPEN_WETHER_APP_ID,
'lat' : settings.OPEN_WETHER_LAT,
'lon' : settings.OPEN_WETHER_LON,
'units' : settings.OPEN_WETHER_UNITS,
}
params = urllib.urlencode(params)
response = urllib2.urlopen(settings.OPEN_WETHER_URL + '?' + params)
self.json = json.loads(response.read())
def get_temp(self):
"""
"""
return {'max' : self.json['main']['temp_max'],
'min' : self.json['main']['temp_min'],
'now' : self.json['main']['temp'], }
class Bot(object):
"""
"""
def __init__(self):
"""
"""
self.set_serif()
def set_serif(self, serif=''):
"""
"""
self.serif = serif
def speak(self):
"""
"""
params = {'token' : settings.SLACK_TOKEN,
'channel': settings.SLACK_CHANNEL,
'text' : self.serif,}
params = urllib.urlencode(params)
req = urllib2.Request(settings.SLACK_URL)
req.add_header('Content-Type', 'application/x-www-form-urlencoded')
req.add_data(params)
res = urllib2.urlopen(req)
body = res.read()
if __name__ == "__main__":
"""
entry point
"""
temp = Weather().get_temp()
bot = Bot()
bot.set_serif('Current temperature: {0}℃ ,Highest temperature: {1}℃ ,Lowest Temperature: {2}℃'.format(temp['now'], temp['max'], temp['min']))
bot.speak()
settings.py
#-*- coding: utf-8 -*-
OPEN_WETHER_URL = "" # API URL
OPEN_WETHER_APP_ID = "" # API KEY
OPEN_WETHER_LAT = "" #latitude
OPEN_WETHER_LON = "" #longitude
OPEN_WETHER_UNITS = "" #Specify whether it is Celsius or absolute temperature. In the case of metric, it is Celsius.
SLACK_URL = "" # URL
SLACK_TOKEN = "" #token
SLACK_CHANNEL = "" #The channel you want to post
https://bitbucket.org/ponsuke/norths_weather_bot
Recommended Posts