LoginSignup
0
0

More than 3 years have passed since last update.

今日の天気の下書きを書いた話

Last updated at Posted at 2020-06-18

前書き

GmailAPIを使って今日の天気を教える下書きを書いてみました。

開発環境

windows10
python3.7

使用するAPI

OpenWeatherMapApi
GmailAPI

OpenWeatherMapAPI

まずOpenWeatherMapAPIのAPIkeyを手に入れましょう。
OpenWeatherMapのAPIkeyを手に入れる

アカウントを作ったらこのようなページに飛ぶはずです。
image.png
そうしたら「API key」をクリックしてAPIkeyを取得しましょう。
image.png
このページになるので「Create key」に名前を付けて取得しましょう。

これでOpenWeatherMapAPIのkeyを手に入れした。
APIkeyは非常に大事なので絶対に公開しないでください。なくしてもいけません。

このAPIは現在の天気、気温などのデータを取得したり、五日後までの三時間ごとの予報を取得したりできます。
試しに現在の天気を取得しましょう。

weather_test.py
import requests
import json

class weather():
    def getweather(self,city):
        city_name = city 
        API_KEY = "xxx" # xxxにAPI Keyを入力。
        api = "http://api.openweathermap.org/data/2.5/weather?units=metric&q={city}&APPID={key}"

        url = api.format(city = city_name, key = API_KEY)

        response = requests.get(url)
        data = response.json()
        self.jsonText = json.dumps(data, indent=4)


    def collweather(self):
        return self.jsonText


city_now=str(input())
a=weather()
a.getweather(city_now)
print(a.collweather())

そうしたら実行してTokyoと入れてみましょう。

$python weather_test.py

Tokyo

結果はこうなります

{
    "coord": {
        "lon": 139.69,
        "lat": 35.69
    },
    "weather": [
        {
            "id": 803,
            "main": "Clouds",
            "description": "broken clouds",
            "icon": "04n"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 22.37,
        "feels_like": 23.94,
        "temp_min": 21.67,
        "temp_max": 22.78,
        "pressure": 1008,
        "humidity": 83
    },
    "visibility": 10000,
    "wind": {
        "speed": 2.6,
        "deg": 110
    },
    "clouds": {
        "all": 75
    },
    "dt": 1592407584,
    "sys": {
        "type": 1,
        "id": 8074,
        "country": "JP",
        "sunrise": 1592421912,
        "sunset": 1592474373
    },
    "timezone": 32400,
    "id": 1850144,
    "name": "Tokyo",
    "cod": 200
}

無事天気が出ましたね。他にも気温や風速も出ています。結構充実しているんですよ。

天気を取得できるようになったところで次はGmailAPIのkeyを手に入れましょう

GmailAPI

今度はGmailAPIのkeyを取得しましょう。
GmailAPIのkeyを手に入れる
手順に沿ってAPIkeyを取得しクイックスタートを行います。
quickstart.pyが実行出来たら次は下書きを書いていきましょう。

下書きを書く

では下書きを作るプログラムを作っていきましょう。

Gmail_test.py
from __future__ import print_function
import pickle
import os.path
import base64
import mimetypes

from email.mime.multipart import MIMEMultipart
from email.mime.text      import MIMEText
from email.mime.image     import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.utils          import formatdate
from apiclient import errors
from apiclient.errors import HttpError
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request



SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
class Gmail():
    def main(self):

        creds = None



        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)

        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials_.json', SCOPES)
                creds = flow.run_local_server(port=0)

            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        self.service = build('gmail', 'v1', credentials=creds)


        results = self.service.users().labels().list(userId='me').execute()
        labels = results.get('labels', [])

        if not labels:
            print('No labels found.')
        else:
            print('Labels:')
            for label in labels:
                print(label['name'])



    def create_message(self,sender, to, subject, message_text):
      """
      ここでGmailの下書きを作ります。
      to:自分のメールアドレス
      from:送信先のメールアドレス
      subject:題名
      message_text:本文
      """
      message = MIMEText(message_text)
      message['to'] = to
      message['from'] = sender
      message['subject'] = subject
      return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}



    def create_draft(self, user_id, message_body):


     """
     ここで下書きをアップロードします。送信はしません。
     message:自分のアドレス(meと置くことが多い)
     message_body:create_message()で作った下書き
     ※serviceはここでは引数から除外していますが、main()のserviceと同じなので問題ありません。
     """
      try:
        message = {'message': message_body}
        draft = self.service.users().drafts().create(userId=user_id, body=message).execute()

        print ('Draft id: %s\nDraft message: %s' % (draft['id'], draft['message']))

        return draft
      except errors.HttpError as error:
        print ('An error occurred: %s' % error)
        return None

