From 353125de21c585ad257a152932eddf952cd1e516 Mon Sep 17 00:00:00 2001 From: suti7yk5032 Date: Sun, 18 Aug 2024 17:41:59 +0900 Subject: [PATCH] =?UTF-8?q?Discord=E7=94=A8=E3=81=AE=E3=83=95=E3=82=A1?= =?UTF-8?q?=E3=82=A4=E3=83=AB=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- earthquake_bot_discord.py | 133 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 earthquake_bot_discord.py diff --git a/earthquake_bot_discord.py b/earthquake_bot_discord.py new file mode 100644 index 0000000..fd2fe9f --- /dev/null +++ b/earthquake_bot_discord.py @@ -0,0 +1,133 @@ +from flask import Flask, request, jsonify +from datetime import datetime +import json +import os +import requests + +class Bot(): + def __init__(self): + self.config_dir_path = "./config/" + self.server_config_path = self.config_dir_path + "config_discord.json" + try: + if not os.path.isdir(self.config_dir_path): + print("config ディレクトリが見つかりません... 作成します。") + os.mkdir(self.config_dir_path) + if not os.path.isfile(self.server_config_path): + print("config ファイルが見つかりません... 作成します。") + self.server_config = { + "bot": { + "webhook_url": "", + "platform": "discord" + } + } + with open(self.server_config_path, "w") as w: + json.dump(self.server_config, w, indent=4) + self.init_result = 2 + + elif os.path.isfile(self.server_config_path): + with open(self.server_config_path, "r") as r: + self.server_config = json.load(r) + print("config ファイルを読み込みました。") + self.init_result = 0 + + except (Exception) as error: + print("初回処理でエラーが発生しました。\nエラー内容\n" + str(error)) + self.init_result = 1 + + def format_earthquake_info(self, data): + if data['type'] == 'eew': + event_time = datetime.fromtimestamp(int(data['time']) / 1000).strftime("%Y年%m月%d日 %H時%M分%S秒") + if data["report"] == '1' or data['report'] == 'final': + if data['report'] == 'final': + report_number = '最終' + else: + report_number = '第' + data['report'] + + intensity = data['intensity'] + epicenter = data['epicenter'] + epicenter_depth = data['depth'] + magnitude = data['magnitude'] + result = {"result": 0, "detail": f"震源地 {epicenter} 予想震度 {intensity}\nマグニチュード {magnitude} 震源の深さ {epicenter_depth}\n緊急地震速報 {report_number}報\n時刻 | {event_time}"} + else: + result = {"result": 1, "detail": "not_1st_or_final_report"} + elif data['type'] == 'pga_alert_cancel': + print(data) + result = {"result": 0, "detail": f"誤報を検出。一つ前のノートは誤報です。"} + elif data['type'] == 'pga_alert': + result = {"result": 1, "detail": "pga_alert_detected"} + elif data['type'] == 'intensity_report': + #event_time = datetime.fromtimestamp(int(data['time']) / 1000).strftime("%Y年%m月%d日 %H時%M分%S秒") + #intensity_info = data['intensity_list'][0] + #intensity = intensity_info['intensity'] + #regions = intensity_info['region_list'][0] + #result = {"result": 0, "detail": f"{regions} で地震 震度 {intensity}\n時刻 | {event_time}"} + result = {"result": 1, "detail": "intensity_report_detected"} + else: + result = {"result": 1, "detail": "unknown_data_detected"} + return result + + def post(self, **kwargs): + content = {"content": kwargs["content"]} + platform = self.server_config["bot"]["platform"] + webhook_url = self.server_config["bot"]["webhook_url"] + + try: + if platform == "discord": + send = requests.post(webhook_url, json.dumps(content), headers={'Content-Type': 'application/json'}) + if send.status_code == 200: + result = {"result": 0, "detail": "Posted to Discord (Used Webhook)"} + else: + result = {"result": 1, "detail": "Can't Post to Discord (Used Webhook)"} + else: + result = {"result": 1, "detail": "Unsupported Platforms"} + except Exception as e: + result = {"result": 1, "detail": str(e)} + finally: + return result + +web = Flask(__name__) + +@web.route('/earthquake', methods=['POST']) +def receive_earthquake_data(): + earthquake_data = request.json + #この時点でjsonは辞書に変換されている + info = bot.format_earthquake_info(earthquake_data) + current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + try: + if info["result"] == 0: + detail = info["detail"] + post = bot.post(content=detail) + if post["result"] == 0: + print(f"{str(current_time)} jsonを受信") + print(f"json_dict\n{earthquake_data}") + print(f"投稿内容\n{detail}") + return jsonify({"status": "success", "message": "Posted"}), 200 + elif post["result"] == 1: + print(f"{str(current_time)} 投稿の際にエラーが発生しました") + print("エラー内容\n" + str(post["detail"])) + return jsonify({"status": "passed", "message": "ERROR"}), 500 + elif info["result"] == 1: + if info["detail"] == "pga_alert_detected": + print(f"{str(current_time)} pga_alert のため、無視されました。") + return jsonify({"status": "passed", "message": "pga_alert"}), 500 + elif info["detail"] == "intensity_report_detected": + print(f"{str(current_time)} intensity_report のため、無視されました。") + return jsonify({"status": "passed", "message": "intensity_report"}), 500 + elif info["detail"] == "not_1st_or_final_report": + print(f"{str(current_time)} 第1報 または 最終報 以外 のため、無視されました。") + return jsonify({"status": "passed", "message": "not_1st_or_final_report"}), 500 + else: + print(f"{str(current_time)} 不明なデータ のため、無視されました。\njsonの内容") + print(earthquake_data) + return jsonify({"status": "passed", "message": "unknown_data"}), 500 + except Exception as e: + print(e) + return jsonify({"status": "error", "message": str(e)}), 500 + +if __name__ == '__main__': + bot = Bot() + print(bot.init_result) + if bot.init_result == 0: + web.run(host='127.0.0.1', port=5000, debug=True) + elif bot.init_result == 2: + print("config ファイルを編集してから、もう一度起動してください。")