Skip to content

Commit 2b539d4

Browse files
author
Jayden Chao
committed
測試提交
1 parent 6cd9f2c commit 2b539d4

File tree

3 files changed

+75
-23
lines changed

3 files changed

+75
-23
lines changed

api/GrokAI.py

Lines changed: 30 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# -*- coding: utf-8 -*-
22

33
from dataclasses import dataclass
4+
from typing import Literal
45
import cloudscraper
56
from rich.console import Console
67
import json
@@ -15,11 +16,7 @@ def print_by_char_rich(console, text, delay=0.002):
1516
@dataclass
1617
class GrokAccount:
1718
cookies: dict
18-
message: str
1919
headers: dict
20-
NewChat: bool = True
21-
ChatID: str = None
22-
modelName: str = "grok-2"
2320

2421

2522
class GrokAI:
@@ -45,31 +42,33 @@ class GrokAI:
4542
def __init__(self,GrokAccount: GrokAccount):
4643
self.GrokAccount = GrokAccount
4744
self.Console = Console()
48-
obj = self.GrokAccount
45+
#obj = self.GrokAccount
4946

50-
has_new_chat = obj.NewChat # 检查 NewChat 是否为 True
51-
has_chat_id = obj.ChatID is not None # 检查 ChatID 是否非 None
47+
48+
49+
def Chat(self,meassge: str ,disableSearch: bool = False, enableImageGeneration: bool = True, isReasoning: bool = False,debug: bool = False,NewChat:bool = True,ChatID:str = None,ModelName: Literal['grok-3','grok-latest'] = 'grok-latest',deepsearch: Literal['deepsearch,deepersearch',None] = None) -> None:
50+
has_new_chat = NewChat # 检查 NewChat 是否为 True
51+
has_chat_id = ChatID is not None # 检查 ChatID 是否非 None
5252
if has_new_chat and has_chat_id:
5353
raise ValueError("NewChat 和 ChatID 不能同时为 True 和非 None")
5454

55-
def Chat(self, disableSearch: bool = False, enableImageGeneration: bool = True, imageGenerationCount: int = 2, isReasoning: bool = False,test: bool = False):
5655
self.cookies = self.GrokAccount.cookies
57-
self.message = self.GrokAccount.message
58-
self.modelName = self.GrokAccount.modelName
59-
self.NewChat = self.GrokAccount.NewChat
60-
self.ChatID = self.GrokAccount.ChatID
56+
self.message = meassge
57+
self.modelName = ModelName
58+
self.NewChat = NewChat
59+
self.ChatID = ChatID
6160
self.headers = self.GrokAccount.headers
6261
self.headers['referer'] = 'https://grok.com/chat/'
6362
self.responseUrl: str
6463
global has_valid_response
6564
has_valid_response = False
6665

67-
scraper = cloudscraper.create_scraper()
66+
scraper = cloudscraper.create_scraper(delay=10, browser={'browser': 'chrome', 'platform': 'windows', 'mobile': False})
6867

6968
if self.NewChat is False:
7069
self.url = f"https://grok.com/rest/app-chat/conversations/{self.ChatID}/responses"
7170
response = scraper.get(f"https://grok.com/rest/app-chat/conversations/{self.ChatID}/response-node")
72-
'''if response.status_code == 200:
71+
if response.status_code == 200:
7372
response_data = response.json()
7473
response_nodes = response_data.get("responseNodes", [])
7574
if response_nodes:
@@ -81,7 +80,7 @@ def Chat(self, disableSearch: bool = False, enableImageGeneration: bool = True,
8180
responseId = None
8281
else:
8382
print("No responseNodes found in the JSON data.")
84-
responseId = None'''
83+
responseId = None
8584
else:
8685
self.url = "https://grok.com/rest/app-chat/conversations/new"
8786

