File size: 6,714 Bytes
c8dca55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcd68ff
c8dca55
13cab43
 
 
 
 
 
c8dca55
 
 
 
 
 
dcd68ff
 
b936818
 
c8dca55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cb5b94
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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
};