izuemon commited on
Commit
8d9f526
·
verified ·
1 Parent(s): 849af15

Update chatgpt.py

Browse files
Files changed (1) hide show
  1. chatgpt.py +58 -45
chatgpt.py CHANGED
@@ -2,13 +2,19 @@ import os
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 = f"https://desk-api.channel.io/desk/channels/{CHANNEL_ID}/groups/{GROUP_ID}/messages"
 
 
 
 
 
12
 
13
  X_ACCOUNT = os.getenv("channeliotokenbot2")
14
  if not X_ACCOUNT:
@@ -21,27 +27,32 @@ HEADERS = {
21
  "x-account": X_ACCOUNT,
22
  }
23
 
24
- PARAMS = {
25
- "sortOrder": "asc", # 昇順で取得
26
- "limit": 50,
27
- "logFolded": "false"
28
- }
29
-
30
  ASSISTANT_PERSON_ID = "595702"
31
 
32
- # ===== ChatGPT互換API =====
33
- CHAT_API_URL = "https://izuemon-gpt-free-api.hf.space/v1/chat/completions"
 
 
 
 
34
 
35
  # ===== Utils =====
36
- def fetch_channel_messages():
 
 
 
 
 
 
37
  res = requests.get(GET_URL, headers=HEADERS, params=PARAMS, timeout=30)
38
  res.raise_for_status()
39
  return res.json().get("messages", [])
40
 
41
- def build_chat_messages(messages, limit=10):
 
42
  chat_messages = []
43
 
44
- for msg in messages[-limit:]:
45
  text = msg.get("plainText")
46
  person_id = msg.get("personId")
47
 
@@ -57,16 +68,16 @@ def build_chat_messages(messages, limit=10):
57
 
58
  return chat_messages
59
 
60
- def call_chat_api(chat_messages):
 
61
  payload = {
62
  "model": "gpt-3.5-turbo",
63
- "messages": chat_messages,
64
- "temperature": 0.7,
65
  }
66
 
67
  res = requests.post(
68
- CHAT_API_URL,
69
- headers={"Content-Type": "application/json"},
70
  data=json.dumps(payload),
71
  timeout=60
72
  )
@@ -75,12 +86,13 @@ def call_chat_api(chat_messages):
75
  data = res.json()
76
  return data["choices"][0]["message"]["content"]
77
 
 
78
  def send_to_channel(text):
79
  payload = {
80
  "requestId": f"desk-web-{int(time.time() * 1000)}",
81
  "blocks": [
82
  {"type": "text", "value": text}
83
- ],
84
  }
85
 
86
  res = requests.post(
@@ -91,54 +103,55 @@ def send_to_channel(text):
91
  )
92
  res.raise_for_status()
93
 
94
- # ===== Main =====
 
95
  def main():
96
- processed_ids = set()
97
 
98
  while True:
99
  try:
100
- messages = fetch_channel_messages()
101
  if not messages:
102
- time.sleep(2)
103
  continue
104
 
105
- # asc なので最後が最新
106
- latest = messages[-1]
107
- latest_id = latest.get("id")
108
- latest_person_id = latest.get("personId")
 
109
 
110
- # すでに処理済み
111
- if latest_id in processed_ids:
112
- time.sleep(2)
 
 
113
  continue
114
 
115
- # 自分の発言には反応しない
116
- if latest_person_id == ASSISTANT_PERSON_ID:
117
- processed_ids.add(latest_id)
118
- time.sleep(2)
119
  continue
120
 
 
121
  chat_messages = build_chat_messages(messages)
122
 
123
- if not chat_messages:
124
- processed_ids.add(latest_id)
125
- continue
126
 
127
- reply = call_chat_api(chat_messages)
128
  send_to_channel(reply)
129
 
130
- processed_ids.add(latest_id)
131
-
132
- # メモリ肥大防止
133
- if len(processed_ids) > 100:
134
- processed_ids = set(list(processed_ids)[-50:])
135
-
136
- print("返信送信完了")
137
 
138
  except Exception as e:
139
  print("エラー:", e)
 
 
 
 
140
 
141
- time.sleep(2)
142
 
