This commit is contained in:
NoLogicAlan committed 2026-05-16 22:03:22 +03:00
1 parent 28fc86103c
commit e966b6ce20
5 files changed
+257 -20

No files matched your search

+25 -1
View File
@@ -2,7 +2,7 @@ import { pathToFileURL } from "node:url";
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
import { Utils } from "./Utils.mjs"; import { Utils } from "./Utils.mjs";
import { EventEmitter } from "node:events"; import { EventEmitter } from "node:events";
import { Message, MessageHandler, PageBuilder } from "./MessageHandler.mjs"; import { Message, MessageHandler, PageBuilder, REQUIRED_BOT_PERMISSIONS, CRITICAL_PERMISSIONS } from "./MessageHandler.mjs";
import { Client, PermissionFlags } from "@fluxerjs/core"; import { Client, PermissionFlags } from "@fluxerjs/core";
import { SettingsManager } from "./Settings.mjs"; import { SettingsManager } from "./Settings.mjs";
import path from "node:path"; import path from "node:path";
@@ -510,6 +510,30 @@ export class CommandHandler extends EventEmitter {
processCommand(cmd, args, msg, previous = false, external = false) { processCommand(cmd, args, msg, previous = false, external = false) {
// Guard first — cmd could be undefined if called from an edge case // Guard first — cmd could be undefined if called from an edge case
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy."); if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
// Check if the bot itself has the critical permissions it needs in this channel.
// This runs BEFORE user-requirement checks so the user gets a clear error
// about what the bot is missing, rather than a generic 403 crash later.
if (!external) {
const channel = msg.channel?.channel ?? msg.channel;
if (channel?.guild) {
const botPermResult = this.messages.checkAllBotPermissions(channel);
if (botPermResult.criticalMissing.length > 0) {
const permEmbed = this.messages.buildPermissionEmbed(botPermResult.missing, channel.guildId);
try {
msg.message?.reply?.({ embeds: [permEmbed] }, { ping: false });
} catch (_) {
// Last resort: plain text
try {
const names = botPermResult.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
msg.message?.reply?.("I'm missing critical permissions: **" + names.join("**, **") + "**. Ask an admin to fix this.", { ping: false });
} catch (__) { /* completely blocked */ }
}
return;
}
}
}
if (cmd.requirements.length > 0 && !external) { if (cmd.requirements.length > 0 && !external) {
if (!this.assertRequirements(cmd, msg)) return; if (!this.assertRequirements(cmd, msg)) return;
} }
+85
View File
@@ -4,6 +4,7 @@ import { logger } from "./constants/Logger.mjs";
import { ServerSettings } from "./Settings.mjs"; import { ServerSettings } from "./Settings.mjs";
import { get247ChannelMode, remove247ChannelMode } from "./constants/Helpers247.mjs"; import { get247ChannelMode, remove247ChannelMode } from "./constants/Helpers247.mjs";
import { VoiceStateCache } from "./constants/VoiceStateCache.mjs"; import { VoiceStateCache } from "./constants/VoiceStateCache.mjs";
import { REQUIRED_BOT_PERMISSIONS, CRITICAL_PERMISSIONS } from "./MessageHandler.mjs";
import mysql from "mysql2"; import mysql from "mysql2";
/** /**
@@ -101,6 +102,84 @@ export class GatewayHandler {
return { key: null, value: null }; return { key: null, value: null };
} }
// ── Guild permission check on join ────────────────────────────────────────
/**
* Check if the bot has all required permissions in a newly joined guild.
* If critical permissions are missing, log a warning and attempt to send
* a notification to the guild's system channel (or first text channel).
*
* @param {import('@fluxerjs/core').Guild} guild
* @param {string} guildId
*/
async _checkGuildPermissions(guild, guildId) {
const { remix } = this;
// Ensure the bot's member is cached so we can check permissions
try {
if (guild.members && !guild.members.me) {
await guild.members.fetchMe();
}
} catch (_) { /* fetch failed — we'll still try */ }
// Find a text channel to check permissions in (prefer system channel)
const channels = guild.channels;
if (!channels) return;
let targetChannel = null;
// Try system channel first
if (guild.systemChannelId) {
targetChannel = channels.get?.(guild.systemChannelId)
?? channels.cache?.get?.(guild.systemChannelId)
?? null;
}
// Fall back to first text channel the bot can see
if (!targetChannel) {
for (const ch of (channels.values?.() ?? [])) {
if (ch.isTextBased?.() || ch.type === 0 || ch.type === "GUILD_TEXT") {
targetChannel = ch;
break;
}
}
}
if (!targetChannel) return;
const result = remix.messages.checkAllBotPermissions(targetChannel);
if (result.missing.length === 0) return; // All good!
// Log the missing permissions
const missingNames = result.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
if (result.criticalMissing.length > 0) {
logger.warn(
`[GuildCreate] Server ${guildId} is missing CRITICAL bot permissions: ${result.criticalMissing.join(", ")}\n` +
` All missing: ${missingNames.join(", ")}`
);
} else {
logger.info(
`[GuildCreate] Server ${guildId} is missing optional permissions: ${result.optionalMissing.join(", ")}`
);
}
// Try to send a permission warning embed to the channel
try {
const permEmbed = remix.messages.buildPermissionEmbed(result.missing, guildId);
await targetChannel.send({ embeds: [permEmbed] });
} catch (e) {
// Can't send embed (missing SendMessages/EmbedLinks) — try plain text
logger.warn(`[GuildCreate] Cannot send permission warning to server ${guildId}: ${e.message}`);
try {
await targetChannel.send(
"⚠️ I'm missing permissions I need to work properly! " +
"Missing: **" + missingNames.join("**, **") + "**. " +
"Please ask a server administrator to grant these permissions in Server Settings → Roles."
);
} catch (_) {
// Completely blocked — can't notify the server at all. The log message above is the only recourse.
logger.warn(`[GuildCreate] Cannot send ANY notification to server ${guildId} — bot is missing SendMessages permission.`);
}
}
}
// ── Voice-state seeding from guild cache ───────────────────────────────────── // ── Voice-state seeding from guild cache ─────────────────────────────────────
/** /**
@@ -678,6 +757,12 @@ export class GatewayHandler {
} }
} }
// ── Bot permission check ────────────────────────────────────────────
// After the bot joins a server, check if it has the required permissions
// in the first available text channel. If critical permissions are missing,
// log a warning and try to notify the server via system channel.
this._checkGuildPermissions(guild, guildId);
}); });
// ── GUILD_DELETE ──────────────────────────────────────────────────────── // ── GUILD_DELETE ────────────────────────────────────────────────────────
+130 -15
View File
@@ -1,7 +1,32 @@
import { Client, Events, EmbedBuilder } from "@fluxerjs/core"; import { Client, Events, EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
import { Utils } from "./Utils.mjs"; import { Utils } from "./Utils.mjs";
/**
* All permissions the bot needs to function correctly, mapped to
* human-readable names and explanations.
* Ordered by importance — text perms first, then voice perms.
*
* @type {ReadonlyMap<string, { name: string, desc: string }>}
*/
export const REQUIRED_BOT_PERMISSIONS = Object.freeze(new Map([
["ViewChannel", { name: "View Channels", desc: "See channels and read their content" }],
["SendMessages", { name: "Send Messages", desc: "Respond to commands and send messages" }],
["EmbedLinks", { name: "Embed Links", desc: "Send rich embed messages (bot responses, now playing, etc.)" }],
["AddReactions", { name: "Add Reactions", desc: "Add pagination reactions (help pages, queue, etc.)" }],
["ReadMessageHistory", { name: "Read Message History", desc: "Read previous messages for context" }],
["ManageMessages", { name: "Manage Messages", desc: "Pin messages, clean up bot responses" }],
["AttachFiles", { name: "Attach Files", desc: "Send files and thumbnails" }],
["Connect", { name: "Connect (Join Voice)", desc: "Join voice channels to play music" }],
["Speak", { name: "Speak", desc: "Stream audio in voice channels" }],
]));
/** Permission flag keys that are absolutely critical — bot cannot work without these. */
export const CRITICAL_PERMISSIONS = ["ViewChannel", "SendMessages", "EmbedLinks", "Connect", "Speak"];
/** Permission flag keys that are nice-to-have but bot can partially work without. */
export const OPTIONAL_PERMISSIONS = ["AddReactions", "ReadMessageHistory", "ManageMessages", "AttachFiles"];
/** Parse a color value from config — accepts hex string "0xe9196c", "#e9196c", or number */ /** Parse a color value from config — accepts hex string "0xe9196c", "#e9196c", or number */
export function parseColor(value, fallback = 0xe9196c) { export function parseColor(value, fallback = 0xe9196c) {
if (!value) return fallback; if (!value) return fallback;
@@ -88,20 +113,94 @@ export class MessageHandler {
/** /**
* Checks if the bot has the specified permissions in a specific channel. * Checks if the bot has the specified permissions in a specific channel.
* *
* @param {string[]} permissions An array of permissions to check for. * @param {string[]} permissions An array of permission flag keys to check for.
* @param {BaseChannel} channel The channel to check the permissions in. * @param {BaseChannel} channel The channel to check the permissions in.
* @returns {string[]} Missing permissions. * @returns {string[]} Missing permission flag keys.
*/ */
checkPermissions(permissions, channel) { checkPermissions(permissions, channel) {
if (!channel?.guild) return []; // DMs — no guild perms if (!channel?.guild) return []; // DMs — no guild perms
// guild.members.me and channel.permissionsFor()
// @fluxerjs/core may expose them or may not — guard with optional chaining so
// a missing implementation fails open (assume OK) rather than throwing.
const me = channel.guild.members?.me ?? null; const me = channel.guild.members?.me ?? null;
if (!me) return []; // can't verify — assume OK if (!me) {
logger.warn("[MessageHandler] Cannot check permissions — guild.members.me is null");
return []; // can't verify
}
const perms = channel.permissionsFor?.(me) ?? null; const perms = channel.permissionsFor?.(me) ?? null;
if (!perms) return []; // API unavailable — assume OK if (!perms) {
return permissions.filter(p => !perms.has(p)); logger.warn("[MessageHandler] Cannot check permissions — channel.permissionsFor() unavailable");
return []; // can't verify
}
// Convert string names (e.g. "SendMessages") to numeric PermissionFlags values,
// same as CommandHandler.assertRequirements does.
return permissions.filter(p => !perms.has(PermissionFlags[p] ?? p));
}
/**
* Check ALL required bot permissions in a channel.
* Returns an object with critical vs optional missing permissions
* so the caller can decide how severe the problem is.
*
* @param {BaseChannel} channel The channel to check.
* @returns {{ missing: string[], criticalMissing: string[], optionalMissing: string[] }}
*/
checkAllBotPermissions(channel) {
const allKeys = [...REQUIRED_BOT_PERMISSIONS.keys()];
const missing = this.checkPermissions(allKeys, channel);
return {
missing,
criticalMissing: missing.filter(p => CRITICAL_PERMISSIONS.includes(p)),
optionalMissing: missing.filter(p => OPTIONAL_PERMISSIONS.includes(p)),
};
}
/**
* Build a rich permission-error embed listing all missing permissions
* with human-readable names and explanations.
*
* @param {string[]} missingKeys Permission flag keys that are missing.
* @param {string} [guildId] Guild ID for locale translation.
* @returns {EmbedBuilder}
*/
buildPermissionEmbed(missingKeys, guildId) {
const criticalItems = [];
const optionalItems = [];
for (const key of missingKeys) {
const info = REQUIRED_BOT_PERMISSIONS.get(key);
const isCritical = CRITICAL_PERMISSIONS.includes(key);
const line = info
? `**${info.name}** — ${info.desc}`
: `**${key}**`;
if (isCritical) {
criticalItems.push("❌ " + line);
} else {
optionalItems.push("⚠️ " + line);
}
}
const embed = new EmbedBuilder().setColor(0xFF4444); // Red for errors
if (criticalItems.length > 0) {
embed.setTitle("Missing Permissions — Bot Cannot Work Properly");
embed.setDescription(
"The bot is missing **critical permissions** it needs to function. " +
"Please ask a server administrator to grant them.\n\n" +
criticalItems.join("\n")
);
} else if (optionalItems.length > 0) {
embed.setTitle("Missing Optional Permissions");
embed.setDescription(
"Some features may not work without these permissions, but the bot can still play music.\n\n" +
optionalItems.join("\n")
);
embed.setColor(0xFFA500); // Orange for warnings
}
embed.setFooter({
text: "Re-invite the bot with correct permissions using the invite link, " +
"or edit the bot's role in Server Settings → Roles."
});
return embed;
} }
/** /**
@@ -110,7 +209,12 @@ export class MessageHandler {
* @returns {Promise<boolean>} If all permissions are given. * @returns {Promise<boolean>} If all permissions are given.
*/ */
async assertPermissions(permissions, message) { async assertPermissions(permissions, message) {
const missing = this.checkPermissions(permissions, message.channel); // Ensure bot's guild member is cached before checking
const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId);
if (guild && !guild.members?.me) {
try { await guild.members.fetchMe(); } catch (_) { /* fetch failed, checkPermissions will warn */ }
}
const missing = this.checkPermissions(permissions, message.channel ?? message.channel?.channel);
if (missing.length === 0) return true; if (missing.length === 0) return true;
if (missing.includes("SendMessages")) { if (missing.includes("SendMessages")) {
@@ -125,7 +229,18 @@ export class MessageHandler {
return false; return false;
} }
this.replyEmbed(message, "I need the following permissions: `" + missing.join(",") + "`. Please contact a server administrator to address this.", { mention: true }); // Build a rich embed listing what's missing and why
const permEmbed = this.buildPermissionEmbed(missing, message.guildId);
try {
await message.reply({ embeds: [permEmbed] }, { ping: false });
} catch (e) {
// If reply fails (e.g. also missing EmbedLinks), fall back to plain text
logger.warn("[MessageHandler] Failed to send permission embed:", e.message);
try {
const names = missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
await message.reply("I need the following permissions: **" + names.join("**, **") + "**. Please ask a server admin to grant them.", { ping: false });
} catch (_) { /* completely blocked */ }
}
return false; return false;
} }
@@ -272,7 +387,7 @@ export class MessageHandler {
* @returns {Promise<Message>} * @returns {Promise<Message>}
*/ */
async reply(replyingTo, message, mention = false) { async reply(replyingTo, message, mention = false) {
if (!(await this.assertPermissions(["SendMessages"], replyingTo))) return null; if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
let opts; let opts;
if (typeof message === "string") { if (typeof message === "string") {
// Auto-wrap plain text in an embed (matches old replyEmbed behavior) // Auto-wrap plain text in an embed (matches old replyEmbed behavior)
@@ -290,7 +405,7 @@ export class MessageHandler {
* @returns {Promise<Message>} * @returns {Promise<Message>}
*/ */
async replyEmbed(replyingTo, message, options = {}) { async replyEmbed(replyingTo, message, options = {}) {
if (!(await this.assertPermissions(["SendMessages"], replyingTo))) return null; if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
// Raw embed payload — pass straight through without re-wrapping // Raw embed payload — pass straight through without re-wrapping
if (typeof message === "object" && Array.isArray(message.embeds)) { if (typeof message === "object" && Array.isArray(message.embeds)) {
@@ -317,8 +432,8 @@ export class MessageHandler {
* @returns {Promise<Message>} * @returns {Promise<Message>}
*/ */
async sendMessage(channel, message) { async sendMessage(channel, message) {
if (this.checkPermissions(["SendMessages"], channel).length !== 0) { if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) {
logger.warn("[MessageHandler] Missing SendMessages permission in channel", channel.id); logger.warn("[MessageHandler] Missing SendMessages/EmbedLinks permission in channel", channel.id);
return null; return null;
} }
let opts; let opts;
+14 -2
View File
@@ -956,7 +956,13 @@ export class PlayerManager {
desc = this.locale?.translate(guildId, "responses.join.autoLeaveInactive247", { channel: `<#${activeChannelId}>`, prefix }) desc = this.locale?.translate(guildId, "responses.join.autoLeaveInactive247", { channel: `<#${activeChannelId}>`, prefix })
?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``; ?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``;
} }
if (typeof ch?.send === "function") ch.send(mkEmbed(desc)); if (typeof ch?.send === "function") {
ch.send(mkEmbed(desc)).catch(err => {
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
logger.warn(`[PlayerManager] Cannot send autoleave message in channel ${ch.id} — missing permissions`);
}
});
}
}); });
player.on("leave", () => {}); player.on("leave", () => {});
@@ -968,7 +974,13 @@ export class PlayerManager {
const disabled = raw === false || raw === 0 || const disabled = raw === false || raw === 0 ||
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim()); ["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
if (disabled) return; if (disabled) return;
if (typeof ch?.send === "function") ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)); if (typeof ch?.send === "function") {
ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)).catch(err => {
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
logger.warn(`[PlayerManager] Cannot send player message in channel ${ch.id} — missing permissions`);
}
});
}
}); });
// Mark as "pending join" so concurrent getPlayer() / checkVoiceChannels() // Mark as "pending join" so concurrent getPlayer() / checkVoiceChannels()
+3 -2
View File
@@ -1,4 +1,5 @@
import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs"; import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs";
import { PermissionFlags } from "@fluxerjs/core";
import Player from "../Player.mjs"; import Player from "../Player.mjs";
import { Utils } from "../Utils.mjs"; import { Utils } from "../Utils.mjs";
import { DatabaseManager } from "./DatabaseManager.mjs"; import { DatabaseManager } from "./DatabaseManager.mjs";
@@ -59,12 +60,12 @@ export class Dashboard {
} }
server.channels = server.channels.filter(c => { server.channels = server.channels.filter(c => {
const ch = channels.find(cl => c.id === cl.id); const ch = channels.find(cl => c.id === cl.id);
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true; return ch ? ch.permissionsFor?.(member)?.has?.(PermissionFlags.ViewChannel) ?? true : true;
}); });
server.voiceChannels = server.voiceChannels.filter(c => { server.voiceChannels = server.voiceChannels.filter(c => {
if (c.type !== 2) return false; if (c.type !== 2) return false;
const ch = channels.find(cl => c.id === cl.id); const ch = channels.find(cl => c.id === cl.id);
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true; return ch ? ch.permissionsFor?.(member)?.has?.(PermissionFlags.ViewChannel) ?? true : true;
}); });
return server; return server;
} catch (e) { } catch (e) {