Spaces:
Running
Running
File size: 7,921 Bytes
1394d41 60437d5 b8ab9ee 60437d5 1394d41 60437d5 1394d41 60437d5 1394d41 b98f5e1 1394d41 f09d967 b98f5e1 60437d5 49f1f09 b8ab9ee 60437d5 b8ab9ee 60437d5 b8ab9ee dc4b507 b8ab9ee 60437d5 1394d41 60437d5 1394d41 f09d967 1394d41 f09d967 1394d41 f09d967 1394d41 f09d967 1394d41 548d87d 1394d41 60437d5 b8ab9ee 60437d5 1394d41 60437d5 1394d41 60437d5 1394d41 f09d967 b8ab9ee 60437d5 f09d967 60437d5 b8ab9ee 60437d5 b8ab9ee 60437d5 b8ab9ee 60437d5 1394d41 60437d5 b8ab9ee 60437d5 b8ab9ee 60437d5 b8ab9ee 60437d5 1394d41 93f0bdc 1394d41 60437d5 b8ab9ee 60437d5 b8ab9ee f09d967 60437d5 1394d41 b8ab9ee 60437d5 b8ab9ee 60437d5 b8ab9ee 60437d5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | # 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() |