Advertisement
nonogamer9

Project Memphis 2 Source Code

Apr 14th, 2025 (edited)
399
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 19.19 KB | Software | 0 0
  1. const prefix = "mem!";
  2. const botname = "Memphis (" + prefix + "start)";
  3. const version = "2.0.0";
  4. const update = "April 14th, 2025";
  5. var uses = 0;
  6.  
  7. // External API URLs
  8. const PUTER_JS_URL = "https://js.puter.com/v2/";
  9. const WEATHER_API_KEY = "dcc6b2a3fa3d4fe58d9193316232905";
  10. const GOOGLE_API_KEY = "AIzaSyDQJ7SjasKcPq_bJhCyxuaoWiVydYTGDK0";
  11. const GOOGLE_CX = "c3619c6476b78442f"; // Custom Search Engine ID
  12. const TRANSLATE_API_KEY = "4a4725a769msh10c74bc91185a85p182f25jsn9a1a93fbbb77";
  13.  
  14. // Load external script for AI
  15. const script = document.createElement("script");
  16. script.src = PUTER_JS_URL;
  17. document.head.appendChild(script);
  18.  
  19. // Helper function to send messages
  20. function sendMsg(msg) {
  21.     setTimeout(() => {
  22.         socket.emit("talk", { text: msg });
  23.     }, 1100);
  24. }
  25.  
  26. // AI Query Function
  27. async function queryPuterAPI(inputText) {
  28.     try {
  29.         const response = await puter.ai.chat(inputText);
  30.         return response || "The AI couldn't generate a proper response.";
  31.     } catch (error) {
  32.         console.error("Error querying Puter.js API:", error);
  33.         return "Sorry, I couldn't process your request.";
  34.     }
  35. }
  36.  
  37. // Initialize bot
  38. setTimeout(() => {
  39.     socket.emit("command", { list: ["name", botname] });
  40. }, 1000);
  41.  
  42. setTimeout(() => {
  43.     sendMsg(`${botname} is online. Type ${prefix}start for available commands.`);
  44. }, 2000);
  45.  
  46. // Command handler
  47. socket.on("talk", async (message) => {
  48.     const text = message.text.trim(); // Trim whitespace for cleaner parsing
  49.  
  50.     // Check if the message starts with the prefix
  51.     if (!text.startsWith(prefix)) {
  52.         return; // Ignore messages that don't start with the bot prefix
  53.     }
  54.  
  55.     // Extract command and arguments
  56.     const [command, ...args] = text.slice(prefix.length).split(" ");
  57.     const argString = args.join(" ").trim();
  58.  
  59.     // Command Handling
  60.     switch (command.toLowerCase()) {
  61.         case "ask":
  62.             if (!argString) {
  63.                 sendMsg(`Please provide a question or prompt after '${prefix}ask'.`);
  64.                 return;
  65.             }
  66.             sendMsg("- Processing your query...");
  67.             const aiResponse = await queryPuterAPI(argString);
  68.             sendMsg(`**AI Response:** ${aiResponse}`);
  69.             uses++;
  70.             break;
  71.  
  72.         case "start":
  73.             sendMsg("__Project Memphis Start Menu__\n"
  74.                 + "- AI: `" + prefix + "ask {question}`\n"
  75.                 + "- Weather: `" + prefix + "weather {location}`\n"
  76.                 + "- Games: `" + prefix + "snake` or `" + prefix + "maze`\n"
  77.                 + "- Utilities: `" + prefix + "notepad`, `" + prefix + "calculator`, `" + prefix + "clock`\n"
  78.                 + "- Search: `" + prefix + "google {query}`, `" + prefix + "translate {text} to {language}`");
  79.             break;
  80.  
  81.         case "weather":
  82.             if (!argString) {
  83.                 sendMsg(`Please provide a location after '${prefix}weather'.`);
  84.                 return;
  85.             }
  86.             getWeather(argString);
  87.             break;
  88.  
  89.         case "snake":
  90.             handleSnakeCommand(argString);
  91.             break;
  92.  
  93.         case "maze":
  94.             handleMazeCommand(argString);
  95.             break;
  96.  
  97.         case "clock":
  98.             sendMsg(getCurrentTime());
  99.             break;
  100.  
  101.         case "calculator":
  102.             if (!argString) {
  103.                 sendMsg(`Please provide an operation after '${prefix}calculator'.`);
  104.                 return;
  105.             }
  106.             calculator(argString);
  107.             break;
  108.  
  109.         case "notepad":
  110.             handleNotepadCommand(argString);
  111.             break;
  112.  
  113.         case "google":
  114.             if (!argString) {
  115.                 sendMsg(`Please provide a search query after '${prefix}google'.`);
  116.                 return;
  117.             }
  118.             googleSearch(argString);
  119.             break;
  120.  
  121.         case "translate":
  122.             if (!argString) {
  123.                 sendMsg(`Please provide text and target language in the format '${prefix}translate <text> to <language>'.`);
  124.                 return;
  125.             }
  126.             translateText(argString);
  127.             break;
  128.  
  129.         default:
  130.             // Handle unrecognized commands gracefully
  131.             sendMsg(`Invalid command. Type '${prefix}start' for a list of commands.`);
  132.     }
  133. });
  134.  
  135. // Utility Functions
  136.  
  137. function getCurrentTime() {
  138.     const now = new Date();
  139.     return `Current time is: ${now.toLocaleTimeString("en-US", { hour12: true })}`;
  140. }
  141.  
  142. function getWeather(location) {
  143.     const apiUrl = `https://api.weatherapi.com/v1/current.json?key=${WEATHER_API_KEY}&q=${encodeURIComponent(location)}`;
  144.    
  145.     fetch(apiUrl)
  146.         .then((response) => response.json())
  147.         .then((data) => {
  148.             if (data.error) {
  149.                 sendMsg("Unable to retrieve weather information. Please check the location.");
  150.             } else {
  151.                 const weatherInfo = `Weather in ${data.location.name}, ${data.location.country}:\nCondition: ${data.current.condition.text}\nTemperature: ${data.current.temp_c}°C\nHumidity: ${data.current.humidity}%\nWind Speed: ${data.current.wind_kph} km/h`;
  152.                 sendMsg(weatherInfo);
  153.             }
  154.         })
  155.         .catch((error) => {
  156.             console.error("Error:", error);
  157.             sendMsg("An error occurred while retrieving weather information.");
  158.         });
  159. }
  160.  
  161. // Snake Game Variables
  162. let snake = [{ x: 0, y: 0 }]; // Snake's initial position
  163. let food = { x: 5, y: 5 }; // Food's initial position
  164. let direction = "right"; // Initial direction of the snake
  165.  
  166. function handleSnakeCommand(command) {
  167.     if (command === "play") {
  168.         startSnakeGame();
  169.     } else if (["up", "down", "left", "right"].includes(command)) {
  170.         updateSnakeDirection(command);
  171.         moveSnake();
  172.         if (checkCollision()) {
  173.             sendMsg("Game Over! You collided with the wall or yourself.");
  174.             return;
  175.         }
  176.         checkFoodEaten();
  177.         sendMsg(renderSnakeGame());
  178.     } else {
  179.         sendMsg(`Invalid command. Use \`${prefix}snake play\` to start the game and \`${prefix}snake up/down/left/right\` to control.`);
  180.     }
  181. }
  182.  
  183. function startSnakeGame() {
  184.     snake = [{ x: 0, y: 0 }];
  185.     food = { x: Math.floor(Math.random() * 14), y: Math.floor(Math.random() * 6) };
  186.     direction = "right";
  187.     sendMsg(renderSnakeGame());
  188. }
  189.  
  190. function updateSnakeDirection(command) {
  191.     if (command === "up" && direction !== "down") direction = "up";
  192.     else if (command === "down" && direction !== "up") direction = "down";
  193.     else if (command === "left" && direction !== "right") direction = "left";
  194.     else if (command === "right" && direction !== "left") direction = "right";
  195. }
  196.  
  197. function moveSnake() {
  198.     const head = { ...snake[0] };
  199.     if (direction === "up") head.y--;
  200.     else if (direction === "down") head.y++;
  201.     else if (direction === "left") head.x--;
  202.     else if (direction === "right") head.x++;
  203.     snake.unshift(head);
  204. }
  205.  
  206. function checkCollision() {
  207.     const head = snake[0];
  208.     if (head.x < 0 || head.x >= 14 || head.y < 0 || head.y >= 6) return true; // Wall collision
  209.     for (let i = 1; i < snake.length; i++) {
  210.         if (snake[i].x === head.x && snake[i].y === head.y) return true; // Self-collision
  211.     }
  212.     return false;
  213. }
  214.  
  215. function checkFoodEaten() {
  216.     const head = snake[0];
  217.     if (head.x === food.x && head.y === food.y) {
  218.         food = { x: Math.floor(Math.random() * 14), y: Math.floor(Math.random() * 6) };
  219.     } else {
  220.         snake.pop(); // Remove tail to maintain length
  221.     }
  222. }
  223.  
  224. function renderSnakeGame() {
  225.     let board = Array.from({ length: 6 }, () => Array(14).fill(0));
  226.     for (const segment of snake) board[segment.y][segment.x] = 1;
  227.     board[food.y][food.x] = 2;
  228.     return board.map(row => row.join(" ")).join("\n");
  229. }
  230.  
  231.  
  232.  
  233. function handleMazeCommand(command) {
  234.     if (command === "play") {
  235.         startMazeGame();
  236.     } else if (command === "up" || command === "down" || command === "left" || command === "right") {
  237.         movePlayer(command);
  238.     } else if (command === "guide") {
  239.         sendMsg("Welcome to mem!maze!\n\n"
  240.           + "You are represented by the number 9, and your goal is to reach the number 3.\n"
  241.           + "Use `" + prefix + "maze up/down/left/right` to move in the maze.\n"
  242.           + "Good luck!");
  243.     } else {
  244.         sendMsg("Invalid command. Use `" + prefix + "maze play` to start the game, `" + prefix + "maze up/down/left/right` to control, or `" + prefix + "maze guide` for instructions.");
  245.     }
  246. }
  247.  
  248. // Maze Game Variables
  249. const mazeRows = 6;
  250. const mazeColumns = 14;
  251. const wallChance = 0.3;
  252. let maze;
  253. let playerPosition;
  254. let goalPosition;
  255.  
  256. function handleMazeCommand(command) {
  257.     if (command === "play") {
  258.         startMazeGame();
  259.     } else if (["up", "down", "left", "right"].includes(command)) {
  260.         movePlayer(command);
  261.     } else if (command === "guide") {
  262.         sendMsg(`Welcome to mem!maze!\n\nYou are represented by the number 9, and your goal is to reach the number 3.\nUse \`${prefix}maze up/down/left/right\` to move in the maze.\nGood luck!`);
  263.     } else {
  264.         sendMsg(`Invalid command. Use \`${prefix}maze play\` to start the game, \`${prefix}maze up/down/left/right\` to control, or \`${prefix}maze guide\` for instructions.`);
  265.     }
  266. }
  267.  
  268. function startMazeGame() {
  269.     maze = generateRandomMaze();
  270.     playerPosition = { x: Math.floor(mazeColumns / 2), y: mazeRows - 1 };
  271.     maze[playerPosition.y][playerPosition.x] = 9;
  272.     goalPosition = generateRandomGoalPosition();
  273.     maze[goalPosition.y][goalPosition.x] = 3;
  274.     sendMsg(renderMaze());
  275. }
  276.  
  277. function generateRandomMaze() {
  278.     return Array.from({ length: mazeRows }, () =>
  279.         Array.from({ length: mazeColumns }, () => Math.random() < wallChance ? 1 : 0)
  280.     );
  281. }
  282.  
  283. function generateRandomGoalPosition() {
  284.     let x, y;
  285.     do {
  286.         x = Math.floor(Math.random() * mazeColumns);
  287.         y = Math.floor(Math.random() * mazeRows);
  288.     } while (maze[y][x] !== 0);
  289.     return { x, y };
  290. }
  291.  
  292. function movePlayer(command) {
  293.     const { x, y } = playerPosition;
  294.     let newX = x, newY = y;
  295.  
  296.     if (command === "up") newY--;
  297.     else if (command === "down") newY++;
  298.     else if (command === "left") newX--;
  299.     else if (command === "right") newX++;
  300.  
  301.     if (newX >= 0 && newX < mazeColumns && newY >= 0 && newY < mazeRows && maze[newY][newX] !== 1) {
  302.         maze[y][x] = 0; // Clear previous position
  303.         playerPosition = { x: newX, y: newY };
  304.         maze[newY][newX] = 9; // Update player position
  305.  
  306.         if (newX === goalPosition.x && newY === goalPosition.y) {
  307.             sendMsg("Congratulations! You reached the goal!");
  308.             startMazeGame(); // Restart game
  309.             return;
  310.         }
  311.         sendMsg(renderMaze());
  312.     } else {
  313.         sendMsg("You cannot move in that direction.");
  314.         sendMsg(renderMaze());
  315.     }
  316. }
  317.  
  318. function renderMaze() {
  319.     return maze.map(row => row.join(" ")).join("\n");
  320. }
  321.  
  322. // Notepad Variables
  323. let notepads = [];
  324. let notepadCounter = 1;
  325. let notepadState = 'idle'; // Tracks the state of the current notepad
  326.  
  327. function handleNotepadCommand(command) {
  328.     const [action, ...args] = command.split(" ");
  329.     const content = args.join(" ").trim();
  330.  
  331.     switch (action.toLowerCase()) {
  332.         case "create":
  333.             createNotepad();
  334.             break;
  335.  
  336.         case "write":
  337.             if (!content) {
  338.                 sendMsg("Please provide content to write. Example: `mem!notepad write This is my note.`");
  339.             } else {
  340.                 writeOnNotepad(content);
  341.             }
  342.             break;
  343.  
  344.         case "save":
  345.             saveNotepad();
  346.             break;
  347.  
  348.         case "list":
  349.             listNotepads();
  350.             break;
  351.  
  352.         case "delete":
  353.             if (!args[0]) {
  354.                 sendMsg("Please provide a notepad ID to delete. Example: `mem!notepad delete 1`.");
  355.             } else {
  356.                 deleteNotepad(args[0]);
  357.             }
  358.             break;
  359.  
  360.         case "modify":
  361.             if (!args[0]) {
  362.                 sendMsg("Please provide a notepad ID to modify. Example: `mem!notepad modify 1`.");
  363.             } else {
  364.                 modifyNotepad(args[0]);
  365.             }
  366.             break;
  367.  
  368.         case "read":
  369.             if (!args[0]) {
  370.                 sendMsg("Please provide a notepad ID to read. Example: `mem!notepad read 1`.");
  371.             } else {
  372.                 readNotepad(args[0]);
  373.             }
  374.             break;
  375.  
  376.         default:
  377.             sendMsg(`Invalid command. Use \`${prefix}notepad create/write/save/list/delete/modify/read\`.`);
  378.     }
  379. }
  380.  
  381. function createNotepad() {
  382.     if (notepadState !== 'idle') {
  383.         sendMsg("A notepad is already in progress. Please save or cancel it before creating a new one.");
  384.         return;
  385.     }
  386.  
  387.     const newNotepad = { id: notepadCounter++, content: "", created: new Date() };
  388.     notepads.push(newNotepad);
  389.     notepadState = 'created';
  390.     sendMsg(`New notepad created with ID: ${newNotepad.id}`);
  391. }
  392.  
  393. function writeOnNotepad(content) {
  394.     const currentNotepad = getCurrentNotepad();
  395.     if (!currentNotepad) return;
  396.  
  397.     currentNotepad.content += content + "\n";
  398.     notepadState = 'modified';
  399.     sendMsg("Content added to the current notepad.");
  400. }
  401.  
  402. function saveNotepad() {
  403.     const currentNotepad = getCurrentNotepad();
  404.     if (!currentNotepad) return;
  405.  
  406.     sendMsg(`Notepad ID ${currentNotepad.id} saved successfully.`);
  407.     console.log(`Saved Notepad Content:\n${currentNotepad.content}`);
  408.     notepads = notepads.map(np => (np.id === currentNotepad.id ? currentNotepad : np));
  409.     notepadState = 'idle';
  410. }
  411.  
  412. function listNotepads() {
  413.     if (notepads.length === 0) {
  414.         sendMsg("No notepads have been created yet.");
  415.         return;
  416.     }
  417.  
  418.     let response = "__List of Notepads__:\n";
  419.     for (const np of notepads) {
  420.         response += `ID: ${np.id}, Created On: ${np.created.toLocaleString()}, Content Length: ${np.content.length} characters\n`;
  421.     }
  422.     sendMsg(response);
  423. }
  424.  
  425. function deleteNotepad(id) {
  426.     const index = parseInt(id, 10) - 1;
  427.     if (index < 0 || index >= notepads.length) {
  428.         sendMsg("Invalid Notepad ID. Please provide a valid ID from the list.");
  429.         return;
  430.     }
  431.  
  432.     notepads.splice(index, 1);
  433.     sendMsg(`Deleted Notepad with ID: ${id}`);
  434. }
  435.  
  436. function modifyNotepad(id) {
  437.     const index = parseInt(id, 10) - 1;
  438.     if (index < 0 || index >= notepads.length) {
  439.         sendMsg("Invalid Notepad ID. Please provide a valid ID from the list.");
  440.         return;
  441.     }
  442.  
  443.     const selectedNotepad = notepads[index];
  444.     selectedNotepad.content += "\n"; // Open it for modification
  445.     notepads[index] = selectedNotepad;
  446.    
  447.     sendMsg(`Modifying Notedpad`);
  448. }
  449.  
  450. function readNotepad(id) {
  451.     const notepadId = parseInt(id, 10);
  452.     const selectedNotepad = notepads.find(np => np.id === notepadId);
  453.  
  454.     if (!selectedNotepad) {
  455.         sendMsg("Invalid Notepad ID. Please provide a valid ID from the list.");
  456.         return;
  457.     }
  458.  
  459.     if (selectedNotepad.content.trim() === "") {
  460.         sendMsg(`Notepad ID ${notepadId} is empty.`);
  461.     } else {
  462.         sendMsg(`__Content of Notepad ID ${notepadId}__:\n${selectedNotepad.content}`);
  463.     }
  464. }
  465.  
  466. // New calculator function
  467. function calculator(operation) {
  468.     const parts = operation.split(" ");
  469.     const operator = parts[1];
  470.     const a = parseFloat(parts[0]);
  471.     const b = parseFloat(parts[2]);
  472.  
  473.     let result;
  474.     switch (operator) {
  475.         case "+":
  476.             result = a + b;
  477.             break;
  478.         case "-":
  479.             result = a - b;
  480.             break;
  481.         case "*":
  482.             result = a * b;
  483.             break;
  484.         case "/":
  485.             result = a / b;
  486.             break;
  487.         default:
  488.             sendMsg("Invalid operation. Please use the format: 'num1 operator num2'. Supported operators are +, -, *, /.");
  489.             return;
  490.     }
  491.  
  492.     sendMsg(`Result: ${result}`);
  493. }
  494.  
  495. function googleSearch(searchQuery) {
  496.     const apiUrl = `https://www.googleapis.com/customsearch/v1?q=${encodeURIComponent(searchQuery)}&key=${GOOGLE_API_KEY}&cx=${GOOGLE_CX}`;
  497.  
  498.     fetch(apiUrl)
  499.         .then((response) => response.json())
  500.         .then((data) => {
  501.             if (data.items && data.items.length > 0) {
  502.                 const resultsText = data.items.slice(0, 2).map((item, index) => `${index+1}. ${item.title}\n   ${item.link}`).join("\n");
  503.                 sendMsg(`Google Search Results for '${searchQuery}':\n${resultsText}`);
  504.             } else {
  505.                 sendMsg(`No results found for '${searchQuery}'.`);
  506.             }
  507.         })
  508.         .catch((error) => {
  509.             console.error("Error fetching Google Search API:", error);
  510.             sendMsg("An error occurred while fetching Google Search results.");
  511.         });
  512. }
  513.  
  514. function translateText(translationQuery) {
  515.     const languages = {
  516.         english: 'en',
  517.         french: 'fr',
  518.         japanese: 'ja',
  519.         spanish: 'es',
  520.         german: 'de',
  521.         chinese: 'zh',
  522.         russian: 'ru',
  523.         italian: 'it',
  524.         portuguese: 'pt',
  525.         dutch: 'nl',
  526.         korean: 'ko',
  527.         arabic: 'ar',
  528.         hindi: 'hi',
  529.         greek: 'el',
  530.         swedish: 'sv',
  531.         turkish: 'tr',
  532.         vietnamese: 'vi',
  533.         thai: 'th',
  534.         hebrew: 'he',
  535.         polish: 'pl',
  536.         danish: 'da',
  537.         finnish: 'fi',
  538.         norwegian: 'no',
  539.         czech: 'cs',
  540.         hungarian: 'hu',
  541.         indonesian: 'id',
  542.         malay: 'ms',
  543.         romanian: 'ro',
  544.         bulgarian: 'bg',
  545.         croatian: 'hr',
  546.         slovak: 'sk',
  547.         ukrainian: 'uk'
  548.     };
  549.  
  550.     if (translationQuery.trim().toLowerCase() === "list languages") {
  551.         sendMsg("Supported languages are:\n" + Object.keys(languages).join(", "));
  552.         return;
  553.     }
  554.  
  555.     const [text, targetLanguage] = translationQuery.split(" to ");
  556.     if (!text || !targetLanguage) {
  557.         sendMsg("Invalid format. Use `" + prefix + "translate <text> to <target language>`.");
  558.         return;
  559.     }
  560.  
  561.     const targetLangCode = languages[targetLanguage.trim().toLowerCase()];
  562.     if (!targetLangCode) {
  563.         sendMsg("Invalid target language. Use `" + prefix + "translate list languages` to see supported languages.");
  564.         return;
  565.     }
  566.  
  567.     const apiUrl = "https://deep-translate1.p.rapidapi.com/language/translate/v2";
  568.  
  569.     const data = {
  570.         q: text.trim(),
  571.         target: targetLangCode
  572.     };
  573.  
  574.     fetch(apiUrl, {
  575.         method: "POST",
  576.         headers: {
  577.             "Content-Type": "application/json",
  578.             "X-RapidAPI-Host": "deep-translate1.p.rapidapi.com",
  579.             "X-RapidAPI-Key": TRANSLATE_API_KEY
  580.         },
  581.         body: JSON.stringify(data)
  582.     })
  583.     .then((response) => response.json())
  584.     .then((data) => {
  585.         if (data.data && data.data.translations) {
  586.             sendMsg(`Translation:\n"${text.trim()}""${data.data.translations.translatedText}"`);
  587.         } else {
  588.             sendMsg("Translation error. Please check the input and target language.");
  589.             console.error("Translation error:", data);
  590.         }
  591.     })
  592.     .catch((error) => {
  593.         console.error("Error:", error);
  594.         sendMsg("An error occurred while translating the text.");
  595.     });
  596. }
  597.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement