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 = "".

grok.skittle041@passinbox.com

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()
Edit
Pub: 20 Feb 2025 09:18 UTC
Edit: 24 Feb 2025 03:31 UTC
Views: 3926