143
  if __name__ == "__main__":
144
  main()
 
2
  import time
3
  import json
4
  import requests
5
+ from datetime import datetime, timezone
6
 
7
  # ===== Channel.io 設定 =====
8
  GROUP_ID = "534868"
9
  CHANNEL_ID = "200605"
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
+ PARAMS = {
15
+ "sortOrder": "asc", # createdAt 昇順で取得
16
+ "limit": 50,
17
+ }
18
 
19
  X_ACCOUNT = os.getenv("channeliotokenbot2")
20
  if not X_ACCOUNT:
 
27
  "x-account": X_ACCOUNT,
28
  }
29
 
 
 
 
 
 
 
30
  ASSISTANT_PERSON_ID = "595702"
31
 
32
+ # ===== GPT (HF Space) =====
33
+ GPT_ENDPOINT = "https://izuemon-gpt-free-api.hf.space/v1/chat/completions"
34
+
35
+ GPT_HEADERS = {
36
+ "Content-Type": "application/json"
37
+ }
38
 
39
  # ===== Utils =====
40
+ def parse_created_at(value):
41
+ if isinstance(value, (int, float)):
42
+ return datetime.fromtimestamp(value / 1000, tz=timezone.utc)
43
+ return None
44
+
45
+
46
+ def fetch_messages():
47
  res = requests.get(GET_URL, headers=HEADERS, params=PARAMS, timeout=30)
48
  res.raise_for_status()
49
  return res.json().get("messages", [])
50
 
51
+
52
+ def build_chat_messages(messages):
53
  chat_messages = []
54
 
55
+ for msg in messages:
56
  text = msg.get("plainText")
57
  person_id = msg.get("personId")
58
 
 
68
 
69
  return chat_messages
70
 
71
+
72
+ def call_gpt(chat_messages):
73
  payload = {
74
  "model": "gpt-3.5-turbo",
75
+ "messages": chat_messages
 
76
  }
77
 
78
  res = requests.post(
79
+ GPT_ENDPOINT,
80
+ headers=GPT_HEADERS,
81
  data=json.dumps(payload),
82
  timeout=60
83
  )
 
86
  data = res.json()
87
  return data["choices"][0]["message"]["content"]
88
 
89
+
90
  def send_to_channel(text):
91
  payload = {
92
  "requestId": f"desk-web-{int(time.time() * 1000)}",
93
  "blocks": [
94
  {"type": "text", "value": text}
95
+ ]
96
  }
97
 
98
  res = requests.post(
 
103
  )
104
  res.raise_for_status()
105
 
106
+
107
+ # ===== Main Loop =====
108
  def main():
109
+ last_processed_created_at = 0
110
 
111
  while True:
112
  try:
113
+ messages = fetch_messages()
114
  if not messages:
115
+ time.sleep(10)
116
  continue
117
 
118
+ # createdAt が最大のメッセージを確認
119
+ latest_msg = max(
120
+ messages,
121
+ key=lambda m: m.get("createdAt", 0)
122
+ )
123
 
124
+ latest_created_at = latest_msg.get("createdAt", 0)
125
+
126
+ # 既に処理済み
127
+ if latest_created_at <= last_processed_created_at:
128
+ time.sleep(10)
129
  continue
130
 
131
+ # 最後の送信者が assistant なら何もしない
132
+ if latest_msg.get("personId") == ASSISTANT_PERSON_ID:
133
+ time.sleep(10)
 
134
  continue
135
 
136
+ # ChatGPT 形式に変換
137
  chat_messages = build_chat_messages(messages)
138
 
139
+ # GPT 呼び出し
140
+ reply = call_gpt(chat_messages)
 
141
 
142
+ # Channel.io に送信
143
  send_to_channel(reply)
144
 
145
+ last_processed_created_at = latest_created_at
146
+ print("送信完了")
 
 
 
 
 
147
 
148
  except Exception as e:
149
  print("エラー:", e)
150
+ import traceback
151
+ traceback.print_exc()
152
+
153
+ time.sleep(15)
154
 
 
155
 
156
  if __name__ == "__main__":
157
  main()