Giter Club home page Giter Club logo

Comments (7)

codisfy avatar codisfy commented on August 28, 2024 2

You will need to 1 disable CSP - you can look for a CSP disabling extension on the chrome store.

Also the document selectors have changed since the UI on CGPT has changed quite a bit.
I tweaked the tampermonkey script to work with the latest UI.
I have tested with gpt 4 only

// ==UserScript==
// @name         ChatGPT API By Browser Script
// @namespace    http://tampermonkey.net/
// @version      1
// @match        https://chat.openai.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=openai.com
// @grant        GM_webRequest
// @license MIT
// ==/UserScript==
console.log('starting');

const WS_URL = `ws://localhost:8765`;

function getTextFromNode(node) {
  let result = '';

  if (!node) return result;
  const childNodes = node.childNodes;

  for (let i = 0; i < childNodes.length; i++) {
    let childNode = childNodes[i];
    if (childNode.nodeType === Node.TEXT_NODE) {
      result += childNode.textContent;
    } else if (childNode.nodeType === Node.ELEMENT_NODE) {
      result += getTextFromNode(childNode);
    }
  }

  return result;
}

function sleep(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

// Main app class
class App {
  constructor() {
    this.socket = null;
    this.observer = null;
    this.stop = false;
    this.dom = null;
  }

  async start({ text, model, newChat }) {
    this.stop = false
    const textarea = document.querySelector('textarea');
    textarea.value = text;
    const event = new Event('input', { bubbles: true });
    textarea.dispatchEvent(event);
    await sleep(500);
    const send = document.querySelectorAll('button[data-testid="send-button"]')[0];
    if (send) {
      send.click();
    } else {
      console.log('Send button not found');
    }

    this.observeMutations();
  }

  observeMutations() {
    this.observer = new MutationObserver(async (mutations) => {
      const list = [...document.querySelectorAll('div.agent-turn')];
      const last = list[list.length - 1];
      if (!last) { 
        console.log('No last message found');
        return;
      }
      const lastText = getTextFromNode(last.querySelector('div[data-message-author-role="assistant"]'));
      console.log('send', {
        text: lastText,
      })
      this.socket.send(
        JSON.stringify({
          type: 'answer',
          text: lastText,
        })
      );
      await sleep(1000);
      const button = document.querySelector('button[aria-label="Stop generating"]');
      if (button) return
      if (
        !button
      ) {
        if (this.stop) return
        this.stop = true
        console.log('send', {
          type: 'stop',
        })
        this.socket.send(
          JSON.stringify({
            type: 'stop',
          })
        );
        this.observer.disconnect();
      }
    });

    const observerConfig = { childList: true, subtree: true };
    this.observer.observe(document.body, observerConfig);
  }

  sendHeartbeat() {
    if (this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify({ type: 'heartbeat' }));
    }
  }

  connect() {
    this.socket = new WebSocket(WS_URL);
    this.socket.onopen = () => {
      console.log('Server connected, can process requests now.');
      this.dom.innerHTML = '<div style="color: green; ">API Connected !</div>';
    }
    this.socket.onclose = () => {
      console.log('The server connection has been disconnected, the request cannot be processed.');
      this.dom.innerHTML = '<div style="color: red; ">API Disconnected !</div>';

      setTimeout(() => {
        console.log('Attempting to reconnect...');
        this.connect();
      }, 2000);
    }
    this.socket.onerror = () => {
      console.log('Server connection error, please check the server.');
      this.dom.innerHTML = '<div style="color: red; ">API Error !</div>';
    }
    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data)
      console.log('params', data)
      this.start(data);
    };
  }

  init() {
    window.addEventListener('load', () => {
      this.dom = document.createElement('div');
      this.dom.style = 'position: fixed; top: 10px; right: 10px; z-index: 9999; display: flex; justify-content: center; align-items: center;';
      document.body.appendChild(this.dom);

      this.connect();

      setInterval(() => this.sendHeartbeat(), 30000);
    });
  }

}

(function () {
  'use strict';
  const app = new App();
  app.init();
})();

from chatgpt-api-by-browser-script.

Related Issues (10)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.