slackのbotに天気を教えてもらう(Python on AWS Lambda + API Gateway)
slackのbotにAPIの定番ともいえる天気情報を教えてもらいました。
環境は手前味噌ですが「slackのbotをAWS Lambda(Python)+API Gatewayで構築」をご参照ください。
LivedoorのWeather Hack APIを使う
Open Weather MAP APIとか使ってたのですが、国内のサービスの方が日本の天気は精度が高そうでしたので。
その中でもキーとかいらない一番お手軽なAPIがLivedoorのWeather Hack APIでしたので使わせていただきました。
詳しい仕様は「お天気Webサービス仕様」をご確認ください。
投稿に「天気」が含まれている際に天気情報を見に行くようにしました。
city_idは公開されているXMLを見に行けば動的に出来ますがそんなに全国いらないので固定にしています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
import wikipedia import requests import json def lambda_handler(event, context): try: user_name = event['user_name'] text = event['text'] msg = user_name + 'さん ' if text == '': msg += 'はい!' elif text.find('おはよ') > -1: msg += 'おはようございます!' elif text.find('こんにちは') > -1: msg += 'こんにちは' elif text.find('疲') > -1 or text.find('お先') > -1: msg += 'お疲れさまでした!' elif text.find('って何') > -1: msg += wikipediaSearch(text) elif text.find('天気') > -1: msg += getWeatherInformation(text) else: msg += 'その言葉は分からないから調べてみました。:sweat:\n' + wikipediaSearch(text) payload={'text':msg} return payload except Exception as e: print(e) raise e def getWeatherInformation(text): weather_api_url = 'http://weather.livedoor.com/forecast/webservice/json/v1' response_string = '' city_id = '' if text.find('大阪') > -1: city_id = '270000' elif text.find('東京') > -1: city_id = '130010' elif text.find('愛知') > -1 or text.find('名古屋') > -1: city_id = '230010' else: city_id = '270000' response_string += '場所がよくわからないもんでとりあえず' try: params = {'city':city_id} response = requests.get(weather_api_url,params=params) response_dict = json.loads(response.text) title = response_dict["title"] description = response_dict["description"]["text"] response_string += title + "です。:nerd_face:\n\n" forecasts_array = response_dict["forecasts"] forcast_array = [] for forcast in forecasts_array: telop = forcast["telop"] telop_icon = '' if telop.find('雪') > -1: telop_icon = ':showman:' elif telop.find('雷') > -1: telop_icon = ':thunder_cloud_and_rain:' elif telop.find('晴') > -1: if telop.find('曇') > -1: telop_icon = ':partly_sunny:' elif telop.find('雨') > -1: telop_icon = ':partly_sunny_rain:' else: telop_icon = ':sunny:' elif telop.find('雨') > -1: telop_icon = ':umbrella:' elif telop.find('曇') > -1: telop_icon = ':cloud:' else: telop_icon = ':fire:' temperature = forcast["temperature"] min_temp = temperature["min"] max_temp = temperature["max"] temp_text = '' if min_temp is not None: if len(min_temp) > 0: temp_text += '\n最低気温は' + min_temp["celsius"] + "度です。" if max_temp is not None: if len(max_temp) > 0: temp_text += '\n最高気温は' + max_temp["celsius"] + "度です。" forcast_array.append(forcast["dateLabel"] + ' ' + telop + telop_icon + temp_text) if len(forcast_array) > 0: response_string += '\n\n'.join(forcast_array) response_string += '\n\n' + description except Exception as e: response_string = 'すいません。天気検索でエラーを起こしてしまいました。改善出来るように頑張ります。:cold_sweat:\n' + e.message + '\n' + str(e) return response_string |
※Wikipediaの検索は別記事「slackのbotにWikipediaを調べてもらう(Python on AWS Lambda + API Gateway)」をご参照ください。
結果は絵文字を使って直感的に分かればいいな〜って感じにしてます。
最後までお読みいただきましてありがとうございました!
「AWS認定資格試験テキスト&問題集 AWS認定ソリューションアーキテクト - プロフェッショナル 改訂第2版」という本を書きました。

「AWS認定資格試験テキスト AWS認定クラウドプラクティショナー 改訂第3版」という本を書きました。

「ポケットスタディ AWS認定 デベロッパーアソシエイト [DVA-C02対応] 」という本を書きました。

「要点整理から攻略するAWS認定ソリューションアーキテクト-アソシエイト」という本を書きました。

「AWSではじめるLinux入門ガイド」という本を書きました。


開発ベンダー5年、ユーザ企業システム部門通算9年、ITインストラクター5年目でプロトタイプビルダーもやりだしたSoftware Engineerです。
質問はコメントかSNSなどからお気軽にどうぞ。
出来る限りなるべく答えます。
このブログの内容/発言の一切は個人の見解であり、所属する組織とは関係ありません。
このブログは経験したことなどの共有を目的としており、手順や結果などを保証するものではありません。
ご参考にされる際は、読者様自身のご判断にてご対応をお願いいたします。
また、勉強会やイベントのレポートは自分が気になったことをメモしたり、聞いて思ったことを書いていますので、登壇者の意見や発表内容ではありません。
ad
ad
関連記事
-
-
EC2 Amazon Linux 2 にAmazon LinuxからWordPressを移行
このブログを新しいインスタンスに移行することにしました。 2015年5月にAma …
-
-
AWS Service CatalogポートフォリオをOrganizations組織で共有する
AWS Service Catalogチュートリアルで作成したポートフォリオのO …
-
-
Amazon ECS Workshop for AWS Summit Online
INTRODUCTION TO AMAZON ECSに手順や必要なリンクがありま …
-
-
Amazon API GatewayをLambda(Python)で削除する
やりたいこと 特定のAWSアカウント、特定のリージョン内のAPI Gateway …
-
-
VPCピア接続した先のVPCインターフェイスエンドポイントを使用する
VPC1とVPC2でピア接続しています。 VPC2にはKMSのインターフェイスエ …
-
-
AWS LambdaでChrome HeadlessドライバをAWS Lambda Layersから使う
この記事はSelenium/Appium Advent Calendar 201 …
-
-
RDSのポイントインタイムリカバリをしました
WordPressで画像アップロードができなくなった(AWS WAFでブロックし …
-
-
AWS CDKでリージョンをまたいだクロススタックリファレンスはできなかった
例えばこんなコードが実行できるかというと、 [crayon-67d6d78eae …
-
-
Aurora Serverless Data APIを有効にしてLambdaからクエリを実行
Aurora Serverless作成 MySQLを作成しました。 作成時にDa …
-
-
AWS Transfer Family EFS向けのSFTP対応サーバー
EFSファイルシステムは作成済です。 AWS Transfer Family S …