Script updated: 2025-02-22
Should disable the Grok prompt injection.
If you want the prompt injection, change systemPromptName = "empty"
to systemPromptName = ""
First, go to https://x.com/settings/grok_settings
and disable everything.
Next, open this url: https://x.com/i/grok
Open the developer console/inspect (ctrl + shift + I or F12).
Go to the Network tab, then send any message to Grok.
Find the request labeled add_response.json
.
Open this request and look at the headers (make sure you are looking at request headers, not response headers).
Find the headers named authorization
, Cookie
, and x_csrf_token
. You may need to send a 2nd message for Cookie
to appear.
Copy the script below into a text file. At the top of the script, paste your authorization
, Cookie
, and x_csrf_token
headers into the script between the """ """
.
If you have multiple accounts, place the relevant headers for each account on new lines, all between the """ """
. The script will try each account, and try both grok-3 and grok-2 on each of them (grok-2 gets redirected to grok-3).
Finally, in the url of the Grok page, you will see something like conversation=12345, replace conversationId with this number. Or leave it as 0. Seems to work either way.
Save the script with a .py
extension, run it, and use http://localhost:5000
in ST.
All system role messages are sent with with a user role.
If you have a prefill disable it.
Each account gets 40 messages every 2 hours. If you run out of messages, try enabling useReasoning = True
.
Responses you receive in ST may also appear on https://x.com/i/grok
in the conversation you're using. The script will attempt to delete the conversation after each message.
Only works with streaming enabled.
By default, Grok has a prompt injection. This script disables that injection with systemPromptName = "empty"
. If you want to enable the injection, change this to systemPromptName = ""
.
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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | authorization = """
"""
Cookie = """
"""
x_csrf_token = """
"""
conversationId = 0
useReasoning = False
useDeepsearch = False
systemPromptName = "empty"
from flask import Flask, request, Response, stream_with_context
import requests, json
app = Flask(__name__)
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0"
model_list = ["grok-3", "grok-2"]
settings = {
"systemPromptName": systemPromptName,
"conversationId": str(conversationId),
"returnSearchResults": False,
"returnCitations": False,
"promptMetadata": {"promptSource": "NATURAL", "action": "INPUT"},
"imageGenerationCount": 4,
"requestFeatures": {"eagerTweets": False, "serverHistory": False},
"enableCustomization": False,
"enableSideBySide": False,
"toolOverrides": {},
"isDeepsearch": useDeepsearch,
"isReasoning": useReasoning
}
headers = {
"authorization": "",
"Cookie": "",
"User-Agent": user_agent
}
users = []
response_url = "https://grok.x.com/2/grok/add_response.json"
delete_url = "https://x.com/i/api/graphql/TlKHSWVMVeaa-i7dqQqFQA/ConversationItem_DeleteConversationMutation"
def list_from_config(config):
return list(filter(lambda x: x.strip() != "", config.split("\n")))
def account_setup():
auths = list_from_config(authorization)
cookies = list_from_config(Cookie)
csrfs = list_from_config(x_csrf_token)
for i in range(min(len(auths), len(cookies), len(csrfs))):
for model in model_list:
users.append({"index": i, "authorization": auths[i], "Cookie": cookies[i], "x-csrf-token": csrfs[i], "model": model})
if len(users) == 0:
print("No accounts found.")
input()
def start_request():
for h in ["authorization", "Cookie", "x-csrf-token"]:
headers[h] = users[0][h]
resp = requests.post(response_url, headers=headers, json=settings, stream=True)
delete_conversation()
return resp
def delete_conversation():
requests.post(delete_url, headers=headers, json={"variables": {"conversationId": str(conversationId)}, "queryId": "TlKHSWVMVeaa-i7dqQqFQA"})
@app.route("/models")
def models():
return {"object": "list", "data": [{"id": "grok-3", "object": "model"}]}
@app.route("/chat/completions", methods=["POST"])
def completions():
print(f"Using account {users[0]["index"]} with model {users[0]["model"]}.")
settings["responses"] = []
for m in request.json["messages"]:
try:
sender = (2 if m["role"] == "assistant" else 1)
message = m["content"]
except (ValueError, KeyError):
sender = 1
message = ""
settings["responses"].append({"message": message, "sender": sender})
settings["grokModelOptionId"] = users[0]["model"]
stream = "stream" in request.json and request.json["stream"]
def stream_response(accounts_tried=1):
resp = start_request()
thinking = False
text = ""
for line in resp.iter_lines():
try:
result = json.loads(line.decode())["result"]
content = result["message"]
if "responseType" in result and result["responseType"] == "limiter":
users.append(users.pop(0))
settings["grokModelOptionId"] = users[0]["model"]
if accounts_tried == len(users):
error = "All accounts rate limited."
if stream:
yield "data: " + json.dumps({"choices": [{"delta": {"content": error, "role": "assistant"}}]}) + "\n\n"
else:
yield {"choices": [{"message": {"content": error, "role": "assistant"}}]}
else:
print(f"Swapped to account {users[0]["index"]} with model {users[0]["model"]}.")
for line in stream_response(accounts_tried+1):
yield line
return
if "isThinking" in result and result["isThinking"] and not thinking:
content = "<thinking>\n" + content
thinking = True
elif "isThinking" not in result and thinking:
content = "\n</thinking>\n\n" + content
thinking = False
if stream:
yield "data: " + json.dumps({"choices": [{"delta": {"content": content, "role": "assistant"}}]}) + "\n\n"
text += content
except:
try:
print(json.loads(line.decode()))
except:
print(line)
if not stream:
yield {"choices": [{"message": {"content": text, "role": "assistant"}}]}
delete_conversation()
if stream:
return Response(stream_with_context(stream_response()), content_type='text/event-stream', headers={'Cache-Control': 'no-cache', 'Connection': 'keep-alive'})
else:
for response in stream_response():
return response
if __name__ == "__main__":
account_setup()
app.run()
|