techwithanirudh

Untitled

Oct 4th, 2023 (edited)
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name        New script - amcforum.wiki
  3. // @namespace   Violentmonkey Scripts
  4. // @match       https://amcforum.wiki/chat/c/*
  5. // @grant       GM_xmlhttpRequest
  6. // @version     1.0
  7. // @author      -
  8. // @description 3/10/2023, 8:17:49 pm
  9. // ==/UserScript==
  10.  
  11. (function() {
  12.     // Constants
  13.     const API_URL = "https://api.openai.com/v1/chat/completions";
  14.     const API_KEY = "sk-apikey";
  15.     const MODEL = "gpt-3.5-turbo";
  16.     const SYSTEM_PROMPT = `You are Grammarly, an AI Language model which fixes spelling mistakes and punctuation.
  17.     Do NOT try to interfere with anything else.
  18.     Do NOT give AI Vibes, just reframe like a 13 year old texting.
  19.     JUST give the reframed message, nothing more.`;
  20.     let HISTORY = [];
  21.     const HISTORY_LENGTH = 3;
  22.  
  23.     // Function to update HISTORY array with chat messages
  24.     const updateHistory = () => {
  25.         const chatMessages = document.querySelectorAll('.chat-message-text p');
  26.         HISTORY = [];
  27.  
  28.         // Populate HISTORY array from bottom to top
  29.         for (let i = chatMessages.length - 1; i >= 0; i--) {
  30.             const role = 'user';
  31.             const content = chatMessages[i].textContent;
  32.             HISTORY.push({ role, content });
  33.         }
  34.  
  35.         HISTORY = HISTORY.slice(0, HISTORY_LENGTH);
  36.     };
  37.  
  38.     // Function to fetch AI-generated text from OpenAI API
  39.     const fetchAIResponse = async (userMessage) => {
  40.         return fetch(
  41.             API_URL,
  42.             {
  43.                 body: JSON.stringify({
  44.                     "model": MODEL,
  45.                     "messages": [
  46.                         {
  47.                             "role": "system",
  48.                             "content": SYSTEM_PROMPT
  49.                         },
  50.                         ...HISTORY,
  51.                         {
  52.                             "role": "user",
  53.                             "content": `Reframe this message: ${userMessage}`
  54.                         }
  55.                     ],
  56.                     "temperature": 0,
  57.                     "max_tokens": 500
  58.                 }),
  59.                 method: "POST",
  60.                 headers: {
  61.                     "Content-Type": "application/json",
  62.                     "Authorization": "Bearer " + API_KEY
  63.                 }
  64.             }
  65.         ).then(response => {
  66.             if (response.ok) {
  67.                 return response.json();
  68.             } else {
  69.                 throw new Error('Failed to fetch AI response');
  70.             }
  71.         }).then(json => {
  72.             return json['choices'][0]['message']['content'];
  73.         });
  74.     };
  75.  
  76.     // Function to modify textarea value and send
  77.     const modifyAndSend = async (event) => {
  78.         const textarea = document.querySelector('.chat-composer__input');
  79.         const sendButton = document.querySelector('.chat-composer-button.-send');
  80.  
  81.         if (textarea && sendButton) {
  82.             // Stop the event propagation and prevent the default action
  83.             event.stopImmediatePropagation();
  84.             event.preventDefault();
  85.  
  86.             // Store the original value and disable textarea, then show loading
  87.             const originalValue = textarea.value;
  88.             textarea.disabled = true;
  89.             textarea.value = 'Loading...';
  90.  
  91.             // Update HISTORY before sending a new message
  92.             updateHistory();
  93.  
  94.             try {
  95.                 // Fetch AI-generated text and update the textarea value
  96.                 const aiResponse = await fetchAIResponse(originalValue);
  97.                 textarea.value = aiResponse;
  98.             } catch (error) {
  99.                 console.error(error);
  100.                 textarea.value = originalValue;
  101.             }
  102.  
  103.             // Re-enable textarea
  104.             textarea.disabled = false;
  105.  
  106.             // Trigger an input event to update the UI
  107.             const inputEvent = new Event('input', {
  108.                 'bubbles': true,
  109.                 'cancelable': true
  110.             });
  111.             textarea.dispatchEvent(inputEvent);
  112.  
  113.             // Send the message
  114.             // sendButton.click();
  115.         }
  116.     };
  117.  
  118.     // Listen for the keydown event on the textarea
  119.     document.addEventListener('keydown', function(event) {
  120.         if (event.target.matches('.chat-composer__input') && event.key === 'Enter') {
  121.             modifyAndSend(event);
  122.         }
  123.     }, true);  // Use capture phase to handle the event as soon as possible
  124. })();
  125.  
Advertisement
Add Comment
Please, Sign In to add comment