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| 4 |
+
import requests
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
+
|
| 7 |
+
# ===== Channel.io =====
|
| 8 |
+
CHANNEL_ID = "200605"
|
| 9 |
+
GROUP_ID = "534868"
|
| 10 |
+
|
| 11 |
+
GET_URL = f"https://desk-api.channel.io/desk/channels/{CHANNEL_ID}/groups/{GROUP_ID}/messages"
|
| 12 |
+
POST_URL = GET_URL
|
| 13 |
+
|
| 14 |
+
X_ACCOUNT = os.getenv("channeliotokenbot2")
|
| 15 |
+
if not X_ACCOUNT:
|
| 16 |
+
raise RuntimeError("環境変数 channeliotokenbot2 が設定されていません")
|
| 17 |
+
|
| 18 |
+
HEADERS = {
|
| 19 |
+
"accept": "application/json",
|
| 20 |
+
"accept-language": "ja",
|
| 21 |
+
"content-type": "application/json",
|
| 22 |
+
"x-account": X_ACCOUNT,
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
PARAMS = {
|
| 26 |
+
"sortOrder": "asc",
|
| 27 |
+
"limit": 50,
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
ASSISTANT_PERSON_ID = "595702"
|
| 31 |
+
|
| 32 |
+
# ===== LLM API =====
|
| 33 |
+
LLM_ENDPOINT = "https://izuemon-gpt-free-api.hf.space/v1"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ===== Utils =====
|
| 37 |
+
def parse_updated_at(value):
|
| 38 |
+
if isinstance(value, (int, float)):
|
| 39 |
+
return datetime.fromtimestamp(value / 1000, tz=timezone.utc)
|
| 40 |
+
elif isinstance(value, str):
|
| 41 |
+
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def fetch_messages():
|
| 46 |
+
res = requests.get(GET_URL, headers=HEADERS, params=PARAMS, timeout=30)
|
| 47 |
+
res.raise_for_status()
|
| 48 |
+
return res.json().get("messages", [])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def build_chat_messages(channel_messages):
|
| 52 |
+
"""
|
| 53 |
+
Channel.io → ChatGPT messages 変換
|
| 54 |
+
"""
|
| 55 |
+
chat_messages = []
|
| 56 |
+
|
| 57 |
+
for msg in channel_messages:
|
| 58 |
+
text = msg.get("plainText")
|
| 59 |
+
if not text:
|
| 60 |
+
continue
|
| 61 |
+
|
| 62 |
+
role = "assistant" if msg.get("personId") == ASSISTANT_PERSON_ID else "user"
|
| 63 |
+
chat_messages.append({
|
| 64 |
+
"role": role,
|
| 65 |
+
"content": text
|
| 66 |
+
})
|
| 67 |
+
|
| 68 |
+
return chat_messages
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def call_llm(messages):
|
| 72 |
+
payload = {
|
| 73 |
+
"model": "gpt-3.5-turbo",
|
| 74 |
+
"messages": messages
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
res = requests.post(
|
| 78 |
+
LLM_ENDPOINT,
|
| 79 |
+
headers={"Content-Type": "application/json"},
|
| 80 |
+
data=json.dumps(payload),
|
| 81 |
+
timeout=60
|
| 82 |
+
)
|
| 83 |
+
res.raise_for_status()
|
| 84 |
+
|
| 85 |
+
data = res.json()
|
| 86 |
+
return data["choices"][0]["message"]["content"]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def send_to_channel(text):
|
| 90 |
+
payload = {
|
| 91 |
+
"requestId": f"desk-web-{int(time.time() * 1000)}",
|
| 92 |
+
"blocks": [
|
| 93 |
+
{"type": "text", "value": text}
|
| 94 |
+
]
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
res = requests.post(
|
| 98 |
+
POST_URL,
|
| 99 |
+
headers=HEADERS,
|
| 100 |
+
data=json.dumps(payload),
|
| 101 |
+
timeout=30
|
| 102 |
+
)
|
| 103 |
+
res.raise_for_status()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# ===== Main =====
|
| 107 |
+
def main():
|
| 108 |
+
processed_until = None
|
| 109 |
+
|
| 110 |
+
while True:
|
| 111 |
+
try:
|
| 112 |
+
messages = fetch_messages()
|
| 113 |
+
|
| 114 |
+
# 新しいメッセージのみ抽出
|
| 115 |
+
new_messages = []
|
| 116 |
+
for msg in messages:
|
| 117 |
+
t = parse_updated_at(msg.get("updatedAt"))
|
| 118 |
+
if not t:
|
| 119 |
+
continue
|
| 120 |
+
|
| 121 |
+
if processed_until is None or t > processed_until:
|
| 122 |
+
new_messages.append(msg)
|
| 123 |
+
|
| 124 |
+
if not new_messages:
|
| 125 |
+
time.sleep(10)
|
| 126 |
+
continue
|
| 127 |
+
|
| 128 |
+
# ChatGPT 用メッセージ構築
|
| 129 |
+
chat_messages = build_chat_messages(messages)
|
| 130 |
+
|
| 131 |
+
# LLM 呼び出し
|
| 132 |
+
reply = call_llm(chat_messages)
|
| 133 |
+
|
| 134 |
+
# Channel.io に送信
|
| 135 |
+
send_to_channel(reply)
|
| 136 |
+
|
| 137 |
+
# 処理済み時刻更新
|
| 138 |
+
processed_until = max(
|
| 139 |
+
parse_updated_at(m["updatedAt"]) for m in new_messages
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
print("返信送信完了")
|
| 143 |
+
|
| 144 |
+
except Exception as e:
|
| 145 |
+
print("エラー:", e)
|
| 146 |
+
|
| 147 |
+
time.sleep(15)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
main()
|