Spaces:
Running
Running
Update join.py
Browse files1 unmodified line23456789109111213141516171819202122232425262728293031323334353618373839401 unmodified line4243444546474849505152535455565758101 unmodified lines1601611621631641331341651661671361371681691701391401711721731421431741751761451771781791801811821831841851861871881891901911921931941951511961971981992002012022032042052062072082092102112121661671681691701712132142152162172182192202212222232242252262272282292302313 unmodified lines2352362371811821831841851861872382392402412422432442452462471891901911921931942482492502512522532542552562572582592602612622632642652661972672682692702712 unmodified lines2742752762772782792802812822832842852862872882892902092912922932942952962972142982993003013022 unmodified lines3053063073083093103113123133143152242252263163173183193203213223233243253262293273283293303313323333343353363373383393403413422353433443452373463473483493503513523533543553563573583593603613623633642442452462472482492502513653663673683693703713723733743753763772532542552562572583783793803813823833843853863873883893902622633913923932652662673943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534542722732742752762772782792804554564574584592824604614624634644654664674684694702842852862874714724734744754764774784794804812922932942952962972982993003014824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185193053063073083093103113123133143153163173183193205205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565573243253263273283293303313323333345585595605615625635643365655665673385685693403413423433443455705713473485725735745755765775785795805815825835845855865875885895903503513523533543553563573583593603613623633643653663673685915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556563823833843853866576586596606616626636646656666676683893903913923936696706716726736746756766776786796806816826836846853956866876886896906916923986936946956966976986997007017027037047057067077087097104034044054064074087117127137147157167177187197207217227237247251 unmodified lineimport requestsimport osimport jsonimport sysimport tracebackfrom datetime import datetime, timedeltafrom zoneinfo import ZoneInfoimport websocketimport threadingimport relimport 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": os.getenv("dmsendertoken") "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, str(code)) if code < 10: return WEATHER_CODE_MAP.get(code, f"不明な天気コード: {code}")
main = code // 10 sub = code % 10 main = code // 10 sub = code % 10
main_str = WEATHER_CODE_MAP.get(main) sub_str = WEATHER_CODE_MAP.get(sub) main_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}" if main_str and sub_str: return f"{main_str}、{sub_str}"
return str(code) 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 global ws_connected, ws_reconnect_count try: # Socket.IOプロトコルの処理 if message == "2": # ping対応 print("WebSocket: ping受信、pong送信") ws.send("3") return if message == "3": # pong print("WebSocket: pong受信") return if 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 = True print("WebSocket: 認証情報を送信しました") print(f"WebSocket: 接続確立、初期メッセージ受信: {message[:100]}...") try: # 認証情報を送信 jwt_token = os.getenv("dmsendertoken") if not jwt_token: print("WebSocket: JWT tokenが設定されていません") return auth_message = f'40/desk/channel,{{"channelId":"240996","jwt":"{jwt_token}"}}' ws.send(auth_message) ws_connected = True ws_reconnect_count = 0 print("WebSocket: 認証情報を送信しました") except Exception as e: print(f"WebSocket: 認証情報送信エラー: {e}") stats["errors"] += 1 return if message.startswith("40"):3 unmodified lines if 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] 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) 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"] += 1 except Exception as e: print(f"WebSocket: メッセージ処理エラー: {e}") stats["errors"] += 1 except Exception as e: print(f"WebSocket メッセージ処理エラー: {e}") print(f"WebSocket on_message エラー: {e}\n{traceback.format_exc()}") stats["errors"] += 1
def handle_push_event(event_data): """pushイベントの処理"""2 unmodified lines chat_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"] += 1 if chat_type == "group" and chat_id == TARGET_GROUP_CHAT_ID: print(f"グループメッセージ受信: {message_text}") 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}") print(f"push イベント処理エラー: {e}\n{traceback.format_exc()}") stats["errors"] += 1
def handle_create_event(event_data): """createイベントの処理(ユーザー参加など)"""2 unmodified lines log = 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 log.get("action") == "join" and chat_id == TARGET_GROUP_CHAT_ID: print(f"ユーザーが参加しました: {person_id}") # 参加メッセージなどを送信する場合はここで処理 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}") print(f"create イベント処理エラー: {e}\n{traceback.format_exc()}") stats["errors"] += 1
def on_error(ws, error): """WebSocketエラー時の処理""" print(f"WebSocket エラー: {error}") stats["errors"] += 1 if 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): global ws_connected """WebSocket接続クローズ時の処理""" global ws_connected, ws_reconnect_count ws_connected = False print("WebSocket 接続が閉じられました") ws_reconnect_count += 1 stats["ws_reconnects"] += 1 print(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_count print("WebSocket 接続が開かれました") ws_reconnect_count = 0 log_stats()
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 ) 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.run_forever( ping_interval=30, ping_timeout=10, reconnect=5 ) # 永続的に接続を維持 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"] += 1 raise
# ---------------- メッセージ送信 ----------------
def post_group_message(chat_id, body): """WebSocket APIを使用してグループメッセージを送信"""def post_group_message(chat_id, body, retry_count=3): """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() 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"] += 1 return response_data elif 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) * 5 print(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: raise except requests.exceptions.ConnectionError as e: print(f"接続エラー: {e}, attempt={attempt + 1}") if attempt < retry_count - 1: time.sleep(5) else: raise except requests.exceptions.RequestException as e: print(f"リクエストエラー: {e}, attempt={attempt + 1}") if attempt < retry_count - 1: time.sleep(2) else: raise except Exception as e: print(f"予期しない送信エラー: {e}\n{traceback.format_exc()}") stats["errors"] += 1 raise print("メッセージ送信に失敗しました(全リトライ終了)") stats["errors"] += 1 raise Exception("メッセージ送信に失敗しました")
# ---------------- 時報 ----------------
def create_time_signal_body(): now = datetime.now(JST) hour = now.hour
if hour < 12: period = "午前" display_hour = hour if hour != 0 else 12 else: period = "午後" display_hour = hour - 12 if hour > 12 else 12 """時報メッセージを作成""" try: now = datetime.now(JST) hour = now.hour
message = f"<b>時報</b>\n{period}{display_hour}時をお知らせします。" if hour < 12: period = "午前" display_hour = hour if hour != 0 else 12 else: period = "午後" display_hour = hour - 12 if hour > 12 else 12
message = 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}], } 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(): with open("todoufuken.json", encoding="utf-8") as f: lines = [] for line in f: stripped = line.lstrip() if stripped.startswith("//"): continue lines.append(line)
json_str = "".join(lines) return json.loads(json_str) """都道府県データを読み込み""" 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}") continue lines.append(line)
json_str = "".join(lines) data = json.loads(json_str) print(f"都道府県データ読み込み成功: {len(data)}件") return data except FileNotFoundError as e: print(f"ファイルエラー: {e}") raise except json.JSONDecodeError as e: print(f"JSON解析エラー: {e}") raise except Exception as e: print(f"都道府県データ読み込みエラー: {e}\n{traceback.format_exc()}") raise
def 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" )
r = requests.get(url) r.raise_for_status() return r.json() 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 data except requests.exceptions.Timeout: print("天気API: リクエストタイムアウト") raise except requests.exceptions.ConnectionError as e: print(f"天気API: 接続エラー: {e}") raise except requests.exceptions.RequestException as e: print(f"天気API: リクエストエラー: {e}") raise except Exception as e: print(f"天気データ取得エラー: {e}\n{traceback.format_exc()}") raise
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"] """天気予報メッセージを作成""" try: print("天気予報メッセージ作成開始") now = datetime.now(JST) today_7am = now.replace(hour=7, minute=0, second=0, microsecond=0)
lines.append(f"\n<b>{pref['name']}:</b>") todoufuken = load_todoufuken() data = fetch_weather(todoufuken)
TARGET_HOURS = {7, 10, 13, 16, 21} lines = ["<b>☀️ 本日の天気予報(7時以降・1時間ごと)</b>"] for i, t in enumerate(times): t_jst = ( datetime.fromisoformat(t) .replace(tzinfo=ZoneInfo("UTC")) .astimezone(JST) ) target_hours = {7, 10, 13, 16, 21} if t_jst.hour not in TARGET_HOURS: continue 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 = 0 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: continue
wc = 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}], } wc = 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 += 1 print(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>データ取得エラー") continue message2 = "☀️・・・晴れ、☁️・・・曇り、🌫️・・・霧・霧雨、🌧️・・・雨、🌨️・・・雪、🌦️・・・にわか雨、⛈️・・・雷雨" 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 body except 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 = None last_weather = None check_interval = 30 # チェック間隔(秒) while True: try: now = datetime.now(JST) current_date = now.date() current_hour = now.hour current_minute = now.minute print(f"ループチェック: {now.strftime('%Y-%m-%d %H:%M:%S')}")
# 毎正時の時報 if current_minute == 0 and last_time_signal != current_hour: try: 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.hour print(f"時報を送信しました: {now.strftime('%H:%M')}") print(f"時報送信: {current_hour}時") body = create_time_signal_body() post_group_message(TARGET_GROUP_CHAT_ID, body) last_time_signal = current_hour print(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: 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_date print("天気予報を送信しました") print("天気予報送信開始") body = create_weather_body() post_group_message(TARGET_GROUP_CHAT_ID, body) last_weather = current_date print("天気予報送信完了") 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(30) # 30秒間隔でチェック time.sleep(check_interval)
except KeyboardInterrupt: print("プログラムを終了します(Ctrl+C)") log_stats() break except Exception as e: print("Error:", e) print(f"メインループエラー: {e}\n{traceback.format_exc()}") stats["errors"] += 1 time.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接続を別スレッドで開始 # WebSocket接続を別スレッドで開始 ws_thread = threading.Thread(target=start_websocket, daemon=True) ws_thread.start() # メインループを実行 main_loop() 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