Spaces:
Running
Running
Update join.py
Browse files1 unmodified line234567891011121314151617181920211 unmodified line232425262728101 unmodified lines1301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731743 unmodified lines1781791801811821831841851861871881891901911921931941951961971981992002 unmodified lines2032042052062072082092102112122132142152162172 unmodified lines2202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074081 unmodified lineimport requestsimport osimport jsonfrom datetime import datetime, timedeltafrom zoneinfo import ZoneInfoimport websocketimport threadingimport relBASE_URL = "https://desk-api.channel.io/desk/channels/240996"API_URL = "https://api.channel.works/desk/channels/240996"TARGET_GROUP_CHAT_ID = "574628"WEBSOCKET_URL = "wss://desk-ws.channel.io/socket.io/?platform=web&EIO=4&transport=websocket"HEADERS = {"accept-language": "ja","x-account": os.getenv("dmsendertoken")}JST = ZoneInfo("Asia/Tokyo")1 unmodified line# WebSocket接続管理用ws = Nonews_connected = False# ---------------- 天気コード ----------------101 unmodified lines}def format_weather_code(code: int) -> str:if code < 10:return WEATHER_CODE_MAP.get(code, str(code))main = code // 10sub = code % 10main_str = WEATHER_CODE_MAP.get(main)sub_str = WEATHER_CODE_MAP.get(sub)if main_str and sub_str:return f"{main_str}、{sub_str}"return str(code)# ---------------- WebSocket処理 ----------------def on_message(ws, message):"""WebSocketメッセージ受信時の処理"""global ws_connectedtry:# Socket.IOプロトコルの処理if message == "2":# ping対応ws.send("3")returnif message == "3":# pongreturnif message.startswith("0{"):# 接続確立時の初期メッセージ# 認証情報を送信jwt_token = os.getenv("dmsendertoken")auth_message = f'40/desk/channel,{{"channelId":"240996","jwt":"{jwt_token}"}}'ws.send(auth_message)ws_connected = Trueprint("WebSocket: 認証情報を送信しました")returnif message.startswith("40"):3 unmodified linesif message.startswith("42"):# メッセージデータの処理# "42"の後にJSON配列が続くjson_str = message[2:]data = json.loads(json_str)if isinstance(data, list) and len(data) >= 2:event_type = data[0]event_data = data[1]if event_type == "push":# メッセージ受信handle_push_event(event_data)elif event_type == "create":# ユーザー参加handle_create_event(event_data)except Exception as e:print(f"WebSocket メッセージ処理エラー: {e}")def handle_push_event(event_data):"""pushイベントの処理"""2 unmodified lineschat_id = entity.get("chatId")chat_type = entity.get("chatType")person_type = entity.get("personType")message_text = entity.get("plainText", "")if chat_type == "group" and chat_id == TARGET_GROUP_CHAT_ID:print(f"グループメッセージ受信: {message_text}")# ここで受信メッセージに対する処理を実装# 例: コマンド処理などexcept Exception as e:print(f"push イベント処理エラー: {e}")def handle_create_event(event_data):"""createイベントの処理(ユーザー参加など)"""2 unmodified lineslog = entity.get("log", {})chat_id = entity.get("chatId")person_id = entity.get("personId")if log.get("action") == "join" and chat_id == TARGET_GROUP_CHAT_ID:print(f"ユーザーが参加しました: {person_id}")# 参加メッセージなどを送信する場合はここで処理except Exception as e:print(f"create イベント処理エラー: {e}")def on_error(ws, error):print(f"WebSocket エラー: {error}")def on_close(ws, close_status_code, close_msg):global ws_connectedws_connected = Falseprint("WebSocket 接続が閉じられました")def on_open(ws):print("WebSocket 接続が開かれました")def start_websocket():"""WebSocket接続を開始"""websocket.enableTrace(False)ws = websocket.WebSocketApp(WEBSOCKET_URL,on_open=on_open,on_message=on_message,on_error=on_error,on_close=on_close)# 永続的に接続を維持ws.run_forever(ping_interval=30,ping_timeout=10,reconnect=5)# ---------------- メッセージ送信 ----------------def post_group_message(chat_id, body):"""WebSocket APIを使用してグループメッセージを送信"""url = f"{API_URL}/groups/{chat_id}/messages"r = requests.post(url, headers=HEADERS, json=body)r.raise_for_status()return r.json()# ---------------- 時報 ----------------def create_time_signal_body():now = datetime.now(JST)hour = now.hourif hour < 12:period = "午前"display_hour = hour if hour != 0 else 12else:period = "午後"display_hour = hour - 12 if hour > 12 else 12message = f"<b>時報</b>\n{period}{display_hour}時をお知らせします。"return {"requestId": f"desk-web-time-signal-{int(time.time())}","blocks": [{"type": "text", "value": message}],}# ---------------- 天気予報 ----------------def load_todoufuken():with open("todoufuken.json", encoding="utf-8") as f:lines = []for line in f:stripped = line.lstrip()if stripped.startswith("//"):continuelines.append(line)json_str = "".join(lines)return json.loads(json_str)def fetch_weather(todoufuken):lats = ",".join(str(p["lat"]) for p in todoufuken)lons = ",".join(str(p["lon"]) for p in todoufuken)url = ("https://api.open-meteo.com/v1/forecast"f"?latitude={lats}"f"&longitude={lons}""&hourly=relative_humidity_2m,apparent_temperature,temperature_2m,""precipitation_probability,weather_code""&forecast_days=1""&timezone=Asia%2FTokyo")r = requests.get(url)r.raise_for_status()return r.json()def create_weather_body():now = datetime.now(JST)today_7am = now.replace(hour=7, minute=0, second=0, microsecond=0)todoufuken = load_todoufuken()data = fetch_weather(todoufuken)lines = ["<b>☀️ 本日の天気予報(7時以降・1時間ごと)</b>"]for idx, pref in enumerate(todoufuken):hourly = data[idx]["hourly"]times = hourly["time"]lines.append(f"\n<b>{pref['name']}:</b>")TARGET_HOURS = {7, 10, 13, 16, 21}for i, t in enumerate(times):t_jst = (datetime.fromisoformat(t).replace(tzinfo=ZoneInfo("UTC")).astimezone(JST))if t_jst.hour not in TARGET_HOURS:continuewc = hourly["weather_code"][i]at = hourly["apparent_temperature"][i]temp = hourly["temperature_2m"][i]pop = hourly["precipitation_probability"][i]rh = hourly["relative_humidity_2m"][i]wc_str = format_weather_code(wc)line = (f" {t_jst.strftime('%H時')}:"f"{wc_str} "f"{at}℃ {temp}℃ {pop}% {rh}%")lines.append(line)message2 = "☀️・・・晴れ、☁️・・・曇り、🌫️・・・霧・霧雨、🌧️・・・雨、🌨️・・・雪、🌦️・・・にわか雨、⛈️・・・雷雨"return {"requestId": f"desk-web-weather-{int(time.time())}","blocks": [{"type": "text", "value": "\n".join(lines)},{"type": "text", "value": message2}],}# ---------------- メインループ ----------------def main_loop():last_time_signal = Nonelast_weather = Nonewhile True:try:now = datetime.now(JST)current_date = now.date()# 毎正時の時報if now.minute == 0 and last_time_signal != now.hour:body = create_time_signal_body()post_group_message(TARGET_GROUP_CHAT_ID, body)last_time_signal = now.hourprint(f"時報を送信しました: {now.strftime('%H:%M')}")# 午前11時30分に天気予報if now.hour == 11 and now.minute == 30 and last_weather != current_date:body = create_weather_body()post_group_message(TARGET_GROUP_CHAT_ID, body)last_weather = current_dateprint("天気予報を送信しました")time.sleep(30) # 30秒間隔でチェックexcept Exception as e:print("Error:", e)time.sleep(10)if __name__ == "__main__":# WebSocket接続を別スレッドで開始ws_thread = threading.Thread(target=start_websocket, daemon=True)ws_thread.start()# メインループを実行main_loop()1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839401 unmodified line4243444546474849505152535455565758101 unmodified lines1601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302313 unmodified lines2352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712 unmodified lines2742752762772782792802812822832842852862872882892902912922932942952962972982993003013022 unmodified lines3053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247251 unmodified lineimport requestsimport osimport jsonimport sysimport tracebackfrom datetime import datetime, timedeltafrom zoneinfo import ZoneInfoimport websocketimport threadingimport logging# ロギングの設定logging.basicConfig(level=logging.INFO,format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',handlers=[logging.FileHandler('bot.log', encoding='utf-8'),logging.StreamHandler(sys.stdout)])BASE_URL = "https://desk-api.channel.io/desk/channels/240996"API_URL = "https://api.channel.works/desk/channels/240996"TARGET_GROUP_CHAT_ID = "574628"WEBSOCKET_URL = "wss://desk-ws.channel.io/socket.io/?platform=web&EIO=4&transport=websocket"# 環境変数の確認DMSENDER_TOKEN = os.getenv("dmsendertoken")if not DMSENDER_TOKEN:print("環境変数 'dmsendertoken' が設定されていません")sys.exit(1)HEADERS = {"accept-language": "ja","x-account": DMSENDER_TOKEN}JST = ZoneInfo("Asia/Tokyo")1 unmodified line# WebSocket接続管理用ws = Nonews_connected = Falsews_reconnect_count = 0MAX_RECONNECT_ATTEMPTS = 10# 統計情報stats = {"messages_sent": 0,"messages_received": 0,"errors": 0,"ws_reconnects": 0,"start_time": datetime.now(JST)}# ---------------- 天気コード ----------------101 unmodified lines}def format_weather_code(code: int) -> str:"""天気コードを文字列に変換"""try:if code < 10:return WEATHER_CODE_MAP.get(code, f"不明な天気コード: {code}")main = code // 10sub = code % 10main_str = WEATHER_CODE_MAP.get(main, f"不明({main})")sub_str = WEATHER_CODE_MAP.get(sub, f"不明({sub})")if main_str and sub_str:return f"{main_str}、{sub_str}"return f"不明な天気コード: {code}"except Exception as e:print(f"天気コード変換エラー (code={code}): {e}")return f"変換エラー({code})"# ---------------- WebSocket処理 ----------------def log_stats():"""統計情報をログ出力"""uptime = datetime.now(JST) - stats["start_time"]print(f"=== 統計情報 ===")print(f"稼働時間: {uptime}")print(f"送信メッセージ数: {stats['messages_sent']}")print(f"受信メッセージ数: {stats['messages_received']}")print(f"エラー数: {stats['errors']}")print(f"WebSocket再接続回数: {stats['ws_reconnects']}")def on_message(ws, message):"""WebSocketメッセージ受信時の処理"""global ws_connected, ws_reconnect_counttry:# Socket.IOプロトコルの処理if message == "2":# ping対応print("WebSocket: ping受信、pong送信")ws.send("3")returnif message == "3":# pongprint("WebSocket: pong受信")returnif message.startswith("0{"):# 接続確立時の初期メッセージprint(f"WebSocket: 接続確立、初期メッセージ受信: {message[:100]}...")try:# 認証情報を送信jwt_token = os.getenv("dmsendertoken")if not jwt_token:print("WebSocket: JWT tokenが設定されていません")returnauth_message = f'40/desk/channel,{{"channelId":"240996","jwt":"{jwt_token}"}}'ws.send(auth_message)ws_connected = Truews_reconnect_count = 0print("WebSocket: 認証情報を送信しました")except Exception as e:print(f"WebSocket: 認証情報送信エラー: {e}")stats["errors"] += 1returnif message.startswith("40"):3 unmodified linesif message.startswith("42"):# メッセージデータの処理try:json_str = message[2:]data = json.loads(json_str)if isinstance(data, list) and len(data) >= 2:event_type = data[0]event_data = data[1]print(f"WebSocket: イベント受信 type={event_type}")if event_type == "push":# メッセージ受信handle_push_event(event_data)elif event_type == "create":# ユーザー参加handle_create_event(event_data)else:print(f"WebSocket: 未処理のイベントタイプ: {event_type}")else:print(f"WebSocket: 予期しないデータ形式: {type(data)}")except json.JSONDecodeError as e:print(f"WebSocket: JSON解析エラー: {e}, データ: {json_str[:200]}")stats["errors"] += 1except Exception as e:print(f"WebSocket: メッセージ処理エラー: {e}")stats["errors"] += 1except Exception as e:print(f"WebSocket on_message エラー: {e}\n{traceback.format_exc()}")stats["errors"] += 1def handle_push_event(event_data):"""pushイベントの処理"""2 unmodified lineschat_id = entity.get("chatId")chat_type = entity.get("chatType")person_type = entity.get("personType")person_id = entity.get("personId")message_text = entity.get("plainText", "")message_id = entity.get("id", "unknown")refers = event_data.get("refers", {})manager_info = refers.get("manager", {})manager_name = manager_info.get("name", "不明")print(f"メッセージ受信: id={message_id}, chatType={chat_type}, chatId={chat_id}, "f"personType={person_type}, personId={person_id}, from={manager_name}")stats["messages_received"] += 1if chat_type == "group" and chat_id == TARGET_GROUP_CHAT_ID:print(f"対象グループのメッセージ: '{message_text[:100]}' from {manager_name}")# ここで受信メッセージに対する処理を実装# 例: コマンド処理などelse:print(f"対象外のチャットからのメッセージ: chatType={chat_type}, chatId={chat_id}")except Exception as e:print(f"push イベント処理エラー: {e}\n{traceback.format_exc()}")stats["errors"] += 1def handle_create_event(event_data):"""createイベントの処理(ユーザー参加など)"""2 unmodified lineslog = entity.get("log", {})chat_id = entity.get("chatId")person_id = entity.get("personId")person_type = entity.get("personType")action = log.get("action", "unknown")print(f"create イベント: action={action}, chatId={chat_id}, "f"personId={person_id}, personType={person_type}")if action == "join":if chat_id == TARGET_GROUP_CHAT_ID:print(f"ユーザーが対象グループに参加しました: personId={person_id}")# 参加メッセージなどを送信する場合はここで処理else:print(f"ユーザーがグループに参加: chatId={chat_id}, personId={person_id}")elif action == "leave":print(f"ユーザーがグループから退出: chatId={chat_id}, personId={person_id}")else:print(f"その他のアクション: {action}")except Exception as e:print(f"create イベント処理エラー: {e}\n{traceback.format_exc()}")stats["errors"] += 1def on_error(ws, error):"""WebSocketエラー時の処理"""print(f"WebSocket エラー: {error}")stats["errors"] += 1if isinstance(error, ConnectionRefusedError):print("WebSocket: 接続が拒否されました")elif isinstance(error, ConnectionResetError):print("WebSocket: 接続がリセットされました")elif isinstance(error, websocket.WebSocketConnectionClosedException):print("WebSocket: 接続が閉じられています")def on_close(ws, close_status_code, close_msg):"""WebSocket接続クローズ時の処理"""global ws_connected, ws_reconnect_countws_connected = Falsews_reconnect_count += 1stats["ws_reconnects"] += 1print(f"WebSocket 接続が閉じられました: status_code={close_status_code}, "f"message={close_msg}, reconnect_count={ws_reconnect_count}")if ws_reconnect_count > MAX_RECONNECT_ATTEMPTS:print(f"WebSocket: 最大再接続回数({MAX_RECONNECT_ATTEMPTS})を超えました")# ここで必要に応じてプログラムを終了するなどの処理def on_open(ws):"""WebSocket接続開始時の処理"""global ws_reconnect_countprint("WebSocket 接続が開かれました")ws_reconnect_count = 0log_stats()def start_websocket():"""WebSocket接続を開始"""print(f"WebSocket接続を開始します: {WEBSOCKET_URL}")try:websocket.enableTrace(False) # デバッグ用にTrueにすると詳細なトレースが表示されますws_app = websocket.WebSocketApp(WEBSOCKET_URL,on_open=on_open,on_message=on_message,on_error=on_error,on_close=on_close)# 永続的に接続を維持ws_app.run_forever(ping_interval=30,ping_timeout=10,reconnect=5 # 5秒後に再接続)except Exception as e:print(f"WebSocket接続の開始に失敗: {e}\n{traceback.format_exc()}")stats["errors"] += 1raise# ---------------- メッセージ送信 ----------------def post_group_message(chat_id, body, retry_count=3):"""WebSocket APIを使用してグループメッセージを送信(リトライ機能付き)"""url = f"{API_URL}/groups/{chat_id}/messages"for attempt in range(retry_count):try:print(f"メッセージ送信試行: chat_id={chat_id}, attempt={attempt + 1}/{retry_count}")print(f"送信データ: {json.dumps(body, ensure_ascii=False)[:200]}")r = requests.post(url, headers=HEADERS, json=body, timeout=10)if r.status_code == 200:response_data = r.json()print(f"メッセージ送信成功: chat_id={chat_id}, status={r.status_code}")stats["messages_sent"] += 1return response_dataelif r.status_code == 401:print(f"認証エラー: status={r.status_code}, response={r.text[:200]}")raise Exception("認証エラー: APIキーが無効です")elif r.status_code == 429:print(f"レート制限: status={r.status_code}, {attempt + 1}回目の試行")if attempt < retry_count - 1:wait_time = (attempt + 1) * 5print(f"{wait_time}秒待機してからリトライします")time.sleep(wait_time)else:print("レート制限により送信失敗(最大リトライ回数超過)")else:print(f"メッセージ送信エラー: status={r.status_code}, response={r.text[:200]}")if attempt < retry_count - 1:time.sleep(2)else:r.raise_for_status()except requests.exceptions.Timeout:print(f"リクエストタイムアウト: {url}, attempt={attempt + 1}")if attempt < retry_count - 1:time.sleep(2)else:raiseexcept requests.exceptions.ConnectionError as e:print(f"接続エラー: {e}, attempt={attempt + 1}")if attempt < retry_count - 1:time.sleep(5)else:raiseexcept requests.exceptions.RequestException as e:print(f"リクエストエラー: {e}, attempt={attempt + 1}")if attempt < retry_count - 1:time.sleep(2)else:raiseexcept Exception as e:print(f"予期しない送信エラー: {e}\n{traceback.format_exc()}")stats["errors"] += 1raiseprint("メッセージ送信に失敗しました(全リトライ終了)")stats["errors"] += 1raise Exception("メッセージ送信に失敗しました")# ---------------- 時報 ----------------def create_time_signal_body():"""時報メッセージを作成"""try:now = datetime.now(JST)hour = now.hourif hour < 12:period = "午前"display_hour = hour if hour != 0 else 12else:period = "午後"display_hour = hour - 12 if hour > 12 else 12message = f"<b>時報</b>\n{period}{display_hour}時をお知らせします。"print(f"時報メッセージ作成: {message}")return {"requestId": f"desk-web-time-signal-{int(time.time())}","blocks": [{"type": "text", "value": message}],}except Exception as e:print(f"時報メッセージ作成エラー: {e}")raise# ---------------- 天気予報 ----------------def load_todoufuken():"""都道府県データを読み込み"""try:file_path = "todoufuken.json"print(f"都道府県データ読み込み: {file_path}")if not os.path.exists(file_path):print(f"ファイルが見つかりません: {file_path}")raise FileNotFoundError(f"ファイルが見つかりません: {file_path}")with open(file_path, encoding="utf-8") as f:lines = []for line_num, line in enumerate(f, 1):stripped = line.lstrip()if stripped.startswith("//"):print(f"コメント行をスキップ: line {line_num}")continuelines.append(line)json_str = "".join(lines)data = json.loads(json_str)print(f"都道府県データ読み込み成功: {len(data)}件")return dataexcept FileNotFoundError as e:print(f"ファイルエラー: {e}")raiseexcept json.JSONDecodeError as e:print(f"JSON解析エラー: {e}")raiseexcept Exception as e:print(f"都道府県データ読み込みエラー: {e}\n{traceback.format_exc()}")raisedef fetch_weather(todoufuken):"""天気データを取得"""try:lats = ",".join(str(p["lat"]) for p in todoufuken)lons = ",".join(str(p["lon"]) for p in todoufuken)url = ("https://api.open-meteo.com/v1/forecast"f"?latitude={lats}"f"&longitude={lons}""&hourly=relative_humidity_2m,apparent_temperature,temperature_2m,""precipitation_probability,weather_code""&forecast_days=1""&timezone=Asia%2FTokyo")print(f"天気データ取得開始: {len(todoufuken)}地点")print(f"API URL: {url[:200]}...")r = requests.get(url, timeout=30)r.raise_for_status()data = r.json()print("天気データ取得成功")return dataexcept requests.exceptions.Timeout:print("天気API: リクエストタイムアウト")raiseexcept requests.exceptions.ConnectionError as e:print(f"天気API: 接続エラー: {e}")raiseexcept requests.exceptions.RequestException as e:print(f"天気API: リクエストエラー: {e}")raiseexcept Exception as e:print(f"天気データ取得エラー: {e}\n{traceback.format_exc()}")raisedef create_weather_body():"""天気予報メッセージを作成"""try:print("天気予報メッセージ作成開始")now = datetime.now(JST)today_7am = now.replace(hour=7, minute=0, second=0, microsecond=0)todoufuken = load_todoufuken()data = fetch_weather(todoufuken)lines = ["<b>☀️ 本日の天気予報(7時以降・1時間ごと)</b>"]target_hours = {7, 10, 13, 16, 21}for idx, pref in enumerate(todoufuken):try:hourly = data[idx]["hourly"]times = hourly["time"]lines.append(f"\n<b>{pref['name']}:</b>")pref_data_count = 0for i, t in enumerate(times):t_jst = (datetime.fromisoformat(t).replace(tzinfo=ZoneInfo("UTC")).astimezone(JST))if t_jst.hour not in target_hours:continuewc = hourly["weather_code"][i]at = hourly["apparent_temperature"][i]temp = hourly["temperature_2m"][i]pop = hourly["precipitation_probability"][i]rh = hourly["relative_humidity_2m"][i]wc_str = format_weather_code(wc)line = (f" {t_jst.strftime('%H時')}:"f"{wc_str} "f"体感{at}℃ 気温{temp}℃ 降水確率{pop}% 湿度{rh}%")lines.append(line)pref_data_count += 1print(f"{pref['name']}: {pref_data_count}時間分のデータを追加")except Exception as e:print(f"都道府県データ処理エラー (index={idx}, pref={pref.get('name', 'unknown')}): {e}")lines.append(f"\n<b>{pref.get('name', '不明')}:</b>データ取得エラー")continuemessage2 = "☀️・・・晴れ、☁️・・・曇り、🌫️・・・霧・霧雨、🌧️・・・雨、🌨️・・・雪、🌦️・・・にわか雨、⛈️・・・雷雨"body = {"requestId": f"desk-web-weather-{int(time.time())}","blocks": [{"type": "text", "value": "\n".join(lines)},{"type": "text", "value": message2}],}print(f"天気予報メッセージ作成完了: {len(lines)}行")return bodyexcept Exception as e:print(f"天気予報メッセージ作成エラー: {e}\n{traceback.format_exc()}")# エラー時のフォールバックメッセージreturn {"requestId": f"desk-web-weather-error-{int(time.time())}","blocks": [{"type": "text", "value": "天気予報の���得に失敗しました。しばらく待ってから再試行してください。"}],}# ---------------- メインループ ----------------def main_loop():"""メイン処理ループ"""print("メインループを開始します")last_time_signal = Nonelast_weather = Nonecheck_interval = 30 # チェック間隔(秒)while True:try:now = datetime.now(JST)current_date = now.date()current_hour = now.hourcurrent_minute = now.minuteprint(f"ループチェック: {now.strftime('%Y-%m-%d %H:%M:%S')}")# 毎正時の時報if current_minute == 0 and last_time_signal != current_hour:try:print(f"時報送信: {current_hour}時")body = create_time_signal_body()post_group_message(TARGET_GROUP_CHAT_ID, body)last_time_signal = current_hourprint(f"時報送信完了: {now.strftime('%H:%M')}")except Exception as e:print(f"時報送信エラー: {e}")stats["errors"] += 1# 午前11時30分に天気予報if current_hour == 11 and current_minute == 30 and last_weather != current_date:try:print("天気予報送信開始")body = create_weather_body()post_group_message(TARGET_GROUP_CHAT_ID, body)last_weather = current_dateprint("天気予報送信完了")except Exception as e:print(f"天気予報送信エラー: {e}")stats["errors"] += 1# 1時間ごとに統計情報をログ出力if current_minute == 0:log_stats()# エラーが多い場合は警告if stats["errors"] > 100:print(f"エラー数が100を超えました: {stats['errors']}")time.sleep(check_interval)except KeyboardInterrupt:print("プログラムを終了します(Ctrl+C)")log_stats()breakexcept Exception as e:print(f"メインループエラー: {e}\n{traceback.format_exc()}")stats["errors"] += 1time.sleep(10)if __name__ == "__main__":try:print("=== ボット起動 ===")print(f"開始時刻: {datetime.now(JST).strftime('%Y-%m-%d %H:%M:%S')}")print(f"ターゲットグループID: {TARGET_GROUP_CHAT_ID}")print(f"API URL: {API_URL}")# 起動時の環境チェックif not os.path.exists("todoufuken.json"):print("todoufuken.json が見つかりません")sys.exit(1)# WebSocket接続を別スレッドで開始ws_thread = threading.Thread(target=start_websocket, daemon=True, name="WebSocketThread")ws_thread.start()print(f"WebSocketスレッドを開始しました: {ws_thread.name}")# メインループを実行main_loop()except KeyboardInterrupt:print("プログラムを終了します")except Exception as e:print(f"致命的なエラーが発生しました: {e}\n{traceback.format_exc()}")sys.exit(1)finally:print("=== ボット終了 ===")log_stats()
join.py+474-157