const storage = require('./storage'); const { EmbedBuilder } = require('discord.js'); /** * broadcast_system.js * Handles global announcements and message tracking */ async function broadcast(client, content, sender) { const broadcastId = Date.now().toString(); const sentMessages = []; const timestamp = new Date().toISOString(); const embed = new EmbedBuilder() .setTitle("📢 Global Announcement") .setDescription(content) .setColor('#5865F2') .setFooter({ text: `FriendlyBot Official | ID: ${broadcastId}` }) .setTimestamp(); for (const guild of client.guilds.cache.values()) { const config = storage.data.config[guild.id] || {}; // Respect the opt-out toggle (defaulting to false based on user request) if (!!config.postEnabled) { try { // Determine target channel: either configured one or system channel const channelId = config.postChannelId; let channel = null; if (channelId) { channel = await guild.channels.fetch(channelId).catch(() => null); } if (!channel) { channel = guild.systemChannel || guild.channels.cache.find(c => c.isTextBased() && c.permissionsFor(guild.members.me).has('SendMessages')); } if (channel) { const msg = await channel.send({ embeds: [embed] }); sentMessages.push({ guildId: guild.id, guildName: guild.name, channelId: channel.id, messageId: msg.id }); } } catch (err) { console.error(`[Broadcast] Failed to send to ${guild.name}:`, err.message); } } } // Save to history storage.data.broadcasts.push({ id: broadcastId, content: content, senderTag: sender.tag, senderId: sender.id, timestamp: timestamp, messages: sentMessages }); storage.save('broadcasts'); return { id: broadcastId, count: sentMessages.length }; } async function removeBroadcast(client, broadcastIdOrText) { // Find the broadcast entry const entryIndex = storage.data.broadcasts.findIndex(b => b.id === broadcastIdOrText || b.content.includes(broadcastIdOrText)); if (entryIndex === -1) return { success: false, message: "Broadcast not found in history." }; const entry = storage.data.broadcasts[entryIndex]; let removedCount = 0; for (const msgInfo of entry.messages) { try { const guild = client.guilds.cache.get(msgInfo.guildId); if (guild) { const channel = await guild.channels.fetch(msgInfo.channelId).catch(() => null); if (channel) { const msg = await channel.messages.fetch(msgInfo.messageId).catch(() => null); if (msg) { await msg.delete(); removedCount++; } } } } catch (err) { console.error(`[Broadcast] Failed to remove from guild ${msgInfo.guildId}:`, err.message); } } // Remove from history storage.data.broadcasts.splice(entryIndex, 1); storage.save('broadcasts'); return { success: true, count: removedCount }; } function getBroadcastHistory() { return storage.data.broadcasts; } module.exports = { broadcast, removeBroadcast, getBroadcastHistory };