102 lines
2.8 KiB
Python
102 lines
2.8 KiB
Python
from fastapi import FastAPI, Body
|
|
from pydantic import BaseModel
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from openai import OpenAI
|
|
import pyautogui
|
|
import os
|
|
import time
|
|
import pyperclip
|
|
|
|
print("Di chuot den o nhap tin nhan trong 5 giay ...")
|
|
time.sleep(5)
|
|
input_position = pyautogui.position()
|
|
|
|
print(f"Da lay toa do: {input_position}")
|
|
|
|
x,y = input_position
|
|
|
|
# Thiết lập API key cho OpenAI
|
|
client = OpenAI(api_key="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") # Hoặc gán trực tiếp: "sk-..."
|
|
|
|
app = FastAPI()
|
|
|
|
# Cấu hình CORS
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# Dữ liệu đầu vào cho API
|
|
class Message(BaseModel):
|
|
name: str
|
|
message: str
|
|
time: int
|
|
room_id: str
|
|
room_name: str
|
|
x: int
|
|
y: int
|
|
|
|
# Gọi OpenAI và giả lập nhập liệu
|
|
def generate_and_type_reply(sender: str, content: str, x: int, y: int):
|
|
try:
|
|
response = client.chat.completions.create(
|
|
model="gpt-4o-mini",
|
|
messages=[
|
|
{"role": "system", "content": "Ban la tro ly tin nhan AI tra loi ngan gon va day du y, than thien. Tra loi tieng Anh. Format xuong dong bang \n"},
|
|
{"role": "user", "content": f"{sender} sent: {content}"}
|
|
]
|
|
)
|
|
reply = response.choices[0].message.content
|
|
print(f"AI tra loi: {reply}")
|
|
|
|
time.sleep(1)
|
|
pyautogui.click(x, y)
|
|
time.sleep(1)
|
|
for line in reply.split("\n"):
|
|
pyautogui.write(line, interval=0.01)
|
|
pyautogui.hotkey("shift", "enter")
|
|
time.sleep(1)
|
|
time.sleep(0.5)
|
|
pyautogui.press("enter")
|
|
pyautogui.press("enter")
|
|
pyautogui.press("enter")
|
|
|
|
return reply
|
|
except Exception as e:
|
|
return f"Lỗi khi gọi AI: {str(e)}"
|
|
|
|
# API để nhận tin nhắn và phản hồi
|
|
@app.post("/reply/")
|
|
def reply_to_message(msg: Message):
|
|
print(f"[{msg.room_name}] {msg.name}: {msg.message}")
|
|
reply = generate_and_type_reply(msg.name, msg.message, msg.x, msg.y)
|
|
return {
|
|
"sender": msg.name,
|
|
"message": msg.message,
|
|
"room": msg.room_name,
|
|
"reply": reply
|
|
}
|
|
|
|
@app.post("/type/")
|
|
def type(message: str = Body(..., embed=True)):
|
|
try:
|
|
print(f"Typing message: ")
|
|
|
|
pyautogui.click(x, y)
|
|
time.sleep(1)
|
|
|
|
# Copy vào clipboard và dán
|
|
pyperclip.copy(message)
|
|
pyautogui.hotkey("ctrl", "v")
|
|
time.sleep(0.5)
|
|
|
|
# Gửi Enter để gửi
|
|
pyautogui.press("enter")
|
|
|
|
return {"status": "success", "typed": message}
|
|
except Exception as e:
|
|
return {"status": "error", "detail": str(e)}
|