Spaces:
Running
Running
Download v2_gpt.py from izuemon/any-env-code: direct link, hf CLI and curl.
- Browser
- Download file 7.92 kB
-
https://huggingface.co/spaces/izuemon/any-env-code/resolve/main/v2_gpt.py
- Command line
-
hf download hf://spaces/izuemon/any-env-code/v2_gpt.py
-
curl -L -o v2_gpt.py https://huggingface.co/spaces/izuemon/any-env-code/resolve/main/v2_gpt.py
7.92 kB
| # main_janken.py | |
| import json | |
| import os | |
| import random | |
| import string | |
| import threading | |
| import time | |
| import traceback | |
| from datetime import datetime | |
| import requests | |
| from channel_auth import ChannelWorksClient | |
| from channel_msg import ChannelMessenger | |
| # --------------------------------------------------------------------------- | |
| # ่จญๅฎ | |
| # --------------------------------------------------------------------------- | |
| CW_EMAIL = os.environ["CW_EMAIL"] | |
| CW_PASSWORD = os.environ["CW_PASSWORD"] | |
| ROOM_ID = "241135" | |
| TARGET_CHAT_ID = "574798" | |
| GROUP_PATH = f"/groups/{TARGET_CHAT_ID}" | |
| # ใใใใใใฎๆ | |
| HANDS = ["โ", "โ", "โ"] | |
| # ๆใฎๅผทใ: โ=0, โ=1, โ=2 (ใฐใผ<ใใงใญ<ใใผ<ใฐใผ) | |
| HAND_INDEX = {h: i for i, h in enumerate(HANDS)} | |
| TRIGGER_WORDS = [ | |
| "ใใใใใ", "ใธใฃใณใฑใณ", | |
| "ใใใใใใฝใ", "ใธใฃใณใฑใณใใณ", | |
| "ใใใใใใฝใ", "ใธใฃใณใฑใณใใค", | |
| "ใใใใใใปใ", "ใธใฃใณใฑใณใใค", | |
| ] | |
| CHANNEL_SEND_URL = ( | |
| f"https://api.channel.works/desk/channels/{ROOM_ID}" | |
| f"/groups/{TARGET_CHAT_ID}/messages" | |
| ) | |
| LOG_LEVEL = ChannelWorksClient.LOG_ERROR | |
| # --------------------------------------------------------------------------- | |
| # ใญใฌใผ | |
| # --------------------------------------------------------------------------- | |
| def log(tag: str, msg: str) -> None: | |
| ts = datetime.now().strftime("%m-%d %H:%M:%S.%f")[:-3] | |
| print(f"[{ts}] [{tag}] {msg}", flush=True) | |
| def _make_request_id() -> str: | |
| suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=4)) | |
| return f"desk-web-{int(time.time() * 1000)}{suffix}" | |
| # --------------------------------------------------------------------------- | |
| # ใใใใใๅคๅฎ | |
| # --------------------------------------------------------------------------- | |
| def detect_user_hand(text: str) -> str | None: | |
| """ใกใใปใผใธๆฌๆใใใฆใผใถใผใๅบใใๆ(็ตตๆๅญ)ใๆขใใ""" | |
| for h in HANDS: | |
| if h in text: | |
| return h | |
| return None | |
| def has_trigger_word(text: str) -> bool: | |
| """ใใใใใใไฟใใญใผใฏใผใใๅซใพใใฆใใใใ""" | |
| return any(w in text for w in TRIGGER_WORDS) | |
| def judge(my_hand: str, user_hand: str) -> str: | |
| """ | |
| ่ชๅใฎๆใจ็ธๆใฎๆใใๅๆใกใใปใผใธใ่ฟใใ | |
| โ(0) < โ(1) < โ(2) < โ(0) ใฎไธใใใฟใ | |
| (my - user) % 3 == 1 ใชใ่ชๅ(ใใใ)ใฎๅใก | |
| (my - user) % 3 == 2 ใชใ็ธๆใฎๅใก | |
| 0 ใชใใใใ | |
| """ | |
| diff = (HAND_INDEX[my_hand] - HAND_INDEX[user_hand]) % 3 | |
| if diff == 0: | |
| return "ใใใ" | |
| if diff == 2: | |
| return "็งใฎๅใก๏ผ" | |
| return "ใใชใใฎๅใก๏ผ" | |
| def make_reply(user_hand: str) -> str: | |
| """ใฉใณใใ ใชๆใๅบใใฆๅๆใกใใปใผใธใ็ๆใใใ""" | |
| my_hand = random.choice(HANDS) | |
| result = judge(my_hand, user_hand) | |
| return f"{my_hand} {result}" | |
| # --------------------------------------------------------------------------- | |
| # Channel ้ไฟก | |
| # --------------------------------------------------------------------------- | |
| def send_channel_message(client: ChannelWorksClient, text: str) -> requests.Response: | |
| tokens = client.get_tokens() or {} | |
| x_account = tokens.get("x-account") or "" | |
| x_account_refresh = tokens.get("x-account-refresh") or "" | |
| cookie_parts = [] | |
| if x_account: | |
| cookie_parts.append(f"x-account={x_account}") | |
| if x_account_refresh: | |
| cookie_parts.append(f"x-account-refresh={x_account_refresh}") | |
| cookie_parts.append("x-account-refresh-bound=false") | |
| cookie_header = "; ".join(cookie_parts) | |
| headers = { | |
| "accept": "application/json", | |
| "accept-language": "ja", | |
| "content-type": "application/json", | |
| "x-account": x_account, | |
| "Cookie": cookie_header, | |
| "Referer": "https://channel.works/", | |
| "Origin": "https://channel.works", | |
| "User-Agent": ( | |
| "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " | |
| "AppleWebKit/537.36 (KHTML, like Gecko) " | |
| "Chrome/152.0.0.0 Safari/537.36" | |
| ), | |
| } | |
| body = { | |
| "requestId": _make_request_id(), | |
| "blocks": [{"type": "text", "value": text}], | |
| "buttons": None, | |
| "form": None, | |
| "webPage": None, | |
| "files": None, | |
| "customPayload": None, | |
| } | |
| log("SEND-REQ", f"POST {CHANNEL_SEND_URL} text={text!r}") | |
| resp = requests.post( | |
| CHANNEL_SEND_URL, | |
| headers=headers, | |
| data=json.dumps(body, ensure_ascii=False).encode("utf-8"), | |
| timeout=30, | |
| ) | |
| log("SEND-RES", f"status={resp.status_code}") | |
| return resp | |
| # --------------------------------------------------------------------------- | |
| # ใกใคใณ | |
| # --------------------------------------------------------------------------- | |
| def main() -> None: | |
| log("BOOT", f"room_id={ROOM_ID} / target_chat_id={TARGET_CHAT_ID}") | |
| log("AUTH", "ChannelWorksClient ๅๆๅ") | |
| client = ChannelWorksClient( | |
| room_id=ROOM_ID, | |
| email=CW_EMAIL, | |
| password=CW_PASSWORD, | |
| log_level=LOG_LEVEL, | |
| ) | |
| client.login() | |
| log("AUTH", "login() ๅฎไบ") | |
| client.start_auto_touch() | |
| log("AUTH", "auto_touch ้ๅง") | |
| my_account_id = str(getattr(client, "_account_id", "") or "") | |
| log("AUTH", f"my_account_id={my_account_id}") | |
| seen_ids: set[str] = set() | |
| seen_lock = threading.Lock() | |
| # ้่คใป้ฃๆ้ฒๆญข็จ | |
| def on_push(wrapper: dict) -> None: | |
| if wrapper.get("event") != "create": | |
| return | |
| entity = wrapper.get("entity") or {} | |
| chat_id = str(entity.get("chatId") or "") | |
| person_id = str(entity.get("personId") or "") | |
| msg_id = entity.get("id") or "" | |
| plain = entity.get("plainText") or "" | |
| if chat_id != TARGET_CHAT_ID: | |
| return | |
| if person_id and my_account_id and person_id == my_account_id: | |
| return | |
| if msg_id: | |
| with seen_lock: | |
| if msg_id in seen_ids: | |
| return | |
| seen_ids.add(msg_id) | |
| if len(seen_ids) > 2000: | |
| seen_ids.clear() | |
| if not plain.strip(): | |
| return | |
| # ใใใใใใใ็ณปใฏใผใ + ๆใฎ็ตตๆๅญใๅซใพใใฆใใใๅคๅฎ | |
| if not has_trigger_word(plain): | |
| return | |
| user_hand = detect_user_hand(plain) | |
| if user_hand is None: | |
| log("PUSH-SKIP", "ๆใฎ็ตตๆๅญใชใ") | |
| return | |
| reply = make_reply(user_hand) | |
| log("REPLY", f"user={user_hand} -> {reply!r}") | |
| try: | |
| resp = send_channel_message(client, reply) | |
| if not 200 <= resp.status_code < 300: | |
| log("SEND-NG", f"status={resp.status_code} body={resp.text[:300]}") | |
| except Exception as exc: | |
| log("SEND-ERR", f"{exc!r}") | |
| traceback.print_exc() | |
| log("WS", "ChannelMessenger ๅๆๅ") | |
| messenger = ChannelMessenger( | |
| client=client, | |
| channel_id=ROOM_ID, | |
| group_path=GROUP_PATH, | |
| log_level=LOG_LEVEL, | |
| on_push=on_push, | |
| ) | |
| log("WS", "start() ๅผใณๅบใ") | |
| try: | |
| messenger.start() | |
| except Exception as exc: | |
| log("WS-ERR", f"start() ๅคฑๆ: {exc!r}") | |
| traceback.print_exc() | |
| return | |
| log("WS", f"start() ๅฎไบ running={messenger.is_running()}") | |
| def watchdog() -> None: | |
| while True: | |
| time.sleep(30) | |
| if not messenger.is_running(): | |
| log("WATCH", "ChannelMessenger ใๅๆญขใใฆใใพใ๏ผ") | |
| break | |
| threading.Thread(target=watchdog, daemon=True).start() | |
| try: | |
| messenger.wait() | |
| except KeyboardInterrupt: | |
| log("WS", "KeyboardInterrupt") | |
| finally: | |
| messenger.stop() | |
| client.stop_auto_touch() | |
| log("WS", "็ตไบ") | |
| if __name__ == "__main__": | |
| main() |