返回提交历史
Modified
gpt4free/hpgptai/__init__.py
+28
-9
XFEstudio/gpt4free
Automatically obtain restNonce
b0dee138
代码差异
1 个文件
+28
-9
@@ -5,20 +5,26 @@
5
5
@File :__init__.py.py
6
6
@IDE :PyCharm
7
7
"""
8
import re
8
9
import json
9
import requests
10
import base64
10
11
import random
11
12
import string
13
import requests
14
from fake_useragent import UserAgent
15
12
16
13
17
class ChatCompletion:
14
18
@staticmethod
15
19
def create(
16
20
messages: list,
17
context: str="Converse as if you were an AI assistant. Be friendly, creative.",
18
restNonce:str="9d6d743bd3",
19
proxy:str=None
21
context: str = "Converse as if you were an AI assistant. Be friendly, creative.",
22
restNonce: str = None,
23
proxy: str = None
20
24
):
21
25
url = "https://chatgptlogin.ac/wp-json/ai-chatbot/v1/chat"
26
if not restNonce:
27
restNonce = ChatCompletion.get_restNonce(proxy)
22
28
headers = {
23
29
"Content-Type": "application/json",
24
30
"X-Wp-Nonce": restNonce
@@ -27,7 +33,7 @@ class ChatCompletion:
27
33
data = {
28
34
"env": "chatbot",
29
35
"session": "N/A",
30
"prompt": ChatCompletion.__build_prompt(context,messages),
36
"prompt": ChatCompletion.__build_prompt(context, messages),
31
37
"context": context,
32
38
"messages": messages,
33
39
"newMessage": messages[-1]["content"],
@@ -48,7 +54,6 @@ class ChatCompletion:
48
54
return res.json()
49
55
return res.text
50
56
51
52
57
@staticmethod
53
58
def randomStr():
54
59
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=34))[:11]
@@ -66,12 +71,26 @@ class ChatCompletion:
66
71
prompt += '\n' + "AI: "
67
72
return prompt
68
73
69
74
@classmethod
75
def get_restNonce(cls, proxy: str = None):
76
url = "https://chatgptlogin.ac/"
77
headers = {
78
"Referer": "https://chatgptlogin.ac/",
79
"User-Agent": UserAgent().random
80
}
81
proxies = {'http': 'http://' + proxy, 'https': 'http://' + proxy} if proxy else None
82
res = requests.get(url, headers=headers, proxies=proxies)
83
src = re.search(
84
'class="mwai-chat mwai-chatgpt">.*<span>Send</span></button></div></div></div> <script defer src="(.*?)">',
85
res.text).group(1)
86
decoded_string = base64.b64decode(src.split(",")[-1]).decode('utf-8')
87
restNonce = re.search(r"let restNonce = '(.*?)';", decoded_string).group(1)
88
return restNonce
70
89
71
90
72
91
class Completion:
73
92
@staticmethod
74
def create(prompt: str,proxy:str):
93
def create(prompt: str, proxy: str):
75
94
messages = [
76
95
{
77
96
"content": prompt,
@@ -81,4 +100,4 @@ class Completion:
81
100
"who": "User: ",
82
101
},
83
102
]
84
return ChatCompletion.create(messages=messages,proxy=proxy)
103
return ChatCompletion.create(messages=messages, proxy=proxy)