Spaces:
Running
Running
Update join.py
Browse files8 unmodified lines91011121314151516171819202122222324252614 unmodified lines41424343444546477 unmodified lines555657575858596061134 unmodified lines1961971981992002012022012032042052064 unmodified lines2112122132122132142152162172182192202212222232242252262272282292202302312322332342232242252352362372382392402412422432442322332452462472482492502512522532542552562572372582592602612622632642652669 unmodified lines27627727825527928025728128228326028428528628728828929029129229329429529629729829930026730130230330430519 unmodified lines32532632729332832933033129833233333433533613 unmodified lines3503513523183533543552 unmodified lines3583593603273613623633643653663673683693703713723733743353753763773783793803373383393403813823833843853863873 unmodified lines3913923933503943953963973983994004014024033544044054064074084094104113614124134144154164174184194204214224234244254264273684284294304314324334344354364374384394403754414424434444454464474484494504514524534544553803814564574584594604614624633854644654663874674684694704714724 unmodified lines47747847948048148240048348448548648740240340448848949049149240740849349449541041149649749849941341450050141750250341950450550650742350850951042651151251342943051451551651743543651851952052144144252244452352452552652728 unmodified lines55655755847955956056156227 unmodified lines59059159251359359459559659714 unmodified lines61261361453461561661712 unmodified lines6306316325536336346356366373 unmodified lines64164264356364464564658 unmodified lines7057067076287087097107117129 unmodified lines72272372472572672772872973073173273373465273573673773873974020 unmodified lines7617627636797647657666826836847677687697707717722 unmodified lines7757767776937787797807817824 unmodified lines7877887897907917927937945 unmodified lines8008018028038048058068078088098108117218128138148158168 unmodified linesimport websocketimport threadingimport loggingimport ssl
# ロギングの設定logging.basicConfig( level=logging.INFO, level=logging.DEBUG, # デバッグレベルに変更 format='%(asctime)s [%(levelname)s] %(name)s: %(message)s', handlers=[ logging.FileHandler('bot.log', encoding='utf-8'), logging.StreamHandler(sys.stdout) ])
logger = logging.getLogger(__name__)
BASE_URL = "https://desk-api.channel.io/desk/channels/240996"API_URL = "https://api.channel.works/desk/channels/240996"14 unmodified linesJST = ZoneInfo("Asia/Tokyo")
# WebSocket接続管理用ws = Nonews_app = Nonews_connected = Falsews_reconnect_count = 0MAX_RECONNECT_ATTEMPTS = 107 unmodified lines "start_time": datetime.now(JST)}
# ---------------- 天気コード ----------------
# ---------------- 天気コード ---------------- (変更なし)WEATHER_CODE_MAP = { 0: "雲の発達なしまたは観測なし", 1: "雲が消散または弱まる",134 unmodified lines global ws_connected, ws_reconnect_count try: print(f"WebSocket raw message: {message[:200]}") # Socket.IOプロトコルの処理 if message == "2": # ping対応 # ping対応 - Socket.IO v4 print("WebSocket: ping受信、pong送信") ws.send("3") return4 unmodified lines return if message.startswith("0{"): # 接続確立時の初期メッセージ print(f"WebSocket: 接続確立、初期メッセージ受信: {message[:100]}...") # 接続確立時の初期メッセージ - Socket.IO v4 print(f"WebSocket: 接続確立、初期メッセージ受信") try: # 初期メッセージをパース init_data = json.loads(message[1:]) ping_interval = init_data.get("pingInterval", 60000) ping_timeout = init_data.get("pingTimeout", 25000) print(f"WebSocket: ping間隔={ping_interval}ms, ping timeout={ping_timeout}ms") # 認証情報を送信 jwt_token = os.getenv("dmsendertoken") if not jwt_token: print("WebSocket: JWT tokenが設定されていません") return # Socket.IO v4形式での認証 auth_message = f'40/desk/channel,{{"channelId":"240996","jwt":"{jwt_token}"}}' print(f"WebSocket: 認証メッセージ送信: {auth_message[:100]}...") ws.send(auth_message) ws_connected = True ws_reconnect_count = 0 print("WebSocket: 認証情報を送信しました") except json.JSONDecodeError as e: print(f"WebSocket: 初期メッセージ解析エラー: {e}") stats["errors"] += 1 except Exception as e: print(f"WebSocket: 認証情報送信エラー: {e}") stats["errors"] += 1 return if message.startswith("40"): # 認証成功 print("WebSocket: 認証成功") # 認証成功 - Socket.IO v4 print(f"WebSocket: 認証応答受信: {message[:100]}") ws_connected = True ws_reconnect_count = 0 print("WebSocket: 認証成功、接続確立") # 認証成功後、グループチャットに接続するためのメッセージを送信 # subscribe_message = f'42/desk/channel,["subscribe",{{"chatKey":"group-{TARGET_GROUP_CHAT_ID}"}}]' # ws.send(subscribe_message) # print(f"WebSocket: グループ購読メッセージ送信: {subscribe_message[:100]}") return if message.startswith("42"): # メッセージデータの処理 # メッセージデータの処理 - Socket.IO v4 try: # "42"の後にJSON配列が続く json_str = message[2:] print(f"WebSocket: データメッセージ受信: {json_str[:200]}") data = json.loads(json_str) if isinstance(data, list) and len(data) >= 2:9 unmodified lines # ユーザー参加 handle_create_event(event_data) else: print(f"WebSocket: 未処理のイベントタイプ: {event_type}") print(f"WebSocket: 未処理のイベントタイプ: {event_type}, data: {json.dumps(event_data)[:200]}") else: print(f"WebSocket: 予期しないデータ形式: {type(data)}") print(f"WebSocket: 予期しないデータ形式: {type(data)}, content: {json_str[:200]}") except json.JSONDecodeError as e: print(f"WebSocket: JSON解析エラー: {e}, データ: {json_str[:200]}") print(f"WebSocket: JSON解析エラー: {e}, データ: {message[2:200]}") stats["errors"] += 1 except Exception as e: print(f"WebSocket: メッセージ処理エラー: {e}") print(traceback.format_exc()) stats["errors"] += 1 return if message.startswith("44"): # エラーメッセージ - Socket.IO v4 print(f"WebSocket: エラーメッセージ受信: {message}") return # その他のメッセージ print(f"WebSocket: その他のメッセージ: {message[:100]}") except Exception as e: print(f"WebSocket on_message エラー: {e}\n{traceback.format_exc()}") print(f"WebSocket on_message エラー: {e}") print(traceback.format_exc()) stats["errors"] += 1
def handle_push_event(event_data):19 unmodified lines if 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()}") print(f"push イベント処理エラー: {e}") print(traceback.format_exc()) stats["errors"] += 1
def handle_create_event(event_data):13 unmodified lines 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":2 unmodified lines print(f"その他のアクション: {action}") except Exception as e: print(f"create イベント処理エラー: {e}\n{traceback.format_exc()}") print(f"create イベント処理エラー: {e}") print(traceback.format_exc()) stats["errors"] += 1
def on_error(ws, error): """WebSocketエラー時の処理""" print(f"WebSocket エラー: {error}") print(f"エラータイプ: {type(error)}") if hasattr(error, '__class__'): print(f"エラークラス: {error.__class__.__name__}") stats["errors"] += 1 if isinstance(error, ConnectionRefusedError): # エラーの種類に応じた処理 error_str = str(error) if "Connection to remote host was lost" in error_str: print("WebSocket: リモートホストとの接続が切断されました(再接続されます)") elif "Connection refused" in error_str: print("WebSocket: 接続が拒否されました") elif isinstance(error, ConnectionResetError): print("WebSocket: 接続がリセットされました") elif isinstance(error, websocket.WebSocketConnectionClosedException): print("WebSocket: 接続が閉じられています") elif "handshake" in error_str.lower(): print("WebSocket: ハンドシェイクエラー") else: print(f"WebSocket: 未分類のエラー: {error_str}")
def on_close(ws, close_status_code, close_msg): """WebSocket接続クローズ時の処理"""3 unmodified lines stats["ws_reconnects"] += 1 print(f"WebSocket 接続が閉じられました: status_code={close_status_code}, " f"message={close_msg}, reconnect_count={ws_reconnect_count}") f"message={close_msg}, reconnect_count={ws_reconnect_count}/{MAX_RECONNECT_ATTEMPTS}") if close_status_code: print(f"クローズステータスコード: {close_status_code}") if close_msg: print(f"クローズメッセージ: {close_msg}") if ws_reconnect_count > MAX_RECONNECT_ATTEMPTS: print(f"WebSocket: 最大再接続回数({MAX_RECONNECT_ATTEMPTS})を超えました") # ここで必要に応じてプログラムを終了するなどの処理 # システム管理者への通知などをここに追加
def on_open(ws): """WebSocket接続開始��の処理""" global ws_reconnect_count print("WebSocket 接続が開かれました") print(f"接続URL: {WEBSOCKET_URL}") ws_reconnect_count = 0 log_stats()
def on_ping(ws, message): """WebSocket ping受信時の処理""" print(f"WebSocket ping受信: {message}")
def on_pong(ws, message): """WebSocket pong受信時の処理""" print(f"WebSocket pong受信: {message}")
def start_websocket(): """WebSocket接続を開始""" global ws_app print(f"WebSocket接続を開始します: {WEBSOCKET_URL}") try: websocket.enableTrace(False) # デバッグ用にTrueにすると詳細なトレースが表示されます # WebSocketのデバッグトレースを有効化(問題解決後はFalseに) websocket.enableTrace(True) # SSL設定(必要に応じて) ssl_opt = { "cert_reqs": ssl.CERT_NONE, # 開発環境用。本番環境では適切な証明書検証を行うこと } ws_app = websocket.WebSocketApp( WEBSOCKET_URL, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close on_close=on_close, on_ping=on_ping, on_pong=on_pong ) # カスタムヘッダーの設定(必要な場合) ws_app.header = { "Origin": "https://desk.channel.io", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" } print("WebSocket: run_foreverを開始します") # 永続的に接続を維持 ws_app.run_forever( ping_interval=30, ping_timeout=10, ping_interval=30, # 30秒間隔でping ping_timeout=10, # 10秒でタイムアウト ping_payload="2", # Socket.IO v4のping形式 sslopt=ssl_opt, reconnect=5 # 5秒後に再接続 ) except Exception as e: print(f"WebSocket接続の開始に失敗: {e}\n{traceback.format_exc()}") print(f"WebSocket接続の開始に失敗: {e}") print(traceback.format_exc()) stats["errors"] += 1 raise # 重要なエラーの場合は再試行 time.sleep(10) start_websocket() # 再帰的に再試行
# ---------------- メッセージ送信 ----------------
4 unmodified lines for attempt in range(retry_count): try: print(f"メッセージ送信試行: chat_id={chat_id}, attempt={attempt + 1}/{retry_count}") print(f"送信URL: {url}") print(f"送信データ: {json.dumps(body, ensure_ascii=False)[:200]}") r = requests.post(url, headers=HEADERS, json=body, timeout=10) response = requests.post(url, headers=HEADERS, json=body, timeout=10) print(f"レスポンスステータス: {response.status_code}") print(f"レスポンスボディ: {response.text[:200]}") if r.status_code == 200: response_data = r.json() print(f"メッセージ送信成功: chat_id={chat_id}, status={r.status_code}") if response.status_code == 200: response_data = response.json() print(f"メッセージ送信成功: chat_id={chat_id}") stats["messages_sent"] += 1 return response_data elif r.status_code == 401: print(f"認証エラー: status={r.status_code}, response={r.text[:200]}") elif response.status_code == 401: print(f"認証エラー: status={response.status_code}") raise Exception("認証エラー: APIキーが無効です") elif r.status_code == 429: print(f"レート制限: status={r.status_code}, {attempt + 1}回目の試行") elif response.status_code == 429: wait_time = (attempt + 1) * 5 print(f"レート制限: {wait_time}秒待機") if attempt < retry_count - 1: wait_time = (attempt + 1) * 5 print(f"{wait_time}秒待機してからリトライします") time.sleep(wait_time) else: print("レート制限により送信失敗(最大リトライ回数超過)") raise Exception("レート制限により送信失敗") else: print(f"メッセージ送信エラー: status={r.status_code}, response={r.text[:200]}") print(f"送信エラー: status={response.status_code}, body={response.text[:200]}") if attempt < retry_count - 1: time.sleep(2) else: r.raise_for_status() response.raise_for_status() except requests.exceptions.Timeout: print(f"リクエストタイムアウト: {url}, attempt={attempt + 1}") print(f"リクエストタイムアウト: 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()}") print(f"予期しない送信エラー: {e}") print(traceback.format_exc()) stats["errors"] += 1 raise 28 unmodified lines print(f"時報メッセージ作成エラー: {e}") raise
# ---------------- 天気予報 ----------------# ---------------- 天気予報 ---------------- (変更なし)
def load_todoufuken(): """都道府県データを読み込み"""27 unmodified lines print(f"JSON解析エラー: {e}") raise except Exception as e: print(f"都道府県データ読み込みエラー: {e}\n{traceback.format_exc()}") print(f"都道府県データ読み込みエラー: {e}") print(traceback.format_exc()) raise
14 unmodified lines )
print(f"天気データ取得開始: {len(todoufuken)}地点") print(f"API URL: {url[:200]}...") r = requests.get(url, timeout=30) r.raise_for_status()12 unmodified lines print(f"天気API: リクエストエラー: {e}") raise except Exception as e: print(f"天気データ取得エラー: {e}\n{traceback.format_exc()}") print(f"天気データ取得エラー: {e}") print(traceback.format_exc()) raise
3 unmodified lines print("天気予報メッセージ作成開始") now = datetime.now(JST) today_7am = now.replace(hour=7, minute=0, second=0, microsecond=0)
todoufuken = load_todoufuken() data = fetch_weather(todoufuken)58 unmodified lines return body except Exception as e: print(f"天気予報メッセージ作成エラー: {e}\n{traceback.format_exc()}") print(f"天気予報メッセージ作成エラー: {e}") print(traceback.format_exc()) # エラー時のフォールバックメッセージ return { "requestId": f"desk-web-weather-error-{int(time.time())}",9 unmodified lines last_time_signal = None last_weather = None check_interval = 30 # チェック間隔(秒) loop_count = 0 while True: try: loop_count += 1 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 loop_count % 20 == 0: # 10分ごとに詳細ログ print(f"ループ実行中: カウント={loop_count}, 時刻={now.strftime('%Y-%m-%d %H:%M:%S')}, " f"接続状態={ws_connected}")
# 毎正時の時報 if current_minute == 0 and last_time_signal != current_hour:20 unmodified lines stats["errors"] += 1
# 1時間ごとに統計情報をログ出力 if current_minute == 0: if current_minute == 0 and current_hour != last_time_signal: log_stats() # エラーが多い場合は警告 if stats["errors"] > 100: print(f"エラー数が100を超えました: {stats['errors']}") # WebSocket接続状態の監視 if not ws_connected and loop_count % 10 == 0: print(f"WebSocketが未接続状態です(再接続試行中: {ws_reconnect_count})")
time.sleep(check_interval)
2 unmodified lines log_stats() break except Exception as e: print(f"メインループエラー: {e}\n{traceback.format_exc()}") print(f"メインループエラー: {e}") print(traceback.format_exc()) stats["errors"] += 1 time.sleep(10)
4 unmodified lines 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}") print(f"WebSocket URL: {WEBSOCKET_URL}") print(f"環境変数 dmsendertoken: {'設定済み' if DMSENDER_TOKEN else '未設定'} ({len(DMSENDER_TOKEN)}文字)") # 起動時の環境チェック if not os.path.exists("todoufuken.json"):5 unmodified lines ws_thread.start() print(f"WebSocketスレッドを開始しました: {ws_thread.name}") # WebSocketの接続確立を待機 time.sleep(2) # メインループを実行 main_loop() except KeyboardInterrupt: print("プログラムを終了します") except Exception as e: print(f"致命的なエラーが発生しました: {e}\n{traceback.format_exc()}") print(f"致命的なエラーが発生しました: {e}") print(traceback.format_exc()) sys.exit(1) finally: print("=== ボット終了 ===")join.py+163-71