@@ -96,7 +95,7 @@ def Chat(self, disableSearch: bool = False, enableImageGeneration: bool = True,
9695
'returnRawGrokInXaiRequest': False,
9796
'fileAttachments': [],
9897
'enableImageStreaming': True,
99-
'imageGenerationCount': imageGenerationCount,
98+
'imageGenerationCount': 2,
10099
'forceConcise': False,
101100
'toolOverrides': {},
102101
'enableSideBySide': True,
@@ -106,18 +105,21 @@ def Chat(self, disableSearch: bool = False, enableImageGeneration: bool = True,
106105
'disableTextFollowUps': True
107106
}
108107

108+
if deepsearch is not None:
109+
self.data["deepsearchPreset"] = deepsearch
110+
109111
console = self.Console
110112
# 创建 cloudscraper 实例
111113

112114
response = scraper.post(self.url, headers=self.headers, cookies=self.cookies, json=self.data, stream=True)
113-
if test is True:
115+
if debug is True:
114116
# 這是測試代碼!!!!
115117
console.print(f"Request URL: {self.url}", style="bold blue")
116118
console.print(f"Headers: {self.headers}", style="bold blue")
117119
console.print(f"Cookies: {self.cookies}", style="bold blue")
118120
console.print(f"Data: {self.data}", style="bold blue")
119121

120-
122+
text = response.text
121123
# 檢查狀態碼
122124
if response.status_code == 200:
123125
for line in response.iter_lines():
@@ -129,12 +131,13 @@ def Chat(self, disableSearch: bool = False, enableImageGeneration: bool = True,
129131

130132
# 提取 token
131133
token = json_data.get("result", {}).get("response", {}).get("token", "")
132-
134+
generated_image_urls = json_data.get("result", {}).get("modelResponse", {}).get("generatedImageUrls", [])
133135
# 如果 token 存在,逐字輸出
134-
if token:
136+
if token or generated_image_urls:
137+
# 如果有圖片網址,打印圖片網址
135138

136139
has_valid_response = True
137-
print_by_char_rich(console, token, delay=0.05)
140+
print_by_char_rich(console, token if token else generated_image_urls, delay=0.05)
138141

139142
except json.JSONDecodeError:
140143
console.print("解析 JSON 失败", style="bold red")
@@ -146,10 +149,14 @@ def Chat(self, disableSearch: bool = False, enableImageGeneration: bool = True,
146149
else:
147150
console.print("请求失败", style="bold red")
148151
console.print(response.status_code, style="bold red")
149-
if "Just a moment..." in response.text or "<title>Just a moment...</title>" in response.text:
152+
if "Just a moment..." in text or "<title>Just a moment...</title>" in text:
150153
console.print("請求被 Cloudflare 防護攔截,請更新 Cookies 或 Headers。", style="bold red")
151154
else:
152-
console.print(response.text, style="bold red")
155+
console.print(text, style="bold red")
156+
157+
if debug is True:
158+
# 這是測試代碼!!!!
159+
console.print(text, style="bold yellow")
153160
'''
154161
for line in response.iter_lines():
155162
if line:

test/.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Automatically created by ruff.
2+
*.txt

test/test.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import sys
2+
import os
3+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
4+
from api.GrokAI import GrokAI, GrokAccount
5+
from rich.console import Console
6+
7+
cookies = {
8+
'_ga': 'GA1.1.1691019154.1742809195',
9+
'sso': 'eyJhbGciOiJIUzI1NiJ9.eyJzZXNzaW9uX2lkIjoiNGNjOTZlOTctYzNlYS00NTUyLTlhYWYtMWI1ZjJiNmY3MDNjIn0.BnY3wcBEA70vch8OHI8a_kBzhKfene7JsEYSvPuHgU0',
10+
'sso-rw': 'eyJhbGciOiJIUzI1NiJ9.eyJzZXNzaW9uX2lkIjoiNGNjOTZlOTctYzNlYS00NTUyLTlhYWYtMWI1ZjJiNmY3MDNjIn0.BnY3wcBEA70vch8OHI8a_kBzhKfene7JsEYSvPuHgU0',
11+
'i18nextLng': 'zh-TW',
12+
'cf_clearance': 'BVyVUo3SHFMJCGaiqOdcFp0wgBTjyegtIsMJbROWumM-1743260506-1.2.1.1-93HWk2jjry2fFZMkL88eD2rgI7IapPgbrBVF7vGUNOeSX3PwiyoFTROqLKEjv18XcTqQ4dK7kuczHuKc5mQxQeBTJh23FF93IgXeSYHyNurzfqmBSqdqXw3cbkXxlbq74AmT1i9utURMwI20p3n9_.Mr8FNUX6hGpLV__H.HHhAXO.tnuhC9e2VgEGzxSYH.wCBkO76Rd12SlFYNFgNdQZ82BWk.bG791kKBLO9O3y8tXOv0okNnPXXfoqLb7Z4LmBffzSsf.4iCzif1L4QkTSfi0HxIoBL0dm6rDmpSqNb4L14EnwIB7YqvUZRAus3Z.0C01vtxtDMgB9l2aoeCnd5ImtTELwSlTBPG4NGKC_jtWlWkmydmj3xhVH4AhW23v5TudF8gWu3kDpPv7fBpmtrcjBZlZxP564Xt1DrLC7Y',
13+
'_ga_8FEWB057YH': 'GS1.1.1743232889.3.1.1743233813.0.0.0',
14+
'__cf_bm': 'kJlhUhv_Q5b7j8.PEBNA2oaPn3HYleB7jBVNpcQbzRQ-1743260665-1.0.1.1-YTE7Af.sWDNUsQp9USARIPeNHhiLo5TXUNoZdzs3cdk5gXc2XkcbSzPYBfyTQ3N7sSeqCGLUd4UBPW1txz0jsvWzAZ9oymP0AIureR7fubM'
15+
}
16+
account = GrokAccount(
17+
cookies=cookies,
18+
headers={
19+
'accept': '*/*',
20+
'content-type': 'application/json',
21+
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/134.0.0.0 Safari/537.36'
22+
},
23+
)
24+
25+
# Initialize the GrokAI instance
26+
grok_ai = GrokAI(account)
27+
28+
# Use the Chat method to send a message
29+
console = Console()
30+
console.print("Sending message to Grok AI...", style="bold green")
31+
32+
try:
33+
grok_ai.Chat(
34+
disableSearch=False,
35+
enableImageGeneration=True,
36+
isReasoning=False,
37+
NewChat=True,
38+
meassge="please generate a picture of a cat",
39+
debug=True,
40+
41+
)
42+
except Exception as e:
43+
console.print(f"An error occurred: {e}", style="bold red")

0 commit comments

Comments
 (0)