Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // TextWall Bot - diamondbot v7.0
- // Fixed recursion and enhanced features
- (async function() {
- 'use strict';
- // Verify tw.2s4.me API is available
- if (typeof w === 'undefined') {
- console.error("TextWall API (w) not found! Make sure you're on tw.2s4.me");
- return;
- }
- // Bot Configuration
- const BOT_CONFIG = {
- username: "diamondbot",
- color: 0, // Color index (0-15 for textwall)
- prefix: "\\", // Changed prefix to backslash
- authorizedUsers: ["Diamond25", "KiwiTest"], // List of authorized users
- messageDelay: 150, // Delay between messages in ms
- position: { x: 0, y: 0 },
- heightSafetyEnabled: true, // Height safety for tetration
- lastAuthorityMessage: "", // Track last authority message to prevent recursion
- authorityEchoEnabled: false // Toggle authority echo to prevent recursion
- };
- // State management
- const state = {
- wall: "",
- subwall: "",
- perms: 0, // 0=user, 1=member, 2=owner
- isRegistered: false,
- isAdmin: false,
- readonly: false,
- hidecursors: false,
- disablechat: false,
- disablecolor: false,
- disablebraille: false,
- members: [],
- walllist: [],
- activeTimers: new Map(),
- commandCooldowns: new Map(),
- messageQueue: [],
- isProcessingQueue: false,
- lastMessageTime: 0,
- cursors: new Map(),
- adminUsers: new Set(), // Track users with ADMIN tag
- processedMessages: new Set() // Track processed messages to prevent recursion
- };
- // Color mappings for textwall
- const COLORS = {
- "#000000": 0, "#ffffff": 1, "#ff0000": 2, "#00ff00": 3,
- "#0000ff": 4, "#ffff00": 5, "#ff00ff": 6, "#00ffff": 7,
- "#808080": 8, "#ff8800": 9, "#8800ff": 10, "#0088ff": 11,
- "#88ff00": 12, "#ff0088": 13, "#884400": 14, "#448800": 15
- };
- // Command pages
- const COMMAND_PAGES = {
- 1: [
- { cmd: "help", desc: "Show command pages", auth: false },
- { cmd: "phelp", desc: "Print all commands", auth: false },
- { cmd: "calculate", desc: "Calculate p1^p2", auth: false },
- { cmd: "calc2", desc: "Calculate p1^^p2 (tetration)", auth: false },
- { cmd: "rng", desc: "Random number between min and max", auth: false }
- ],
- 2: [
- { cmd: "timer", desc: "Set a timer (h m s)", auth: false },
- { cmd: "say", desc: "Make bot say something", auth: false },
- { cmd: "status", desc: "Show bot status", auth: false },
- { cmd: "pos", desc: "Show current position", auth: false },
- { cmd: "page", desc: "Show detailed page info", auth: false }
- ],
- 3: [
- { cmd: "members", desc: "List wall members", auth: false },
- { cmd: "walls", desc: "List available subwalls", auth: false },
- { cmd: "authlist", desc: "Show authorized users", auth: false },
- { cmd: "to", desc: "Teleport bot to X Y (Authority)", auth: true },
- { cmd: "colorid", desc: "Change bot color (Authority)", auth: true }
- ],
- 4: [
- { cmd: "addauth", desc: "Add user to authority list (Authority)", auth: true },
- { cmd: "removeauth", desc: "Remove user from authority (Authority)", auth: true },
- { cmd: "disableHS", desc: "Toggle height safety (Authority)", auth: true },
- { cmd: "echoauth", desc: "Toggle authority echo (Authority)", auth: true }
- ]
- };
- // Load break_eternity.js
- async function loadBreakEternity() {
- if (typeof window.Decimal !== 'undefined') {
- console.log("✓ Break Eternity already loaded");
- return true;
- }
- const sources = [
- 'https://cdn.jsdelivr.net/npm/break_eternity.js@latest/break_eternity.min.js',
- 'https://unpkg.com/break_eternity.js@latest/dist/break_eternity.min.js',
- 'https://cdnjs.cloudflare.com/ajax/libs/break_eternity.js/1.3.0/break_eternity.min.js'
- ];
- for (let src of sources) {
- try {
- await loadScript(src);
- if (typeof window.Decimal !== 'undefined') {
- console.log(`✓ Break Eternity loaded from: ${src}`);
- return true;
- }
- } catch (e) {
- console.warn(`Failed to load from ${src}`);
- }
- }
- // Fallback implementation
- window.Decimal = createFallbackDecimal();
- console.log("✓ Using fallback Decimal implementation");
- return true;
- }
- function loadScript(src) {
- return new Promise((resolve, reject) => {
- const script = document.createElement('script');
- script.src = src;
- script.onload = resolve;
- script.onerror = reject;
- document.head.appendChild(script);
- });
- }
- function createFallbackDecimal() {
- return class Decimal {
- constructor(value) {
- this.value = typeof value === 'string' || typeof value === 'number'
- ? parseFloat(value) || 0
- : value?.value || 0;
- }
- static pow(base, exp) {
- const b = base instanceof Decimal ? base.value : parseFloat(base);
- const e = exp instanceof Decimal ? exp.value : parseFloat(exp);
- if (e === 0) return new Decimal(1);
- if (b === 0) return new Decimal(0);
- let result;
- if (Math.abs(e) > 308) {
- result = e > 0 ? Infinity : 0;
- } else {
- result = Math.pow(b, e);
- }
- return new Decimal(result);
- }
- static tetrate(base, height) {
- const b = base instanceof Decimal ? base.value : parseFloat(base);
- const h = parseInt(height);
- if (h === 0) return new Decimal(1);
- if (h === 1) return new Decimal(b);
- if (b === 0) return new Decimal(0);
- const maxHeight = BOT_CONFIG.heightSafetyEnabled ? 5 : 10;
- let result = b;
- for (let i = 1; i < h && i < maxHeight; i++) {
- result = Math.pow(b, result);
- if (!isFinite(result)) break;
- }
- return new Decimal(result);
- }
- toString() {
- if (!isFinite(this.value)) return this.value > 0 ? "Infinity" : "-Infinity";
- if (Math.abs(this.value) < 1e-6) return "0";
- if (Math.abs(this.value) < 1e6 && Math.abs(this.value) > 1e-3) {
- return this.value.toString();
- }
- return this.value.toExponential(2);
- }
- };
- }
- // Main Bot Class
- class TextWallBot {
- constructor(config) {
- this.config = config;
- this.state = state;
- this.eventHandlers = {};
- this.running = true;
- }
- async init() {
- console.log("═══════════════════════════════════");
- console.log(" TextWall Bot v7.0 Initializing ");
- console.log("═══════════════════════════════════");
- // Load dependencies
- await loadBreakEternity();
- // Set up all event listeners
- this.setupEventListeners();
- // Set username
- this.setUsername(this.config.username);
- // Set initial color
- this.setColor(this.config.color);
- // Initial position
- this.teleportCursor(0, 0);
- // Announce bot is online after a short delay
- setTimeout(() => {
- this.sendMessage(`${this.config.username} v7.0 online! Type ${this.config.prefix}help for commands`);
- }, 2000);
- console.log("✓ Bot initialized successfully!");
- console.log(`✓ Prefix: ${this.config.prefix}`);
- console.log(`✓ Authorized users: ${this.config.authorizedUsers.join(', ')}`);
- console.log("═══════════════════════════════════");
- }
- setupEventListeners() {
- // Store handlers for cleanup
- this.eventHandlers = {
- // Connection events
- join: (data) => this.onJoin(data),
- alert: (data) => this.onAlert(data),
- // Chat events
- msg: (data) => this.onMessage(data),
- // Editor events
- edit: (data) => this.onEdit(data),
- protect: (data) => this.onProtect(data),
- clear: (data) => this.onClear(data),
- // Cursor events
- cursor: (data) => this.onCursor(data),
- cursorleft: (id) => this.onCursorLeft(id),
- // Permission events
- perms: (level) => this.onPerms(level),
- memberadded: (member) => this.onMemberAdded(member),
- memberlist: (members) => this.onMemberList(members),
- walllist: (walls) => this.onWallList(walls),
- // State events
- readonly: (state) => this.onReadonly(state),
- hidecursors: (state) => this.onHideCursors(state),
- disablechat: (state) => this.onDisableChat(state),
- disablecolor: (state) => this.onDisableColor(state),
- disablebraille: (state) => this.onDisableBraille(state),
- // Account events
- nametaken: () => this.onNameTaken(),
- passfail: () => this.onPassFail(),
- tokenfail: () => this.onTokenFail(),
- regclosed: () => this.onRegClosed(),
- namechanged: (name) => this.onNameChanged(name),
- accountdeleted: () => this.onAccountDeleted(),
- // Heartbeat
- pong: (ms) => this.onPong(ms)
- };
- // Register all event listeners
- for (let [event, handler] of Object.entries(this.eventHandlers)) {
- if (w && w.on) {
- w.on(event, handler);
- }
- }
- console.log(`✓ Registered ${Object.keys(this.eventHandlers).length} event listeners`);
- }
- cleanup() {
- this.running = false;
- // Remove all event listeners
- for (let [event, handler] of Object.entries(this.eventHandlers)) {
- if (w && w.off) {
- w.off(event, handler);
- }
- }
- // Clear timers
- this.state.activeTimers.forEach(timer => {
- clearTimeout(timer.timeout);
- if (timer.intervalId) clearInterval(timer.intervalId);
- });
- console.log("✓ Bot cleaned up");
- }
- // Check if user has authority
- isAuthorized(username, isAdmin) {
- // Admins always have authority
- if (isAdmin) {
- this.state.adminUsers.add(username);
- return true;
- }
- // Check if user is in authorized list
- return this.config.authorizedUsers.includes(username);
- }
- // Event Handlers
- onJoin(data) {
- this.state.wall = data.wall || "";
- this.state.subwall = data.subwall || "";
- console.log(`📍 Joined: ${this.state.wall}/${this.state.subwall}`);
- }
- onAlert(data) {
- console.log(`⚠️ Server Alert: ${data.message}`);
- }
- onMessage(data) {
- if (!data || !data.msg) return;
- // Skip bot's own messages to prevent recursion
- if (data.nick === this.config.username) return;
- const message = data.msg.trim();
- const sender = data.nick || "Unknown";
- const isAdmin = data.isAdmin || false;
- // Create unique message ID to prevent duplicate processing
- const messageId = `${sender}-${message}-${Date.now()}`;
- // Skip if already processed (prevents recursion)
- if (this.state.processedMessages.has(messageId)) return;
- // Mark as processed
- this.state.processedMessages.add(messageId);
- // Clean up old processed messages (keep only last 100)
- if (this.state.processedMessages.size > 100) {
- const messages = Array.from(this.state.processedMessages);
- messages.slice(0, messages.length - 100).forEach(msg => {
- this.state.processedMessages.delete(msg);
- });
- }
- // Track admin users
- if (isAdmin) {
- this.state.adminUsers.add(sender);
- }
- // Check authority
- const hasAuth = this.isAuthorized(sender, isAdmin);
- // Log message with authority indicator if applicable
- if (hasAuth) {
- console.log(`🔑 [AUTHORITY] ${sender} ~ ${message}`);
- // Only echo authority messages if enabled AND it's not a command AND not a duplicate
- if (this.config.authorityEchoEnabled &&
- !message.startsWith(this.config.prefix) &&
- this.config.lastAuthorityMessage !== `${sender}:${message}`) {
- this.config.lastAuthorityMessage = `${sender}:${message}`;
- this.sendMessage(`[AUTHORITY] ${sender} ~ ${message}`);
- }
- } else {
- console.log(`💬 [${sender}${data.isRegistered ? ' ®' : ''}]: ${message}`);
- }
- // Check for commands
- if (message.startsWith(this.config.prefix)) {
- this.handleCommand(message, sender, data);
- }
- }
- onEdit(data) {
- if (data.edits && data.edits.length > 0) {
- console.log(`✏️ ${data.edits.length} edit(s) made`);
- }
- }
- onProtect(data) {
- console.log(`🔒 Chunk ${data.cell} protection: ${data.protect ? 'ON' : 'OFF'}`);
- }
- onClear(data) {
- console.log(`🧹 Area cleared: (${data.x1},${data.y1}) to (${data.x2},${data.y2})`);
- }
- onCursor(data) {
- if (!data.id) return;
- this.state.cursors.set(data.id, {
- name: data.n || "",
- location: data.l || [0, 0],
- color: data.c || 0
- });
- if (data.n === this.config.username && data.l) {
- this.config.position.x = data.l[0];
- this.config.position.y = data.l[1];
- }
- }
- onCursorLeft(id) {
- this.state.cursors.delete(id);
- }
- onPerms(level) {
- this.state.perms = level;
- const permName = ['User', 'Member', 'Owner'][level] || 'Unknown';
- console.log(`🔑 Permission level: ${permName} (${level})`);
- }
- onMemberAdded(member) {
- console.log(`➕ Member added: ${member}`);
- if (!this.state.members.includes(member)) {
- this.state.members.push(member);
- }
- }
- onMemberList(members) {
- this.state.members = members || [];
- console.log(`👥 Members: ${this.state.members.join(', ') || 'None'}`);
- }
- onWallList(walls) {
- this.state.walllist = walls || [];
- console.log(`📋 Available walls: ${walls.length / 2} wall(s)`);
- }
- onReadonly(state) {
- this.state.readonly = state;
- if (state) console.log("📝 Wall is now READONLY");
- }
- onHideCursors(state) {
- this.state.hidecursors = state;
- if (state) console.log("👤 Cursors are now HIDDEN");
- }
- onDisableChat(state) {
- this.state.disablechat = state;
- if (state) console.log("🔇 Chat is DISABLED");
- }
- onDisableColor(state) {
- this.state.disablecolor = state;
- if (state) console.log("🎨 Colors are DISABLED");
- }
- onDisableBraille(state) {
- this.state.disablebraille = state;
- if (state) console.log("⠿ Braille is DISABLED");
- }
- onNameTaken() {
- console.log("❌ Name is already taken!");
- }
- onPassFail() {
- console.log("❌ Invalid password!");
- }
- onTokenFail() {
- console.log("❌ Invalid token!");
- }
- onRegClosed() {
- console.log("❌ Registration is closed!");
- }
- onNameChanged(name) {
- console.log(`✅ Name changed to: ${name}`);
- this.config.username = name;
- }
- onAccountDeleted() {
- console.log("❌ Account has been deleted!");
- }
- onPong(ms) {
- // Heartbeat
- }
- // Command handling
- handleCommand(message, sender, messageData) {
- const commandLine = message.slice(this.config.prefix.length);
- const [command, ...args] = commandLine.split(/\s+/);
- const cmd = command.toLowerCase();
- // Check cooldown
- const cooldownKey = `${cmd}-${sender}`;
- const lastUsed = this.state.commandCooldowns.get(cooldownKey) || 0;
- const now = Date.now();
- const hasAuth = this.isAuthorized(sender, messageData.isAdmin);
- if (now - lastUsed < 2000 && !hasAuth) {
- return; // 2 second cooldown (except for authorized users)
- }
- this.state.commandCooldowns.set(cooldownKey, now);
- // Execute command
- this.executeCommand(cmd, args, sender, messageData);
- }
- executeCommand(command, args, sender, messageData) {
- const hasAuth = this.isAuthorized(sender, messageData.isAdmin);
- const commands = {
- // Basic commands
- 'help': () => this.cmdHelp(args),
- 'phelp': () => this.cmdPrintHelp(),
- 'calculate': () => this.cmdCalculate(args),
- 'calc2': () => this.cmdTetration(args),
- 'rng': () => this.cmdRandom(args),
- // General commands
- 'timer': () => this.cmdTimer(args),
- 'say': () => this.cmdSay(args),
- 'status': () => this.cmdStatus(),
- 'pos': () => this.cmdPosition(),
- 'page': () => this.cmdPage(args),
- // Info commands
- 'members': () => this.cmdMembers(),
- 'walls': () => this.cmdWalls(),
- 'authlist': () => this.cmdAuthList(),
- // Authority commands
- 'to': () => hasAuth ? this.cmdTeleport(args) : this.sendMessage("Permission invalid - Authority required"),
- 'colorid': () => hasAuth ? this.cmdColor(args) : this.sendMessage("Permission invalid"),
- 'addauth': () => hasAuth ? this.cmdAddAuth(args) : this.sendMessage("Permission invalid - Authority required"),
- 'removeauth': () => hasAuth ? this.cmdRemoveAuth(args) : this.sendMessage("Permission invalid - Authority required"),
- 'disablehs': () => hasAuth ? this.cmdDisableHeightSafety() : this.sendMessage("Permission invalid - Authority required"),
- 'echoauth': () => hasAuth ? this.cmdToggleEcho() : this.sendMessage("Permission invalid - Authority required")
- };
- const cmdFunc = commands[command];
- if (cmdFunc) {
- cmdFunc();
- }
- }
- // Commands
- cmdHelp(args) {
- const page = parseInt(args[0]) || 1;
- const maxPage = Object.keys(COMMAND_PAGES).length;
- if (page < 1 || page > maxPage) {
- this.sendMessage(`Invalid page. Use ${this.config.prefix}help 1-${maxPage}`);
- return;
- }
- // Send page header
- this.sendMessage(`📖 Commands Page ${page}/${maxPage}:`);
- // Send each command as separate message
- const commands = COMMAND_PAGES[page];
- commands.forEach((cmd, index) => {
- setTimeout(() => {
- this.sendMessage(`${this.config.prefix}${cmd.cmd}${cmd.auth ? ' 🔐' : ''} - ${cmd.desc}`);
- }, (index + 1) * 200);
- });
- }
- cmdPrintHelp() {
- this.sendMessage("📚 All Commands:");
- let delay = 200;
- for (let pageNum in COMMAND_PAGES) {
- const page = COMMAND_PAGES[pageNum];
- setTimeout(() => {
- this.sendMessage(`── Page ${pageNum} ──`);
- }, delay);
- delay += 200;
- page.forEach(cmd => {
- setTimeout(() => {
- this.sendMessage(`${this.config.prefix}${cmd.cmd}${cmd.auth ? ' 🔐' : ''} - ${cmd.desc}`);
- }, delay);
- delay += 200;
- });
- }
- }
- cmdPage(args) {
- const page = parseInt(args[0]) || 1;
- const maxPage = Object.keys(COMMAND_PAGES).length;
- if (page < 1 || page > maxPage) {
- this.sendMessage(`Invalid page. Pages: 1-${maxPage}`);
- return;
- }
- this.sendMessage(`📄 Page ${page} Detailed Info:`);
- const commands = COMMAND_PAGES[page];
- commands.forEach((cmd, i) => {
- setTimeout(() => {
- this.sendMessage(`${i+1}. ${this.config.prefix}${cmd.cmd} - ${cmd.desc}`);
- }, (i + 1) * 200);
- });
- }
- cmdSay(args) {
- if (args.length < 1) {
- this.sendMessage(`Usage: ${this.config.prefix}say [message]`);
- return;
- }
- const message = args.join(' ');
- this.sendMessage(message);
- }
- cmdCalculate(args) {
- if (args.length < 2) {
- this.sendMessage(`Usage: ${this.config.prefix}calculate base exponent`);
- return;
- }
- try {
- const base = args[0];
- const exp = args[1];
- const result = window.Decimal.pow(new window.Decimal(base), new window.Decimal(exp));
- this.sendMessage(`${base}^${exp} = ${result.toString()}`);
- } catch (error) {
- this.sendMessage("Error: Invalid input for calculation");
- }
- }
- cmdTetration(args) {
- if (args.length < 2) {
- this.sendMessage(`Usage: ${this.config.prefix}calc2 base height`);
- return;
- }
- try {
- const base = args[0];
- const height = parseInt(args[1]);
- if (height < 0 || !Number.isInteger(height)) {
- this.sendMessage("Height must be a non-negative integer");
- return;
- }
- const maxHeight = this.config.heightSafetyEnabled ? 5 : 10;
- if (height > maxHeight) {
- this.sendMessage(`Height too large! Maximum is ${maxHeight}${this.config.heightSafetyEnabled ? ' (Height Safety ON)' : ' (Height Safety OFF)'}`);
- return;
- }
- const result = window.Decimal.tetrate(new window.Decimal(base), height);
- this.sendMessage(`${base}^^${height} = ${result.toString()}`);
- } catch (error) {
- this.sendMessage("Error: Invalid input for tetration");
- }
- }
- cmdRandom(args) {
- if (args.length < 2) {
- this.sendMessage(`Usage: ${this.config.prefix}rng min max`);
- return;
- }
- const min = parseFloat(args[0]);
- const max = parseFloat(args[1]);
- if (isNaN(min) || isNaN(max)) {
- this.sendMessage("Invalid input. Please provide valid numbers.");
- return;
- }
- if (min > max) {
- this.sendMessage("Min must be less than or equal to max.");
- return;
- }
- const randomNum = Math.random() * (max - min) + min;
- this.sendMessage(`Random number between ${min} and ${max}: ${randomNum.toFixed(2)}`);
- }
- cmdTimer(args) {
- if (args.length < 3) {
- this.sendMessage(`Usage: ${this.config.prefix}timer hours minutes seconds (use 0 to skip)`);
- return;
- }
- const hours = Math.max(0, parseInt(args[0]) || 0);
- const minutes = Math.max(0, parseInt(args[1]) || 0);
- const seconds = Math.max(0, parseInt(args[2]) || 0);
- if (hours === 0 && minutes === 0 && seconds === 0) {
- this.sendMessage("Timer must have at least one non-zero value");
- return;
- }
- if (hours > 24) {
- this.sendMessage("Maximum timer is 24 hours");
- return;
- }
- const totalMs = (hours * 3600 + minutes * 60 + seconds) * 1000;
- // Build display string (ignore 0 values)
- let timeStr = [];
- if (hours > 0) timeStr.push(`${hours}h`);
- if (minutes > 0) timeStr.push(`${minutes}m`);
- if (seconds > 0) timeStr.push(`${seconds}s`);
- const timerId = Date.now();
- this.sendMessage(`⏰ Timer set for ${timeStr.join(' ')} (ID: ${timerId})`);
- // Create timer
- const timerObj = setTimeout(() => {
- this.sendMessage(`⏰ TIMER COMPLETE! ${timeStr.join(' ')} has elapsed (ID: ${timerId})`);
- this.state.activeTimers.delete(timerId);
- }, totalMs);
- // Store timer
- this.state.activeTimers.set(timerId, {
- timeout: timerObj,
- duration: timeStr.join(' '),
- startTime: Date.now(),
- endTime: Date.now() + totalMs
- });
- // Progress updates for long timers
- if (totalMs > 60000) {
- let updateCount = 0;
- const maxUpdates = 3;
- const updateInterval = Math.max(30000, totalMs / 4);
- const intervalId = setInterval(() => {
- const timer = this.state.activeTimers.get(timerId);
- if (!timer || updateCount >= maxUpdates) {
- clearInterval(intervalId);
- return;
- }
- const remaining = timer.endTime - Date.now();
- if (remaining > 1000) {
- const h = Math.floor(remaining / 3600000);
- const m = Math.floor((remaining % 3600000) / 60000);
- const s = Math.floor((remaining % 60000) / 1000);
- let remStr = [];
- if (h > 0) remStr.push(`${h}h`);
- if (m > 0) remStr.push(`${m}m`);
- if (s > 0) remStr.push(`${s}s`);
- this.sendMessage(`⏰ Timer ${timerId}: ${remStr.join(' ')} remaining`);
- updateCount++;
- }
- }, updateInterval);
- this.state.activeTimers.get(timerId).intervalId = intervalId;
- }
- }
- cmdStatus() {
- const status = [
- `Wall: ${this.state.wall}/${this.state.subwall}`,
- `Perms: ${['User', 'Member', 'Owner'][this.state.perms]}`,
- `Pos: (${this.config.position.x}, ${this.config.position.y})`,
- `Timers: ${this.state.activeTimers.size}`,
- `Color: ${this.config.color}`,
- `HS: ${this.config.heightSafetyEnabled ? 'ON' : 'OFF'}`,
- `Echo: ${this.config.authorityEchoEnabled ? 'ON' : 'OFF'}`,
- `Auth: ${this.config.authorizedUsers.length}`
- ];
- this.sendMessage(`📊 ${status.join(' | ')}`);
- }
- cmdPosition() {
- this.sendMessage(`📍 Current position: (${this.config.position.x}, ${this.config.position.y})`);
- }
- cmdMembers() {
- if (this.state.members.length === 0) {
- this.sendMessage("No members in this wall");
- } else {
- this.sendMessage(`Members: ${this.state.members.join(', ')}`);
- }
- }
- cmdWalls() {
- if (this.state.walllist.length === 0) {
- this.sendMessage("No subwalls available");
- } else {
- const walls = [];
- for (let i = 0; i < this.state.walllist.length; i += 2) {
- const wallName = this.state.walllist[i];
- const isPrivate = this.state.walllist[i + 1];
- walls.push(`${wallName}${isPrivate ? ' (private)' : ''}`);
- }
- this.sendMessage(`Subwalls: ${walls.join(', ')}`);
- }
- }
- cmdTeleport(args) {
- if (args.length < 2) {
- this.sendMessage(`Usage: ${this.config.prefix}to X Y`);
- return;
- }
- const x = parseInt(args[0]);
- const y = parseInt(args[1]);
- if (isNaN(x) || isNaN(y)) {
- this.sendMessage("Invalid coordinates. Please provide integers.");
- return;
- }
- if (Math.abs(x) > 10000 || Math.abs(y) > 10000) {
- this.sendMessage("Coordinates out of range (max ±10000)");
- return;
- }
- this.teleportCursor(x, y);
- this.sendMessage(`📍 Teleported to (${x}, ${y})`);
- }
- cmdColor(args) {
- if (args.length < 1) {
- this.sendMessage(`Usage: ${this.config.prefix}colorid #hex or 0-15`);
- return;
- }
- const input = args[0].toLowerCase();
- let colorIndex;
- if (!isNaN(input)) {
- colorIndex = parseInt(input);
- if (colorIndex < 0 || colorIndex > 15) {
- this.sendMessage("Invalid colot");
- return;
- }
- } else if (input.startsWith('#')) {
- colorIndex = COLORS[input];
- if (colorIndex === undefined) {
- this.sendMessage("Invalid colot");
- return;
- }
- } else {
- this.sendMessage("Invalid colot");
- return;
- }
- this.setColor(colorIndex);
- this.sendMessage(`🎨 Color changed to ${colorIndex}`);
- }
- cmdAddAuth(args) {
- if (args.length < 1) {
- this.sendMessage(`Usage: ${this.config.prefix}addauth username`);
- return;
- }
- const username = args[0];
- if (this.config.authorizedUsers.includes(username)) {
- this.sendMessage(`${username} already has authority`);
- return;
- }
- this.config.authorizedUsers.push(username);
- this.sendMessage(`✅ Added ${username} to authority list`);
- console.log(`🔑 Authority granted to: ${username}`);
- }
- cmdRemoveAuth(args) {
- if (args.length < 1) {
- this.sendMessage(`Usage: ${this.config.prefix}removeauth username`);
- return;
- }
- const username = args[0];
- if (username === "Diamond25" || username === "KiwiTest") {
- this.sendMessage(`Cannot remove default authority from ${username}`);
- return;
- }
- const index = this.config.authorizedUsers.indexOf(username);
- if (index === -1) {
- this.sendMessage(`${username} doesn't have authority`);
- return;
- }
- this.config.authorizedUsers.splice(index, 1);
- this.sendMessage(`❌ Removed ${username} from authority list`);
- console.log(`🔑 Authority revoked from: ${username}`);
- }
- cmdDisableHeightSafety() {
- this.config.heightSafetyEnabled = !this.config.heightSafetyEnabled;
- const status = this.config.heightSafetyEnabled ? "ENABLED" : "DISABLED";
- this.sendMessage(`⚠️ Height safety is now ${status} (Max tetration height: ${this.config.heightSafetyEnabled ? '5' : '10'})`);
- console.log(`Height safety: ${status}`);
- }
- cmdToggleEcho() {
- this.config.authorityEchoEnabled = !this.config.authorityEchoEnabled;
- const status = this.config.authorityEchoEnabled ? "ENABLED" : "DISABLED";
- this.sendMessage(`📢 Authority echo is now ${status}`);
- console.log(`Authority echo: ${status}`);
- }
- cmdAuthList() {
- const authUsers = [...this.config.authorizedUsers];
- const adminUsers = Array.from(this.state.adminUsers);
- const allAuth = [...new Set([...authUsers, ...adminUsers])];
- this.sendMessage(`🔑 Authorized users (${allAuth.length}): ${allAuth.join(', ')}`);
- }
- // Core functions
- setUsername(username) {
- if (typeof api !== 'undefined' && api.nick) {
- api.nick(username);
- } else if (typeof setNick === 'function') {
- setNick(username);
- } else if (typeof changeNick === 'function') {
- changeNick(username);
- }
- console.log(`👤 Username: ${username}`);
- }
- setColor(colorIndex) {
- if (typeof api !== 'undefined' && api.color) {
- api.color(colorIndex);
- } else if (typeof setColor === 'function') {
- setColor(colorIndex);
- }
- this.config.color = colorIndex;
- console.log(`🎨 Color set to: ${colorIndex}`);
- }
- teleportCursor(x, y) {
- if (typeof api !== 'undefined' && api.cursor) {
- api.cursor(x, y);
- } else if (typeof moveCursor === 'function') {
- moveCursor(x, y);
- } else if (typeof cursor === 'object' && cursor.move) {
- cursor.move(x, y);
- }
- this.config.position.x = x;
- this.config.position.y = y;
- }
- sendMessage(message) {
- if (this.state.disablechat) {
- console.log("Chat is disabled, cannot send message");
- return;
- }
- this.state.messageQueue.push(message);
- if (!this.state.isProcessingQueue) {
- this.processMessageQueue();
- }
- }
- async processMessageQueue() {
- if (this.state.messageQueue.length === 0 || !this.running) {
- this.state.isProcessingQueue = false;
- return;
- }
- this.state.isProcessingQueue = true;
- const message = this.state.messageQueue.shift();
- // Rate limiting
- const now = Date.now();
- const timeSinceLastMessage = now - this.state.lastMessageTime;
- if (timeSinceLastMessage < this.config.messageDelay) {
- await new Promise(resolve =>
- setTimeout(resolve, this.config.messageDelay - timeSinceLastMessage)
- );
- }
- this.state.lastMessageTime = Date.now();
- // Send using w.chat.send
- try {
- if (w && w.chat && w.chat.send) {
- w.chat.send(message);
- console.log(`📤 Sent: ${message}`);
- } else {
- if (typeof sendChat === 'function') {
- sendChat(message);
- } else if (typeof api !== 'undefined' && api.chat) {
- api.chat(message);
- } else {
- console.error("No chat send method available!");
- }
- }
- } catch (error) {
- console.error("Failed to send message:", error);
- }
- // Continue processing queue
- setTimeout(() => this.processMessageQueue(), this.config.messageDelay);
- }
- }
- // Initialize the bot
- console.clear();
- console.log("Starting TextWall Bot v7.0...");
- const bot = new TextWallBot(BOT_CONFIG);
- await bot.init();
- // Make bot globally accessible
- window.diamondBot = bot;
- // Utility commands
- window.stopBot = function() {
- console.log("Stopping bot...");
- bot.cleanup();
- bot.sendMessage("Bot shutting down...");
- console.log("✅ Bot stopped");
- };
- window.restartBot = async function() {
- console.log("Restarting bot...");
- window.stopBot();
- await new Promise(resolve => setTimeout(resolve, 1000));
- const newBot = new TextWallBot(BOT_CONFIG);
- await newBot.init();
- window.diamondBot = newBot;
- console.log("✅ Bot restarted");
- };
- window.botStatus = function() {
- console.table({
- 'Username': bot.config.username,
- 'Prefix': bot.config.prefix,
- 'Wall': `${bot.state.wall}/${bot.state.subwall}`,
- 'Position': `(${bot.config.position.x}, ${bot.config.position.y})`,
- 'Color': bot.config.color,
- 'Permissions': ['User', 'Member', 'Owner'][bot.state.perms] || 'Unknown',
- 'Active Timers': bot.state.activeTimers.size,
- 'Authorized Users': bot.config.authorizedUsers.length,
- 'Height Safety': bot.config.heightSafetyEnabled ? 'ON' : 'OFF',
- 'Authority Echo': bot.config.authorityEchoEnabled ? 'OFF (Default)' : 'ON',
- 'Queue Size': bot.state.messageQueue.length
- });
- };
- window.botHelp = function() {
- console.log("╔══════════════════════════════════════════╗");
- console.log("║ TextWall Bot v7.0 - Help ║");
- console.log("╠══════════════════════════════════════════╣");
- console.log("║ PREFIX: \\ ║");
- console.log("║ ║");
- console.log("║ MAIN COMMANDS: ║");
- console.log("║ \\help [1-4] - Show command page ║");
- console.log("║ \\phelp - Print ALL commands ║");
- console.log("║ \\say text - Make bot say something ║");
- console.log("║ ║");
- console.log("║ FIXES: ║");
- console.log("║ • Fixed recursion bug ║");
- console.log("║ • Authority echo OFF by default ║");
- console.log("║ • Use \\echoauth to toggle ║");
- console.log("║ ║");
- console.log("║ CONSOLE: ║");
- console.log("║ window.stopBot() - Stop bot ║");
- console.log("║ window.restartBot() - Restart bot ║");
- console.log("║ window.botStatus() - Show status ║");
- console.log("║ window.botHelp() - This help ║");
- console.log("╚══════════════════════════════════════════╝");
- };
- // Show help on start
- window.botHelp();
- })();
Advertisement
Add Comment
Please, Sign In to add comment