[PYTHON] Tweet the weather forecast with a bot Part 2

Yes. Past articles http://qiita.com/clarinet758/items/0142e88cd19a4246f308

http://weather.service.msn.com/data.aspx?src=vista&weadegreetype=C&culture=ja-JP&wealocations=wc:
Unfortunately the update seems to have not updated the data since mid-November 2016. Somehow it causes the third, so the update will make the tea muddy. The new acquisition destination is OpenWeatherMap. I still used Python 2 series. It's spicy. Reference http://qiita.com/b-wind/items/06e19043a0cd70b10b03
http://qiita.com/nownabe/items/aeac1ce0977be963a740
http://qiita.com/sudnonk12/items/744fb48e378c05979952

If you read the above, I don't think you need to read anything in the future.

If you want a little information for Twitter, do you use one of the two? When,

  1. Current weather data The endpoint is ```api.openweathermap.org/data/2.5/weather? The following option `` `. Only one case in the state at the time of the latest update can be obtained. I think that this is used if the current weather is ~. This wasn't what I wanted this time, so that's it for here.
  2. 5 day / 3 hour forecast The endpoint is ```api.openweathermap.org/data/2.5/forecast ?? The following option `` `. It seems that you can get it for 5 days with 3 hour intervals. You can check the forecast for what month, day, and time with the value of dt_txt. In addition, I think that it is a part to worry about which time to refer to "tomorrow's weather" for the information of 3 hours.

Sample code

weather


#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import datetime
import oat
import time
import urllib2
import json


class Weather3:
    def __init__(self, api_key, hour, name, code, tag):
        self.api_key = api_key
        self.day = [u'today', u'tomorrow'][hour == **].encode('utf-8')
        self.name = name.encode('utf-8')
        self.code = code
        self.indx = [-1]*25
        self.indx[*] = *
        self.f = self.indx[hour]
        self.tag = tag

    def get_json(self):
        url = 'http://api.openweathermap.org/data/2.5/forecast?id={0:}&APPID={1:}'.format(self.code, self.api_key)
        o = urllib2.urlopen(url)
        r = o.read()
        j = json.loads(r)
        return j

    def get_info(self):
        ind = self.f
        data = self.get_json()
        base = data['list'][ind]
        tenki = base['weather'][0]['main']
        t_max = str('{0:.2f}'.format(base['main']['temp_max']-273.15))
        t_min = str('{0:.2f}'.format(base['main']['temp_min']-273.15))
        return (tenki, t_max, t_min)

    def make_txt(self):
        d = self.get_info()
        temp = "{0:}of{1:}ら辺of天候は{2:}is. The maximum temperature is{3:}At around degrees, the lowest temperature is{4:}About degree.#{5:}"
        text = temp.format(self.day, self.name, d[0], d[1], d[2], self.tag)
        return text

    def tweet(self):
        message = self.make_txt()
#        print message
        oat.tweet(message)

    def run(self):
        self.tweet()
        time.sleep(5)

if __name__ == '__main__':
    target = [[u'Shinagawa', 1852140], [u'Funabashi', '1863905'], [u'Kumamoto', '1858421'], [u'Uji', '1849372']]
    jikan = datetime.datetime.now()
    flag = jikan.hour
    tag = jikan.microsecond

    for i in target:
        w = Weather3(oat.api_key, flag, i[0], i[1], tag)
        w.run()

token


#!/usr/bin/python
# -*- coding:UTF-8 -*-

from urllib import urlencode
from oauth2 import Client, Consumer, Token
import tweepy

#Twitter
consumer_key = "xxxxxx"
consumer_secret = "xxxxxxxxxxx"
user_key = "*****-xxxxxxxxxx"
user_secret = "xxxxxxxxx"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(user_key, user_secret)
client = Client(Consumer(consumer_key, consumer_secret), Token(user_key, user_secret))
api = tweepy.API(auth)
ep = "https://api.twitter.com/1.1/statuses/update.json"

#OpenWeatherMap
api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

def tweet(message):
    client.request(ep, 'POST', urlencode({'status': message}))


def reply(message, ids):
    client.request(ep, 'POST', urlencode({'status': message, 'in_reply_to_status_id': ids}))

Depending on the time you move, the weather tomorrow today and the number of information you use in the acquired information will vary depending on how you use it. In addition, I wrote -273.15 to convert the temperature from Kelvin to Celsius, but it seems that it will be returned in Celsius if you turn on the option when you hit the endpoint. Twitter post sample image http://www.nowshika.com/joso/img11110131.png

Recommended Posts

Tweet the weather forecast with a bot Part 2
Notification of weather forecast (rain, etc.) by DM as a part of the function of bot
I made a weather forecast bot-like with Python.
View today's weather forecast with a shell script
Draw a graph with PyQtGraph Part 5-Increase the Y-axis
Create a tweet heatmap with the Google Maps API
Tweet the probability of precipitation as part of the function of the bot
Scraping weather forecast with python
[Part 4] Use Deep Learning to forecast the weather from weather images
[Part 1] Use Deep Learning to forecast the weather from weather images
[Part 3] Use Deep Learning to forecast the weather from weather images
Create a Twitter BOT with the GoogleAppEngine SDK for Python
[Python] I asked LINE BOT to answer the weather forecast.
[Part 2] Use Deep Learning to forecast the weather from weather images
The story of making a question box bot with discord.py
Play with a turtle with turtle graphics (Part 1)
Get the weather with Python requests
Get the weather with Python requests 2
I liked the tweet with python. ..
[LINE bot] I'm a ranger! Part 2
I want to know the weather with LINE bot feat.Heroku + Python
Find the optimal value of a function with a genetic algorithm (Part 2)
Count the maximum concatenated part of a random graph with NetworkX
Create a Twitter BOT service with GAE / P + Tweepy + RIOT API! (Part 1)
Create a Twitter BOT service with GAE / P + Tweepy + RIOT API! (Part 2)
Search the maze with the python A * algorithm
Deb package development with Git: (Part 1) Creating a stray package with the minimum configuration
Stock Price Forecast with TensorFlow (LSTM) ~ Stock Forecast Part 1 ~
Let's make a Twitter Bot with Python!
Draw a graph with PyQtGraph Part 1-Drawing
Make a thermometer with Raspberry Pi and make it visible on the browser Part 3
A model that identifies the guitar with fast.ai
I made a stamp substitute bot with line
Tweet regularly with the Go language Twitter API
[Python] Get the files in a folder with Python
Make a Twitter trend bot with heroku + Python
Find a position above the threshold with NumPy
Create a LINE BOT with Minette for Python
Draw a graph with PyQtGraph Part 3-PlotWidget settings
Follow the AR marker with a 2-axis servo
I made a LINE Bot with Serverless Framework!
Steps to create a Twitter bot with python
Draw a graph with PyQtGraph Part 4-PlotItem settings
Save the object to a file with pickle
Draw a graph with PyQtGraph Part 6-Displaying a legend
Make a LINE WORKS bot with Amazon Lex
Let's do web scraping with Python (weather forecast)
Create a translation tool with the Translate Toolkit
I made a Mattermost bot with Python (+ Flask)
I tried to make the weather forecast on the official line by referring to the weather forecast bot of "Dialogue system made with python".
Add a function to tell the weather of today to slack bot (made by python)
Stock Price Forecast with TensorFlow (Multilayer Perceptron: MLP) ~ Stock Forecast Part 2 ~
[AWS] I made a reminder BOT with LINE WORKS
I made a Twitter BOT with GAE (python) (with a reference)
Make a morphological analysis bot loosely with LINE + Flask
Cut a part of the string using a Python slice
How to create a submenu with the [Blender] plugin
Try to visualize the room with Raspberry Pi, part 1
Make a BOT that shortens the URL of Discord
Take a screenshot of the LCD with Python-LEGO Mindstorms
How to make a shooting game with toio (Part 1)