#ここから下は試しに実行するとき用のもので必要はありません
a=Gmail()
a.main()
sender=input()
to=input()
subject=input()
message_text=input()
body=a.create_message(sender,to,subject,message_text)
a.create_draft(me,body)

公式サイトにも似たようなことが書かれていますがそのままquickstart.pyにコピペして実行するとエラーが出ることがあるのでここでは実際に出たエラーとその対策について解説します。

1.except errors.HttpError, error: でエラーが出た。
これはerrorを「errorとして」使うようにというようなエラー文が出るはずです。なのでerroras errorに直してください。

2.message = MIMEText(message_text)でエラーが出た。
これはquickstart.pyにMIMEに関するライブラリを書いていないからです。
上のimport MINI~を追加してください。
3.権限がありませんと言われた。
これはquickstart.pyにあらかじめ用意されている認証スコープが読み取り専用だからです。SCOPES = ['https://www.googleapis.com/auth/gmail.readonry']SCOPES = ['https://www.googleapis.com/auth/gmail.modify']に変更してください。

まぁざっとこんな感じだと思います。
ではさっそく実行してみましょう。

$python Gmail_test.py

(自分のメールアドレス)
(送信先のメールアドレス)
test
test

結果はこうなります

Labels:
CHAT
SENT
INBOX
IMPORTANT
TRASH
DRAFT
SPAM
CATEGORY_FORUMS
CATEGORY_UPDATES
CATEGORY_PERSONAL
CATEGORY_PROMOTIONS
CATEGORY_SOCIAL
STARRED
UNREAD

Draft id:xxx
Draft message: {'id': 'xxx', 'xxx': 'xxx', 'labelIds': ['DRAFT']}

これでGmailの下書きを作ることが出来ました。
image.png

下書きもできたのでその下書きに今日の天気も書いておきましょう。

総仕上げ

まずディレクトリを作ってその中に先程作ったweather_test.pyとGmail.pyを入れておきましょう。

weather_test.pyを少し手直しします。

weather_test.py
import requests
import json

class weather():
    def getweather(self,city):
        city_name = city 
        API_KEY = "xxx" 
        api = "http://api.openweathermap.org/data/2.5/weather?units=metric&q={city}&APPID={key}"

        url = api.format(city = city_name, key = API_KEY)

        response = requests.get(url)
        self.data = response.json()
        jsonText = json.dumps(self.data, indent=4)

    def collall(self):
        return self.data
    def collweather(self):
        return self.data['weather'][0]['main']
    def colltemp(self):
        return self.data['main']['temp']
    def collcity(self):
        return self.data['name']

では後はこの二つを使って今日の天気を知らせる下書きを書きましょう。

mail_test.py
from Gmail_test import Gmail
from weather_test import weather




mail=Gmail()
tweather=weather()
mail.main()
tweather.getweather(input())


subject='Today weather'

text=tweather.collcity()+'の天気は'+tweather.collweather()+'で気温は'+str(tweather.colltemp())+'です。'
today_mail=mail.create_message(input(),input(),subject,text)
user_id='me'
mail.create_draft( user_id, today_mail)

結構簡素に書けましたねw まぁ二つのクラスを取り入れればよかったので…
では実行しましょう。今回は東京都の天気を見てみます。

$python mail_test.py

Tokyo
(自分のメールアドレス)
(送信先のメールアドレス)

image.png

これで完成ですね!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0