-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpollHandler.js
170 lines (139 loc) · 7.39 KB
/
pollHandler.js
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
const { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder } = require('discord.js');
const { insertPollResult, getPollResults, getAllTimeResults } = require('./database');
const config = require('./config.json');
let logMessages = {}; // Store the log message IDs for each poll date
async function postPoll(channelId, date) {
const channel = await client.channels.fetch(channelId);
const embed = new EmbedBuilder()
.setTitle('Were you green or red for the day following this analyst?')
.setColor('#9cfa05')
.addFields(
{ name: 'Total', value: '0', inline: false },
{ name: 'Green', value: '0 (0%)', inline: true },
{ name: 'Red', value: '0 (0%)', inline: true },
{ name: 'Did not follow/trade', value: '0 (0%)', inline: true }
);
const pollMessage = await channel.send({
embeds: [embed],
components: [
new ActionRowBuilder().addComponents(
new ButtonBuilder().setCustomId('green').setLabel('📈 Green').setStyle(ButtonStyle.Success),
new ButtonBuilder().setCustomId('red').setLabel('📉 Red').setStyle(ButtonStyle.Danger),
new ButtonBuilder().setCustomId('no_trade').setLabel('❌ Did not follow/trade').setStyle(ButtonStyle.Secondary)
)
]
});
const filter = (interaction) => ['green', 'red', 'no_trade'].includes(interaction.customId);
const collector = pollMessage.createMessageComponentCollector({ filter, time: 10 * 60 * 60 * 1000 });
const userVotes = new Set(); // Track users who have voted
collector.on('collect', async (interaction) => {
if (userVotes.has(interaction.user.id)) {
await interaction.reply({ content: 'You have already voted in this poll.', ephemeral: true }).catch(console.error);
return;
}
await interaction.deferUpdate();
await insertPollResult(channelId, date, interaction.customId);
userVotes.add(interaction.user.id);
await updatePollMessage(pollMessage, channelId, date);
await updateLogChannel(date);
});
collector.on('end', async () => {
await disablePoll(pollMessage);
});
}
async function startPolls(date) {
// Send initial log message template only once
if (!logMessages[date]) {
await sendInitialLogMessage(date);
}
for (const channelId of config.pollChannels) {
await postPoll(channelId, date);
}
}
async function sendInitialLogMessage(date) {
const logChannel = await client.channels.fetch(config.logChannelId);
const logEmbeds = [];
let currentEmbed = new EmbedBuilder().setTitle(`${date} Poll Results`).setColor('#9cfa05');
let currentDescription = '';
for (const [index, channelId] of config.pollChannels.entries()) {
currentDescription += `
Results for <#${channelId}>:
Green: \`0\` **0%** for the day. (All time: \`0\` **0%**)
Red: \`0\` **0%** for the day. (All time: \`0\` **0%**)
Did not follow/trade: \`0\` **0%** for the day. (All time: \`0\` **0%**)\n\n`;
if ((index + 1) % 10 === 0 || index === config.pollChannels.length - 1) {
currentEmbed.setDescription(currentDescription.trim());
logEmbeds.push(currentEmbed);
currentEmbed = new EmbedBuilder().setTitle(`${date} Poll Results`).setColor('#9cfa05');
currentDescription = '';
}
}
const logMessagesSent = [];
for (const logEmbed of logEmbeds) {
const sentMessage = await logChannel.send({ embeds: [logEmbed] });
logMessagesSent.push(sentMessage);
}
logMessages[date] = logMessagesSent;
}
async function updatePollMessage(pollMessage, channelId, date) {
const results = await getPollResults(channelId, date);
const totalVotes = results.reduce((acc, result) => acc + result.count, 0);
const greenVotes = results.find(result => result.answer === 'green')?.count || 0;
const redVotes = results.find(result => result.answer === 'red')?.count || 0;
const noTradeVotes = results.find(result => result.answer === 'no_trade')?.count || 0;
const greenPercentage = totalVotes > 0 ? ((greenVotes / totalVotes) * 100).toFixed(2) : 0;
const redPercentage = totalVotes > 0 ? ((redVotes / totalVotes) * 100).toFixed(2) : 0;
const noTradePercentage = totalVotes > 0 ? ((noTradeVotes / totalVotes) * 100).toFixed(2) : 0;
const embed = new EmbedBuilder()
.setTitle('Were you green or red for the day following this analyst?')
.setColor('#9cfa05')
.addFields(
{ name: 'Total', value: `${totalVotes}`, inline: false },
{ name: 'Green', value: `${greenVotes} (${greenPercentage}%)`, inline: true },
{ name: 'Red', value: `${redVotes} (${redPercentage}%)`, inline: true },
{ name: 'Did not follow/trade', value: `${noTradeVotes} (${noTradePercentage}%)`, inline: true }
);
await pollMessage.edit({ embeds: [embed] }).catch(console.error);
}
async function updateLogChannel(date) {
const logMessagesSent = logMessages[date];
const logEmbeds = [];
let currentEmbed = new EmbedBuilder().setTitle(`${date} Poll Results`).setColor('#9cfa05');
let currentDescription = '';
for (const [index, channelId] of config.pollChannels.entries()) {
const results = await getPollResults(channelId, date);
const totalVotes = results.reduce((acc, result) => acc + result.count, 0);
const greenVotes = results.find(result => result.answer === 'green')?.count || 0;
const redVotes = results.find(result => result.answer === 'red')?.count || 0;
const noTradeVotes = results.find(result => result.answer === 'no_trade')?.count || 0;
const greenPercentage = totalVotes > 0 ? ((greenVotes / totalVotes) * 100).toFixed(2) : 0;
const redPercentage = totalVotes > 0 ? ((redVotes / totalVotes) * 100).toFixed(2) : 0;
const noTradePercentage = totalVotes > 0 ? ((noTradeVotes / totalVotes) * 100).toFixed(2) : 0;
const allTimeResults = await getAllTimeResults(channelId);
const allTimeVotes = allTimeResults.reduce((acc, result) => acc + result.count, 0);
const allTimeGreen = allTimeResults.find(result => result.answer === 'green')?.count || 0;
const allTimeRed = allTimeResults.find(result => result.answer === 'red')?.count || 0;
const allTimeNoTrade = allTimeResults.find(result => result.answer === 'no_trade')?.count || 0;
const allTimeGreenPercentage = allTimeVotes > 0 ? ((allTimeGreen / allTimeVotes) * 100).toFixed(2) : 0;
const allTimeRedPercentage = allTimeVotes > 0 ? ((allTimeRed / allTimeVotes) * 100).toFixed(2) : 0;
const allTimeNoTradePercentage = allTimeVotes > 0 ? ((allTimeNoTrade / allTimeVotes) * 100).toFixed(2) : 0;
currentDescription += `
Results for <#${channelId}>:
Green: \`${greenVotes}\` **${greenPercentage}%** for the day. (All time: \`${allTimeGreen}\` **${allTimeGreenPercentage}%**)
Red: \`${redVotes}\` **${redPercentage}%** for the day. (All time: \`${allTimeRed}\` **${allTimeRedPercentage}%**)
Did not follow/trade: \`${noTradeVotes}\` **${noTradePercentage}%** for the day. (All time: \`${allTimeNoTrade}\` **${allTimeNoTradePercentage}%**)\n\n`;
if ((index + 1) % 10 === 0 || index === config.pollChannels.length - 1) {
currentEmbed.setDescription(currentDescription.trim());
logEmbeds.push(currentEmbed);
currentEmbed = new EmbedBuilder().setTitle(`${date} Poll Results`).setColor('#9cfa05');
currentDescription = '';
}
}
for (let i = 0; i < logMessagesSent.length; i++) {
await logMessagesSent[i].edit({ embeds: [logEmbeds[i]] }).catch(console.error);
}
}
async function disablePoll(pollMessage) {
await pollMessage.edit({ components: [] }).catch(console.error);
}
module.exports = { startPolls, disablePoll };