const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, MessageFlags } = require('discord.js'); const { UI } = require('./NewBotStyle'); const storage = require('./storage'); /** * dmall.js * Handles the !dmall command: messaging every server member and tracking responses. */ async function initiateDMAll(ctx) { const isInteraction = ctx.isChatInputCommand && ctx.isChatInputCommand(); const author = isInteraction ? ctx.user : ctx.author; const member = ctx.member; const guild = ctx.guild; const channel = ctx.channel; // 1. Permission check (Admin only) if (!member.permissions.has('Administrator')) { const msg = "❌ **Access Denied**: Only Administrators can use `!dmall`."; if (isInteraction) return ctx.reply({ content: msg, flags: [MessageFlags.Ephemeral] }); return ctx.reply(msg); } // 2. Fetch all members const waitMsg = await ctx.reply({ content: "🔄 **Fetching members and sending DMs...** This may take a moment.", fetchReply: true, flags: isInteraction ? [MessageFlags.Ephemeral] : [] }); try { await guild.members.fetch(); } catch (err) { console.error("[DMALL] Member fetch failed:", err); } const members = guild.members.cache.filter(m => !m.user.bot); const sessionId = Date.now().toString(); const session = { guildId: guild.id, channelId: channel.id, messageId: null, available: [], // Use array for storage compatibility unavailable: [], total: members.size }; // 3. Create the list message in the channel const statusEmbed = createStatusEmbed(session); const statusMsg = await channel.send({ embeds: [statusEmbed] }); session.messageId = statusMsg.id; // Save session to persistent storage storage.data.dmall_sessions[sessionId] = session; storage.save('active_polls'); // Using active_polls type as it triggers saveState // 4. Send DMs const dmEmbed = new EmbedBuilder() .setTitle(`🎮 Server Invitation: ${guild.name}`) .setDescription(`Hello! You've been invited to participate in a match or event in **${guild.name}**.\n\nPlease let us know if you are available to play by clicking a button below!`) .setColor(UI.colors.primary) .setThumbnail(guild.iconURL({ dynamic: true })) .setFooter({ text: "FriendlyBot Pro • DM Invitation" }) .setTimestamp(); const row = new ActionRowBuilder().addComponents( new ButtonBuilder() .setCustomId(`dmall_accept_${sessionId}`) .setLabel('Accept') .setStyle(ButtonStyle.Success) .setEmoji('✅'), new ButtonBuilder() .setCustomId(`dmall_decline_${sessionId}`) .setLabel('Decline') .setStyle(ButtonStyle.Danger) .setEmoji('❌') ); let sentCount = 0; let processedCount = 0; for (const [id, member] of members) { // Skip muted users if (storage.data.muted_users && storage.data.muted_users[member.id]) { processedCount++; continue; } try { await member.send({ embeds: [dmEmbed], components: [row] }); sentCount++; } catch (err) { // Ignore members with closed DMs } processedCount++; // Delay 4 seconds per person to avoid rate limiting await new Promise(resolve => setTimeout(resolve, 4000)); } const successMsg = `✅ **DM-All Complete**: Successfully sent invitations to **${sentCount}** members.`; if (isInteraction) { await ctx.editReply(successMsg); } else { await waitMsg.edit(successMsg); } } function createStatusEmbed(session) { const availableList = session.available && session.available.length > 0 ? session.available.map(id => `<@${id}>`).join('\n') : "*No one yet*"; const unavailableList = session.unavailable && session.unavailable.length > 0 ? session.unavailable.map(id => `<@${id}>`).join('\n') : "*No one yet*"; const respondedCount = (session.available?.length || 0) + (session.unavailable?.length || 0); return new EmbedBuilder() .setTitle("📊 Player Availability List") .setDescription(`Tracking responses for the latest **!dmall** invitation.`) .addFields( { name: `✅ Available (${session.available?.length || 0})`, value: availableList, inline: true }, { name: `❌ Unavailable (${session.unavailable?.length || 0})`, value: unavailableList, inline: true } ) .setColor(UI.colors.primary) .setFooter({ text: `Progress: ${respondedCount}/${session.total} members responded` }) .setTimestamp(); } async function handleResponse(interaction) { if (!interaction.isButton() || !interaction.customId.startsWith('dmall_')) return; const parts = interaction.customId.split('_'); const action = parts[1]; // accept or decline const sessionId = parts[2]; const session = storage.data.dmall_sessions[sessionId]; if (!session) { return interaction.reply({ content: "❌ This session has expired or the bot has restarted.", flags: [MessageFlags.Ephemeral] }); } const userId = interaction.user.id; // Ensure arrays exist if (!session.available) session.available = []; if (!session.unavailable) session.unavailable = []; // Remove from both lists first to handle changing response session.available = session.available.filter(id => id !== userId); session.unavailable = session.unavailable.filter(id => id !== userId); if (action === 'accept') { session.available.push(userId); } else { session.unavailable.push(userId); } // Save changes storage.save('active_polls'); // Update the DM message await interaction.update({ content: `✅ **Response Recorded**: You are marked as **${action === 'accept' ? 'Available' : 'Unavailable'}**. Thank you!`, components: [], embeds: [] }); // Update the channel message try { const client = interaction.client; const channel = await client.channels.fetch(session.channelId); if (channel) { const msg = await channel.messages.fetch(session.messageId); if (msg) { await msg.edit({ embeds: [createStatusEmbed(session)] }); } } } catch (err) { console.error("[DMALL] Failed to update status message:", err.message); } } module.exports = { initiateDMAll, handleResponse };