File size: 5,714 Bytes
4de97a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df4c73a
 
 
 
 
4de97a6
 
 
 
df4c73a
4de97a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import time
import requests
from typing import List, Dict, Any, Optional

# ===== 設定 =====
X_ACCOUNT = os.getenv("orionchanneltalktoken")
if not X_ACCOUNT:
    raise RuntimeError("環境変数 orionchanneltalktoken が設定されていません")

BASE = "https://desk-api.channel.io/desk/channels/232082"
GROUP_ID = 548829
CHECK_PERSON_ID = "619110"

# accountIdベースのブラックリスト
BLACKLIST_ACCOUNT_IDS = []

HEADERS = {
    "accept": "application/json",
    "accept-language": "ja",
    "content-type": "application/json",
    "x-account": X_ACCOUNT,
}

GET_PARAMS = {
    "sortOrder": "desc",
    "limit": 34,
    "logFolded": "false",
}

WELCOME_TEMPLATE = """
おりおんるーむへようこそ。
自動でいくつかの部屋へと招待します。
💫雑談⇛みんなで会話をすることができます。
🌐宣伝⇛自分のチャネルや、新しく作成した部屋を宣伝することができます。
また、後日自動招待部屋を追加する可能性があります。その場合も手動で招待をいたします。
"""

INVITE_GROUPS = [
    548834,
    548832
]

# ===== API =====

def get_messages() -> List[Dict[str, Any]]:
    url = f"{BASE}/groups/{GROUP_ID}/messages"
    r = requests.get(url, headers=HEADERS, params=GET_PARAMS, timeout=20)
    r.raise_for_status()
    return r.json().get("messages", [])


def get_group_titles() -> Dict[int, str]:
    url = f"{BASE}/groups?limit=1000"
    response = requests.get(url, headers=HEADERS, timeout=20)
    response.raise_for_status()

    groups = response.json().get("groups", [])
    return {
        group.get("id"): group.get("title")
        for group in groups
        if "id" in group and "title" in group
    }


def get_manager_account_id(person_id: str) -> Optional[str]:
    """
    personId を使って managers API を取得し、
    managers[0].accountId を返す
    """
    url = f"{BASE}/managers"
    params = {
        "limit": 1,
        "since": person_id
    }

    r = requests.get(url, headers=HEADERS, params=params, timeout=20)
    r.raise_for_status()

    data = r.json()
    managers = data.get("managers", [])

    if not managers:
        return None

    return str(managers[0].get("accountId"))


def blacklist_manager(person_id: str) -> None:
    """
    personId を使って manager を削除
    """
    url = f"{BASE}/managers/{person_id}"
    requests.delete(url, headers=HEADERS, timeout=20).raise_for_status()
    payload = {
        "requestId": f"desk-web-{int(time.time() * 1000)}",
        "blocks": [
            {"type": "text", "value": "さようなら。"}
        ]
    }
    url = f"{BASE}/groups/{GROUP_ID}/messages"
    requests.post(url, headers=HEADERS, json=payload, timeout=20).raise_for_status()
    print(f"[INFO] personId={person_id} を削除しました")


def post_welcome_message() -> None:
    TITLES = get_group_titles()

    welcome_text = WELCOME_TEMPLATE.format(
        hq=TITLES.get(532214, "本部")
    )

    url = f"{BASE}/groups/{GROUP_ID}/messages"
    payload = {
        "requestId": f"desk-web-{int(time.time() * 1000)}",
        "blocks": [
            {"type": "text", "value": welcome_text}
        ]
    }

    requests.post(url, headers=HEADERS, json=payload, timeout=20).raise_for_status()
    print("[INFO] 歓迎メッセージを送信しました")


def invite_person(group_id: int, person_id: str) -> None:
    url = f"{BASE}/groups/{group_id}/invite"
    params = {"managerIds": person_id}
    requests.post(url, headers=HEADERS, params=params, timeout=20).raise_for_status()
    print(f"[INFO] personId={person_id} を group {group_id} に招待しました")


# ===== ロジック =====

def process():
    messages = get_messages()

    # CHECK_PERSON_ID の最新発言時刻
    latest_check_person = max(
        (int(m.get("createdAt", 0))
         for m in messages
         if str(m.get("personId")) == CHECK_PERSON_ID),
        default=0
    )

    join_targets = []
    
    for m in messages:
        log = m.get("log") or {}
        if log.get("action") != "join":
            continue
    
        created_at = int(m.get("createdAt", 0))
        person_id = str(m.get("personId", ""))
    
        # ===== ここを追加 =====
        # CHECK_PERSON_ID の最新発言より前なら無視
        if created_at <= latest_check_person:
            continue
    
        # ===== ブラックリスト判定(accountIdベース)=====
        try:
            account_id = get_manager_account_id(person_id)
        except Exception as e:
            print(f"[ERROR] manager取得失敗 personId={person_id} : {e}")
            continue
    
        if account_id and account_id in BLACKLIST_ACCOUNT_IDS:
            try:
                blacklist_manager(person_id)
            except Exception as e:
                print(f"[ERROR] 削除失敗 personId={person_id} : {e}")
            continue
    
        # ===== 通常処理 =====
        join_targets.append(person_id)
    if not join_targets:
        return

    join_targets = list(set(join_targets))

    # 歓迎メッセージは1回だけ
    post_welcome_message()

    # 招待処理
    for pid in join_targets:
        for gid in INVITE_GROUPS:
            try:
                invite_person(gid, pid)
            except Exception as e:
                print(f"[ERROR] 招待失敗 personId={pid} group={gid} : {e}")


def main():
    print("[INFO] Bot 起動(10秒間隔)")
    while True:
        try:
            process()
        except Exception as e:
            print(f"[ERROR] {e}")
        time.sleep(10)


if __name__ == "__main__":
    main()