forked from hugoecarl/Whats-GPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
55 lines (41 loc) · 1.5 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from fastapi import FastAPI, Request
from pydantic import BaseModel
import requests
import openai
import json
# with open('keys.json', 'r') as f:
# KEYS = json.loads(f.read())
# f.close()
class Item(BaseModel):
entry: list
app = FastAPI()
@app.get("/api")
def read_root(request: Request):
return int(request.query_params.get('hub.challenge'))
@app.post("/api")
def create_item(item: Item):
user_message = item.entry[0]['changes'][0]['value']['messages'][0]['text']['body']
with open('chat.json', 'r') as f:
messages = json.loads(f.read())
f.close()
messages.append({"role": "user", "content": f"{user_message}"})
openai.api_key = KEYS['OPEN_AI_KEY']
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
ai_message = response.get('choices')[0].get('message').get('content').strip()
header = {"Authorization": f"Bearer {KEYS['AUTH_TOKEN_WHATS']}"}
payload = {
"messaging_product": "whatsapp",
"to": item.entry[0]['changes'][0]['value']['contacts'][0]['wa_id'],
"type": "text",
"text": {
"body": f"{ai_message}"
}
}
r = requests.post('https://graph.facebook.com/v15.0/105624622440704/messages', json=payload, headers=header)
messages.append({"role": "assistant", "content": f"{ai_message}"})
with open('chat.json', 'w') as f:
json.dump(messages, f, indent=4)
return item.entry[0]['changes'][0]['value']['contacts'][0]['wa_id']