Spaces:
Running
Running
Update join.py
Browse files8 unmodified lines91011121314151617181920212223242514 unmodified lines404142434445467 unmodified lines5455565758596061134 unmodified lines1961971981992002012022032044 unmodified lines2092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412429 unmodified lines25225325425525625725825926026126226326426526626726826927019 unmodified lines29029129229329429529629729829930030113 unmodified lines3153163173183193203212 unmodified lines3243253263273283293303313323333343353363373383393403413423433 unmodified lines3473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893904 unmodified lines39539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644728 unmodified lines47647747847948048148227 unmodified lines51051151251351451551614 unmodified lines53153253353453553653712 unmodified lines5505515525535545555563 unmodified lines56056156256356456556658 unmodified lines6256266276286296306319 unmodified lines64164264364464564664764864965065165265365465520 unmodified lines6766776786796806816826836846856866872 unmodified lines6906916926936946956964 unmodified lines7017027037047057065 unmodified lines7127137147157167177187197207217227237248 unmodified linesimport 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"14 unmodified linesJST = ZoneInfo("Asia/Tokyo")# WebSocket接続管理用ws = Nonews_connected = Falsews_reconnect_count = 0MAX_RECONNECT_ATTEMPTS = 107 unmodified lines"start_time": datetime.now(JST)}# ---------------- 天気コード ----------------WEATHER_CODE_MAP = {0: "雲の発達なしまたは観測なし",1: "雲が消散または弱まる",134 unmodified linesglobal ws_connected, ws_reconnect_counttry:# Socket.IOプロトコルの処理if message == "2":# ping対応print("WebSocket: ping受信、pong送信")ws.send("3")return4 unmodified linesreturnif 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"):# 認証成功print("WebSocket: 認証成功")returnif message.startswith("42"):# メッセージデータの処理try:json_str = message[2:]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}")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):19 unmodified linesif 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):13 unmodified linesif 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 linesprint(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接続クローズ時の処理"""3 unmodified linesstats["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# ---------------- メッセージ送信 ----------------4 unmodified linesfor 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"] += 1raise28 unmodified linesprint(f"時報メッセージ作成エラー: {e}")raise# ---------------- 天気予報 ----------------def load_todoufuken():"""都道府県データを読み込み"""27 unmodified linesprint(f"JSON解析エラー: {e}")raiseexcept Exception as e:print(f"都道府県データ読み込みエラー: {e}\n{traceback.format_exc()}")raise14 unmodified lines)print(f"天気データ取得開始: {len(todoufuken)}地点")print(f"API URL: {url[:200]}...")r = requests.get(url, timeout=30)r.raise_for_status()12 unmodified linesprint(f"天気API: リクエストエラー: {e}")raiseexcept Exception as e:print(f"天気データ取得エラー: {e}\n{traceback.format_exc()}")raise3 unmodified linesprint("天気予報メッセージ作成開始")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 linesreturn bodyexcept Exception as e:print(f"天気予報メッセージ作成エラー: {e}\n{traceback.format_exc()}")# エラー時のフォールバックメッセージreturn {"requestId": f"desk-web-weather-error-{int(time.time())}",9 unmodified lineslast_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:20 unmodified linesstats["errors"] += 1# 1時間ごとに統計情報をログ出力if current_minute == 0:log_stats()# エラーが多い場合は警告if stats["errors"] > 100:print(f"エラー数が100を超えました: {stats['errors']}")time.sleep(check_interval)2 unmodified lineslog_stats()breakexcept Exception as e:print(f"メインループエラー: {e}\n{traceback.format_exc()}")stats["errors"] += 1time.sleep(10)4 unmodified linesprint(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"):5 unmodified linesws_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("=== ボット終了 ===")8 unmodified lines9101112131415161718192021222324252614 unmodified lines414243444546477 unmodified lines55565758596061134 unmodified lines1961971981992002012022032042052064 unmodified lines2112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652669 unmodified lines27627727827928028128228328428528628728828929029129229329429529629729829930030130230330430519 unmodified lines32532632732832933033133233333433533613 unmodified lines3503513523533543552 unmodified lines3583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873 unmodified lines3913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724 unmodified lines47747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652728 unmodified lines55655755855956056156227 unmodified lines59059159259359459559659714 unmodified lines61261361461561661712 unmodified lines6306316326336346356366373 unmodified lines64164264364464564658 unmodified lines7057067077087097107117129 unmodified lines72272372472572672772872973073173273373473573673773873974020 unmodified lines7617627637647657667677687697707717722 unmodified lines7757767777787797807817824 unmodified lines7877887897907917927937945 unmodified lines8008018028038048058068078088098108118128138148158168 unmodified linesimport websocketimport threadingimport loggingimport ssl# ロギングの設定logging.basicConfig(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_app = Nonews_connected = Falsews_reconnect_count = 0MAX_RECONNECT_ATTEMPTS = 107 unmodified lines"start_time": datetime.now(JST)}# ---------------- 天気コード ---------------- (変更なし)WEATHER_CODE_MAP = {0: "雲の発達なしまたは観測なし",1: "雲が消散または弱まる",134 unmodified linesglobal ws_connected, ws_reconnect_counttry:print(f"WebSocket raw message: {message[:200]}")# Socket.IOプロトコルの処理if message == "2":# ping対応 - Socket.IO v4print("WebSocket: ping受信、pong送信")ws.send("3")return4 unmodified linesreturnif message.startswith("0{"):# 接続確立時の初期メッセージ - Socket.IO v4print(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)except json.JSONDecodeError as e:print(f"WebSocket: 初期メッセージ解析エラー: {e}")stats["errors"] += 1except Exception as e:print(f"WebSocket: 認証情報送信エラー: {e}")stats["errors"] += 1returnif message.startswith("40"):# 認証成功 - Socket.IO v4print(f"WebSocket: 認証応答受信: {message[:100]}")ws_connected = Truews_reconnect_count = 0print("WebSocket: 認証成功、接続確立")# 認証成功後、グループチャットに接続するためのメッセージを送信# subscribe_message = f'42/desk/channel,["subscribe",{{"chatKey":"group-{TARGET_GROUP_CHAT_ID}"}}]'# ws.send(subscribe_message)# print(f"WebSocket: グループ購読メッセージ送信: {subscribe_message[:100]}")returnif message.startswith("42"):# メッセージデータの処理 - Socket.IO v4try:# "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}, data: {json.dumps(event_data)[:200]}")else:print(f"WebSocket: 予期しないデータ形式: {type(data)}, content: {json_str[:200]}")except json.JSONDecodeError as e:print(f"WebSocket: JSON解析エラー: {e}, データ: {message[2:200]}")stats["errors"] += 1except Exception as e:print(f"WebSocket: メッセージ処理エラー: {e}")print(traceback.format_exc())stats["errors"] += 1returnif message.startswith("44"):# エラーメッセージ - Socket.IO v4print(f"WebSocket: エラーメッセージ受信: {message}")return# その他のメッセージprint(f"WebSocket: その他のメッセージ: {message[:100]}")except Exception as e:print(f"WebSocket on_message エラー: {e}")print(traceback.format_exc())stats["errors"] += 1def handle_push_event(event_data):19 unmodified linesif 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}")print(traceback.format_exc())stats["errors"] += 1def handle_create_event(event_data):13 unmodified linesif 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 linesprint(f"その他のアクション: {action}")except Exception as e:print(f"create イベント処理エラー: {e}")print(traceback.format_exc())stats["errors"] += 1def 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# エラーの種類に応じた処理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 "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 linesstats["ws_reconnects"] += 1print(f"WebSocket 接続が閉じられました: status_code={close_status_code}, "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_countprint("WebSocket 接続が開かれました")print(f"接続URL: {WEBSOCKET_URL}")ws_reconnect_count = 0def 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_appprint(f"WebSocket接続を開始します: {WEBSOCKET_URL}")try:# 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_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, # 30秒間隔でpingping_timeout=10, # 10秒でタイムアウトping_payload="2", # Socket.IO v4のping形式sslopt=ssl_opt,reconnect=5 # 5秒後に再接続)except Exception as e:print(f"WebSocket接続の開始に失敗: {e}")print(traceback.format_exc())stats["errors"] += 1# 重要なエラーの場合は再試行time.sleep(10)start_websocket() # 再帰的に再試行# ---------------- メッセージ送信 ----------------4 unmodified linesfor 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]}")response = requests.post(url, headers=HEADERS, json=body, timeout=10)print(f"レスポンスステータス: {response.status_code}")print(f"レスポンスボディ: {response.text[:200]}")if response.status_code == 200:response_data = response.json()print(f"メッセージ送信成功: chat_id={chat_id}")stats["messages_sent"] += 1return response_dataelif response.status_code == 401:print(f"認証エラー: status={response.status_code}")raise Exception("認証エラー: APIキーが無効です")elif response.status_code == 429:wait_time = (attempt + 1) * 5print(f"レート制限: {wait_time}秒待機")if attempt < retry_count - 1:time.sleep(wait_time)else:raise Exception("レート制限により送信失敗")else:print(f"送信エラー: status={response.status_code}, body={response.text[:200]}")if attempt < retry_count - 1:time.sleep(2)else:response.raise_for_status()except requests.exceptions.Timeout:print(f"リクエストタイムアウト: attempt={attempt + 1}")if attempt < retry_count - 1:time.sleep(2)except requests.exceptions.ConnectionError as e:print(f"接続エラー: {e}, attempt={attempt + 1}")if attempt < retry_count - 1:time.sleep(5)except requests.exceptions.RequestException as e:print(f"リクエストエラー: {e}, attempt={attempt + 1}")if attempt < retry_count - 1:time.sleep(2)except Exception as e:print(f"予期しない送信エラー: {e}")print(traceback.format_exc())stats["errors"] += 1raise28 unmodified linesprint(f"時報メッセージ作成エラー: {e}")raise# ---------------- 天気予報 ---------------- (変更なし)def load_todoufuken():"""都道府県データを読み込み"""27 unmodified linesprint(f"JSON解析エラー: {e}")raiseexcept Exception as e:print(f"都道府県データ読み込みエラー: {e}")print(traceback.format_exc())raise14 unmodified lines)print(f"天気データ取得開始: {len(todoufuken)}地点")r = requests.get(url, timeout=30)r.raise_for_status()12 unmodified linesprint(f"天気API: リクエストエラー: {e}")raiseexcept Exception as e:print(f"天気データ取得エラー: {e}")print(traceback.format_exc())raise3 unmodified linesprint("天気予報メッセージ作成開始")now = datetime.now(JST)todoufuken = load_todoufuken()data = fetch_weather(todoufuken)58 unmodified linesreturn bodyexcept Exception as e:print(f"天気予報メッセージ作成エラー: {e}")print(traceback.format_exc())# エラー時のフォールバックメッセージreturn {"requestId": f"desk-web-weather-error-{int(time.time())}",9 unmodified lineslast_time_signal = Nonelast_weather = Nonecheck_interval = 30 # チェック間隔(秒)loop_count = 0while True:try:loop_count += 1now = datetime.now(JST)current_date = now.date()current_hour = now.hourcurrent_minute = now.minuteif 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 linesstats["errors"] += 1# 1時間ごとに統計情報をログ出力if current_minute == 0 and current_hour != last_time_signal:log_stats()# WebSocket接続状態の監視if not ws_connected and loop_count % 10 == 0:print(f"WebSocketが未接続状態です(再接続試行中: {ws_reconnect_count})")time.sleep(check_interval)2 unmodified lineslog_stats()breakexcept Exception as e:print(f"メインループエラー: {e}")print(traceback.format_exc())stats["errors"] += 1time.sleep(10)4 unmodified linesprint(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 linesws_thread.start()print(f"WebSocketスレッドを開始しました: {ws_thread.name}")# WebSocketの接続確立を待機time.sleep(2)# メインループを実行main_loop()except KeyboardInterrupt:print("プログラムを終了します")except Exception as e:print(f"致命的なエラーが発生しました: {e}")print(traceback.format_exc())sys.exit(1)finally:print("=== ボット終了 ===")
join.py+163-71