Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const prefix = "mem!";
- const botname = "Memphis (" + prefix + "start)";
- const version = "2.0.0";
- const update = "April 14th, 2025";
- var uses = 0;
- // External API URLs
- const PUTER_JS_URL = "https://js.puter.com/v2/";
- const WEATHER_API_KEY = "dcc6b2a3fa3d4fe58d9193316232905";
- const GOOGLE_API_KEY = "AIzaSyDQJ7SjasKcPq_bJhCyxuaoWiVydYTGDK0";
- const GOOGLE_CX = "c3619c6476b78442f"; // Custom Search Engine ID
- const TRANSLATE_API_KEY = "4a4725a769msh10c74bc91185a85p182f25jsn9a1a93fbbb77";
- // Load external script for AI
- const script = document.createElement("script");
- script.src = PUTER_JS_URL;
- document.head.appendChild(script);
- // Helper function to send messages
- function sendMsg(msg) {
- setTimeout(() => {
- socket.emit("talk", { text: msg });
- }, 1100);
- }
- // AI Query Function
- async function queryPuterAPI(inputText) {
- try {
- const response = await puter.ai.chat(inputText);
- return response || "The AI couldn't generate a proper response.";
- } catch (error) {
- console.error("Error querying Puter.js API:", error);
- return "Sorry, I couldn't process your request.";
- }
- }
- // Initialize bot
- setTimeout(() => {
- socket.emit("command", { list: ["name", botname] });
- }, 1000);
- setTimeout(() => {
- sendMsg(`${botname} is online. Type ${prefix}start for available commands.`);
- }, 2000);
- // Command handler
- socket.on("talk", async (message) => {
- const text = message.text.trim(); // Trim whitespace for cleaner parsing
- // Check if the message starts with the prefix
- if (!text.startsWith(prefix)) {
- return; // Ignore messages that don't start with the bot prefix
- }
- // Extract command and arguments
- const [command, ...args] = text.slice(prefix.length).split(" ");
- const argString = args.join(" ").trim();
- // Command Handling
- switch (command.toLowerCase()) {
- case "ask":
- if (!argString) {
- sendMsg(`Please provide a question or prompt after '${prefix}ask'.`);
- return;
- }
- sendMsg("- Processing your query...");
- const aiResponse = await queryPuterAPI(argString);
- sendMsg(`**AI Response:** ${aiResponse}`);
- uses++;
- break;
- case "start":
- sendMsg("__Project Memphis Start Menu__\n"
- + "- AI: `" + prefix + "ask {question}`\n"
- + "- Weather: `" + prefix + "weather {location}`\n"
- + "- Games: `" + prefix + "snake` or `" + prefix + "maze`\n"
- + "- Utilities: `" + prefix + "notepad`, `" + prefix + "calculator`, `" + prefix + "clock`\n"
- + "- Search: `" + prefix + "google {query}`, `" + prefix + "translate {text} to {language}`");
- break;
- case "weather":
- if (!argString) {
- sendMsg(`Please provide a location after '${prefix}weather'.`);
- return;
- }
- getWeather(argString);
- break;
- case "snake":
- handleSnakeCommand(argString);
- break;
- case "maze":
- handleMazeCommand(argString);
- break;
- case "clock":
- sendMsg(getCurrentTime());
- break;
- case "calculator":
- if (!argString) {
- sendMsg(`Please provide an operation after '${prefix}calculator'.`);
- return;
- }
- calculator(argString);
- break;
- case "notepad":
- handleNotepadCommand(argString);
- break;
- case "google":
- if (!argString) {
- sendMsg(`Please provide a search query after '${prefix}google'.`);
- return;
- }
- googleSearch(argString);
- break;
- case "translate":
- if (!argString) {
- sendMsg(`Please provide text and target language in the format '${prefix}translate <text> to <language>'.`);
- return;
- }
- translateText(argString);
- break;
- default:
- // Handle unrecognized commands gracefully
- sendMsg(`Invalid command. Type '${prefix}start' for a list of commands.`);
- }
- });
- // Utility Functions
- function getCurrentTime() {
- const now = new Date();
- return `Current time is: ${now.toLocaleTimeString("en-US", { hour12: true })}`;
- }
- function getWeather(location) {
- const apiUrl = `https://api.weatherapi.com/v1/current.json?key=${WEATHER_API_KEY}&q=${encodeURIComponent(location)}`;
- fetch(apiUrl)
- .then((response) => response.json())
- .then((data) => {
- if (data.error) {
- sendMsg("Unable to retrieve weather information. Please check the location.");
- } else {
- 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`;
- sendMsg(weatherInfo);
- }
- })
- .catch((error) => {
- console.error("Error:", error);
- sendMsg("An error occurred while retrieving weather information.");
- });
- }
- // Snake Game Variables
- let snake = [{ x: 0, y: 0 }]; // Snake's initial position
- let food = { x: 5, y: 5 }; // Food's initial position
- let direction = "right"; // Initial direction of the snake
- function handleSnakeCommand(command) {
- if (command === "play") {
- startSnakeGame();
- } else if (["up", "down", "left", "right"].includes(command)) {
- updateSnakeDirection(command);
- moveSnake();
- if (checkCollision()) {
- sendMsg("Game Over! You collided with the wall or yourself.");
- return;
- }
- checkFoodEaten();
- sendMsg(renderSnakeGame());
- } else {
- sendMsg(`Invalid command. Use \`${prefix}snake play\` to start the game and \`${prefix}snake up/down/left/right\` to control.`);
- }
- }
- function startSnakeGame() {
- snake = [{ x: 0, y: 0 }];
- food = { x: Math.floor(Math.random() * 14), y: Math.floor(Math.random() * 6) };
- direction = "right";
- sendMsg(renderSnakeGame());
- }
- function updateSnakeDirection(command) {
- if (command === "up" && direction !== "down") direction = "up";
- else if (command === "down" && direction !== "up") direction = "down";
- else if (command === "left" && direction !== "right") direction = "left";
- else if (command === "right" && direction !== "left") direction = "right";
- }
- function moveSnake() {
- const head = { ...snake[0] };
- if (direction === "up") head.y--;
- else if (direction === "down") head.y++;
- else if (direction === "left") head.x--;
- else if (direction === "right") head.x++;
- snake.unshift(head);
- }
- function checkCollision() {
- const head = snake[0];
- if (head.x < 0 || head.x >= 14 || head.y < 0 || head.y >= 6) return true; // Wall collision
- for (let i = 1; i < snake.length; i++) {
- if (snake[i].x === head.x && snake[i].y === head.y) return true; // Self-collision
- }
- return false;
- }
- function checkFoodEaten() {
- const head = snake[0];
- if (head.x === food.x && head.y === food.y) {
- food = { x: Math.floor(Math.random() * 14), y: Math.floor(Math.random() * 6) };
- } else {
- snake.pop(); // Remove tail to maintain length
- }
- }
- function renderSnakeGame() {
- let board = Array.from({ length: 6 }, () => Array(14).fill(0));
- for (const segment of snake) board[segment.y][segment.x] = 1;
- board[food.y][food.x] = 2;
- return board.map(row => row.join(" ")).join("\n");
- }
- function handleMazeCommand(command) {
- if (command === "play") {
- startMazeGame();
- } else if (command === "up" || command === "down" || command === "left" || command === "right") {
- movePlayer(command);
- } else if (command === "guide") {
- sendMsg("Welcome to mem!maze!\n\n"
- + "You are represented by the number 9, and your goal is to reach the number 3.\n"
- + "Use `" + prefix + "maze up/down/left/right` to move in the maze.\n"
- + "Good luck!");
- } else {
- 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.");
- }
- }
- // Maze Game Variables
- const mazeRows = 6;
- const mazeColumns = 14;
- const wallChance = 0.3;
- let maze;
- let playerPosition;
- let goalPosition;
- function handleMazeCommand(command) {
- if (command === "play") {
- startMazeGame();
- } else if (["up", "down", "left", "right"].includes(command)) {
- movePlayer(command);
- } else if (command === "guide") {
- 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!`);
- } else {
- 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.`);
- }
- }
- function startMazeGame() {
- maze = generateRandomMaze();
- playerPosition = { x: Math.floor(mazeColumns / 2), y: mazeRows - 1 };
- maze[playerPosition.y][playerPosition.x] = 9;
- goalPosition = generateRandomGoalPosition();
- maze[goalPosition.y][goalPosition.x] = 3;
- sendMsg(renderMaze());
- }
- function generateRandomMaze() {
- return Array.from({ length: mazeRows }, () =>
- Array.from({ length: mazeColumns }, () => Math.random() < wallChance ? 1 : 0)
- );
- }
- function generateRandomGoalPosition() {
- let x, y;
- do {
- x = Math.floor(Math.random() * mazeColumns);
- y = Math.floor(Math.random() * mazeRows);
- } while (maze[y][x] !== 0);
- return { x, y };
- }
- function movePlayer(command) {
- const { x, y } = playerPosition;
- let newX = x, newY = y;
- if (command === "up") newY--;
- else if (command === "down") newY++;
- else if (command === "left") newX--;
- else if (command === "right") newX++;
- if (newX >= 0 && newX < mazeColumns && newY >= 0 && newY < mazeRows && maze[newY][newX] !== 1) {
- maze[y][x] = 0; // Clear previous position
- playerPosition = { x: newX, y: newY };
- maze[newY][newX] = 9; // Update player position
- if (newX === goalPosition.x && newY === goalPosition.y) {
- sendMsg("Congratulations! You reached the goal!");
- startMazeGame(); // Restart game
- return;
- }
- sendMsg(renderMaze());
- } else {
- sendMsg("You cannot move in that direction.");
- sendMsg(renderMaze());
- }
- }
- function renderMaze() {
- return maze.map(row => row.join(" ")).join("\n");
- }
- // Notepad Variables
- let notepads = [];
- let notepadCounter = 1;
- let notepadState = 'idle'; // Tracks the state of the current notepad
- function handleNotepadCommand(command) {
- const [action, ...args] = command.split(" ");
- const content = args.join(" ").trim();
- switch (action.toLowerCase()) {
- case "create":
- createNotepad();
- break;
- case "write":
- if (!content) {
- sendMsg("Please provide content to write. Example: `mem!notepad write This is my note.`");
- } else {
- writeOnNotepad(content);
- }
- break;
- case "save":
- saveNotepad();
- break;
- case "list":
- listNotepads();
- break;
- case "delete":
- if (!args[0]) {
- sendMsg("Please provide a notepad ID to delete. Example: `mem!notepad delete 1`.");
- } else {
- deleteNotepad(args[0]);
- }
- break;
- case "modify":
- if (!args[0]) {
- sendMsg("Please provide a notepad ID to modify. Example: `mem!notepad modify 1`.");
- } else {
- modifyNotepad(args[0]);
- }
- break;
- case "read":
- if (!args[0]) {
- sendMsg("Please provide a notepad ID to read. Example: `mem!notepad read 1`.");
- } else {
- readNotepad(args[0]);
- }
- break;
- default:
- sendMsg(`Invalid command. Use \`${prefix}notepad create/write/save/list/delete/modify/read\`.`);
- }
- }
- function createNotepad() {
- if (notepadState !== 'idle') {
- sendMsg("A notepad is already in progress. Please save or cancel it before creating a new one.");
- return;
- }
- const newNotepad = { id: notepadCounter++, content: "", created: new Date() };
- notepads.push(newNotepad);
- notepadState = 'created';
- sendMsg(`New notepad created with ID: ${newNotepad.id}`);
- }
- function writeOnNotepad(content) {
- const currentNotepad = getCurrentNotepad();
- if (!currentNotepad) return;
- currentNotepad.content += content + "\n";
- notepadState = 'modified';
- sendMsg("Content added to the current notepad.");
- }
- function saveNotepad() {
- const currentNotepad = getCurrentNotepad();
- if (!currentNotepad) return;
- sendMsg(`Notepad ID ${currentNotepad.id} saved successfully.`);
- console.log(`Saved Notepad Content:\n${currentNotepad.content}`);
- notepads = notepads.map(np => (np.id === currentNotepad.id ? currentNotepad : np));
- notepadState = 'idle';
- }
- function listNotepads() {
- if (notepads.length === 0) {
- sendMsg("No notepads have been created yet.");
- return;
- }
- let response = "__List of Notepads__:\n";
- for (const np of notepads) {
- response += `ID: ${np.id}, Created On: ${np.created.toLocaleString()}, Content Length: ${np.content.length} characters\n`;
- }
- sendMsg(response);
- }
- function deleteNotepad(id) {
- const index = parseInt(id, 10) - 1;
- if (index < 0 || index >= notepads.length) {
- sendMsg("Invalid Notepad ID. Please provide a valid ID from the list.");
- return;
- }
- notepads.splice(index, 1);
- sendMsg(`Deleted Notepad with ID: ${id}`);
- }
- function modifyNotepad(id) {
- const index = parseInt(id, 10) - 1;
- if (index < 0 || index >= notepads.length) {
- sendMsg("Invalid Notepad ID. Please provide a valid ID from the list.");
- return;
- }
- const selectedNotepad = notepads[index];
- selectedNotepad.content += "\n"; // Open it for modification
- notepads[index] = selectedNotepad;
- sendMsg(`Modifying Notedpad`);
- }
- function readNotepad(id) {
- const notepadId = parseInt(id, 10);
- const selectedNotepad = notepads.find(np => np.id === notepadId);
- if (!selectedNotepad) {
- sendMsg("Invalid Notepad ID. Please provide a valid ID from the list.");
- return;
- }
- if (selectedNotepad.content.trim() === "") {
- sendMsg(`Notepad ID ${notepadId} is empty.`);
- } else {
- sendMsg(`__Content of Notepad ID ${notepadId}__:\n${selectedNotepad.content}`);
- }
- }
- // New calculator function
- function calculator(operation) {
- const parts = operation.split(" ");
- const operator = parts[1];
- const a = parseFloat(parts[0]);
- const b = parseFloat(parts[2]);
- let result;
- switch (operator) {
- case "+":
- result = a + b;
- break;
- case "-":
- result = a - b;
- break;
- case "*":
- result = a * b;
- break;
- case "/":
- result = a / b;
- break;
- default:
- sendMsg("Invalid operation. Please use the format: 'num1 operator num2'. Supported operators are +, -, *, /.");
- return;
- }
- sendMsg(`Result: ${result}`);
- }
- function googleSearch(searchQuery) {
- const apiUrl = `https://www.googleapis.com/customsearch/v1?q=${encodeURIComponent(searchQuery)}&key=${GOOGLE_API_KEY}&cx=${GOOGLE_CX}`;
- fetch(apiUrl)
- .then((response) => response.json())
- .then((data) => {
- if (data.items && data.items.length > 0) {
- const resultsText = data.items.slice(0, 2).map((item, index) => `${index+1}. ${item.title}\n ${item.link}`).join("\n");
- sendMsg(`Google Search Results for '${searchQuery}':\n${resultsText}`);
- } else {
- sendMsg(`No results found for '${searchQuery}'.`);
- }
- })
- .catch((error) => {
- console.error("Error fetching Google Search API:", error);
- sendMsg("An error occurred while fetching Google Search results.");
- });
- }
- function translateText(translationQuery) {
- const languages = {
- english: 'en',
- french: 'fr',
- japanese: 'ja',
- spanish: 'es',
- german: 'de',
- chinese: 'zh',
- russian: 'ru',
- italian: 'it',
- portuguese: 'pt',
- dutch: 'nl',
- korean: 'ko',
- arabic: 'ar',
- hindi: 'hi',
- greek: 'el',
- swedish: 'sv',
- turkish: 'tr',
- vietnamese: 'vi',
- thai: 'th',
- hebrew: 'he',
- polish: 'pl',
- danish: 'da',
- finnish: 'fi',
- norwegian: 'no',
- czech: 'cs',
- hungarian: 'hu',
- indonesian: 'id',
- malay: 'ms',
- romanian: 'ro',
- bulgarian: 'bg',
- croatian: 'hr',
- slovak: 'sk',
- ukrainian: 'uk'
- };
- if (translationQuery.trim().toLowerCase() === "list languages") {
- sendMsg("Supported languages are:\n" + Object.keys(languages).join(", "));
- return;
- }
- const [text, targetLanguage] = translationQuery.split(" to ");
- if (!text || !targetLanguage) {
- sendMsg("Invalid format. Use `" + prefix + "translate <text> to <target language>`.");
- return;
- }
- const targetLangCode = languages[targetLanguage.trim().toLowerCase()];
- if (!targetLangCode) {
- sendMsg("Invalid target language. Use `" + prefix + "translate list languages` to see supported languages.");
- return;
- }
- const apiUrl = "https://deep-translate1.p.rapidapi.com/language/translate/v2";
- const data = {
- q: text.trim(),
- target: targetLangCode
- };
- fetch(apiUrl, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "X-RapidAPI-Host": "deep-translate1.p.rapidapi.com",
- "X-RapidAPI-Key": TRANSLATE_API_KEY
- },
- body: JSON.stringify(data)
- })
- .then((response) => response.json())
- .then((data) => {
- if (data.data && data.data.translations) {
- sendMsg(`Translation:\n"${text.trim()}" → "${data.data.translations.translatedText}"`);
- } else {
- sendMsg("Translation error. Please check the input and target language.");
- console.error("Translation error:", data);
- }
- })
- .catch((error) => {
- console.error("Error:", error);
- sendMsg("An error occurred while translating the text.");
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement