izuemon commited on
Commit
a6a1daf
·
verified ·
1 Parent(s): 29a57f2

Update chatgpt.py

Browse files
Files changed (1) hide show
  1. chatgpt.py +30 -51
chatgpt.py CHANGED
@@ -2,11 +2,10 @@ import os
2
  import time
3
  import json
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
@@ -29,37 +28,27 @@ PARAMS = {
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
@@ -67,15 +56,14 @@ def build_chat_messages(channel_messages):
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
@@ -85,13 +73,12 @@ def call_llm(messages):
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(
@@ -102,50 +89,42 @@ def send_to_channel(text):
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()
 
2
  import time
3
  import json
4
  import requests
 
5
 
6
+ # ===== Channel.io 設定 =====
 
7
  GROUP_ID = "534868"
8
+ CHANNEL_ID = "200605"
9
 
10
  GET_URL = f"https://desk-api.channel.io/desk/channels/{CHANNEL_ID}/groups/{GROUP_ID}/messages"
11
  POST_URL = GET_URL
 
28
 
29
  ASSISTANT_PERSON_ID = "595702"
30
 
31
+ # ===== ChatGPT互換API =====
32
+ CHAT_API_URL = "https://izuemon-gpt-free-api.hf.space/v1/chat/completions"
 
33
 
34
  # ===== Utils =====
35
+ def fetch_channel_messages():
 
 
 
 
 
 
 
 
36
  res = requests.get(GET_URL, headers=HEADERS, params=PARAMS, timeout=30)
37
  res.raise_for_status()
38
  return res.json().get("messages", [])
39
 
40
+ def build_chat_messages(messages):
 
 
 
 
41
  chat_messages = []
42
 
43
+ for msg in messages:
44
  text = msg.get("plainText")
45
+ person_id = msg.get("personId")
46
+
47
  if not text:
48
  continue
49
 
50
+ role = "assistant" if person_id == ASSISTANT_PERSON_ID else "user"
51
+
52
  chat_messages.append({
53
  "role": role,
54
  "content": text
 
56
 
57
  return chat_messages
58
 
59
+ def call_chat_api(chat_messages):
 
60
  payload = {
61
  "model": "gpt-3.5-turbo",
62
+ "messages": chat_messages,
63
  }
64
 
65
  res = requests.post(
66
+ CHAT_API_URL,
67
  headers={"Content-Type": "application/json"},
68
  data=json.dumps(payload),
69
  timeout=60
 
73
  data = res.json()
74
  return data["choices"][0]["message"]["content"]
75
 
 
76
  def send_to_channel(text):
77
  payload = {
78
  "requestId": f"desk-web-{int(time.time() * 1000)}",
79
  "blocks": [
80
  {"type": "text", "value": text}
81
+ ],
82
  }
83
 
84
  res = requests.post(
 
89
  )
90
  res.raise_for_status()
91
 
 
92
  # ===== Main =====
93
  def main():
94
+ processed = set()
95
 
96
  while True:
97
  try:
98
+ messages = fetch_channel_messages()
99
 
100
+ if not messages:
101
+ time.sleep(10)
102
+ continue
 
 
 
103
 
104
+ # 最新メッセージをトリガーにする
105
+ latest = messages[-1]
106
+ msg_id = latest.get("id")
107
 
108
+ if msg_id in processed:
109
  time.sleep(10)
110
  continue
111
 
 
112
  chat_messages = build_chat_messages(messages)
113
 
114
+ if not chat_messages:
115
+ processed.add(msg_id)
116
+ continue
117
 
118
+ reply = call_chat_api(chat_messages)
119
  send_to_channel(reply)
120
 
121
+ processed.add(msg_id)
122
+ print("送信完了")
 
 
 
 
123
 
124
  except Exception as e:
125
  print("エラー:", e)
126
 
127
  time.sleep(15)
128
 
 
129
  if __name__ == "__main__":
130
  main()