any-env-code / chatgpt.py
izuemon's picture
Update chatgpt.py
a6a1daf verified
raw
history blame
2.95 kB
import os
import time
import json
import requests
# ===== Channel.io 設定 =====
GROUP_ID = "534868"
CHANNEL_ID = "200605"
GET_URL = f"https://desk-api.channel.io/desk/channels/{CHANNEL_ID}/groups/{GROUP_ID}/messages"
POST_URL = GET_URL
X_ACCOUNT = os.getenv("channeliotokenbot2")
if not X_ACCOUNT:
raise RuntimeError("環境変数 channeliotokenbot2 が設定されていません")
HEADERS = {
"accept": "application/json",
"accept-language": "ja",
"content-type": "application/json",
"x-account": X_ACCOUNT,
}
PARAMS = {
"sortOrder": "asc",
"limit": 50,
}
ASSISTANT_PERSON_ID = "595702"
# ===== ChatGPT互換API =====
CHAT_API_URL = "https://izuemon-gpt-free-api.hf.space/v1/chat/completions"
# ===== Utils =====
def fetch_channel_messages():
res = requests.get(GET_URL, headers=HEADERS, params=PARAMS, timeout=30)
res.raise_for_status()
return res.json().get("messages", [])
def build_chat_messages(messages):
chat_messages = []
for msg in messages:
text = msg.get("plainText")
person_id = msg.get("personId")
if not text:
continue
role = "assistant" if person_id == ASSISTANT_PERSON_ID else "user"
chat_messages.append({
"role": role,
"content": text
})
return chat_messages
def call_chat_api(chat_messages):
payload = {
"model": "gpt-3.5-turbo",
"messages": chat_messages,
}
res = requests.post(
CHAT_API_URL,
headers={"Content-Type": "application/json"},
data=json.dumps(payload),
timeout=60
)
res.raise_for_status()
data = res.json()
return data["choices"][0]["message"]["content"]
def send_to_channel(text):
payload = {
"requestId": f"desk-web-{int(time.time() * 1000)}",
"blocks": [
{"type": "text", "value": text}
],
}
res = requests.post(
POST_URL,
headers=HEADERS,
data=json.dumps(payload),
timeout=30
)
res.raise_for_status()
# ===== Main =====
def main():
processed = set()
while True:
try:
messages = fetch_channel_messages()
if not messages:
time.sleep(10)
continue
# 最新メッセージをトリガーにする
latest = messages[-1]
msg_id = latest.get("id")
if msg_id in processed:
time.sleep(10)
continue
chat_messages = build_chat_messages(messages)
if not chat_messages:
processed.add(msg_id)
continue
reply = call_chat_api(chat_messages)
send_to_channel(reply)
processed.add(msg_id)
print("送信完了")
except Exception as e:
print("エラー:", e)
time.sleep(15)
if __name__ == "__main__":
main()