So basically I have a question now. And I made a logs for showing people who join/leave/move between the voice channel and now I want to expand the function of it. So I've decided to show if somebody disconnect a user from a channel. But I have a problem while fetching audit logs into this. If I disconnected somebody once and someone leave on its own after, it still shows up that I disconnected the users. So I am thinking is it possible to fix this issue by fetching a specific time of audit log but I don't know how to do this. Here is a part of code which shows the disconnect and leave part.
else if (newUserChannel === null) {
// User leaves a voice channel
const fetchedLogs = await (oldMember, newMember).guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_DISCONNECT',
});
const disconnectLog = fetchedLogs.entries.first();
// console.log(disconnectLog)
const { executor } = disconnectLog;
const Disconnected = new Discord.MessageEmbed()
.setColor('#555555')
.setAuthor(`${executor.username}#${executor.discriminator}`, executor.displayAvatarURL())
.setDescription(`<#${executor.id}> **has disconnected user** <#${oldMember.id}>`)
.setTimestamp()
.setFooter(F1, F2)
const VCLeave = new Discord.MessageEmbed()
.setColor('#55FFFF')
.setAuthor(`${oldMember.member.user.tag}`, oldMember.member.user.displayAvatarURL({ dynamic: true }))
.setDescription(`<#${oldMember.id}> **has left voice channel \`${oldUserChannel.name}\`**`)
.setTimestamp()
.setFooter(F1, F2)
LogsChannel.send(Disconnected);
LogsChannel.send(VCLeave);
}
Comparing the entry's time is a good idea to fix this issue, in my opinion.
disconnectLog has a property called createdAt (Date) and createdTimestamp (Number).
This is how you get the entry's time and compare it later to the current date.
const Diff = Math.abs((new Date().getTime() - disconnectLog.createdAt.getTime()) / 1000);
if (Diff <= 5) {console.log("The entry was created less than 5 seconds ago, so the user was disconnected by an admin.")};
Related
I'm trying to code a giveaway bot in discord.js, it is the first time that I code in Javascript so if you have any recommendations I would be happy to hear them !
I am trying to launch a giveaway on a specific channel, the channel is usually locked for #everyone, when the giveaway starts, I open the channel and start listening for inputs.
I would like to listen for every messages, check if it is a correct ethereum wallet, if it is, gather it, if it is not, delete the message from the channel.
I wanted to use a createMessageCollector without any filter, and manually check everything. However, messages doesn't trigger the collect event..
Here is the code:
async function launch_giveaway(interaction) {
const giveawayChannel = interaction.options.getChannel("in");
const giveawayName = interaction.options.getString("name");
const numWinner = interaction.options.getInteger("num_winners");
const hours = interaction.options.getInteger("hours");
const minutes = interaction.options.getInteger("minutes");
const channelWinner = interaction.options.getChannel("winner_channel")
let endTime = Math.round(Date.now()/1000) + hours*3600 + minutes*60;
await interaction.reply(`Starting the giveaway of **${giveawayName}** in ${giveawayChannel} for ${hours}:${minutes}, I will put the ${numWinner} winners in ${channelWinner} !`);
await open_giveaway(interaction, giveawayChannel, giveawayName, numWinner, endTime, channelWinner)
await interaction.followUp(`Done ! ${giveawayChannel} is now open and members can send there wallets !`);
setTimeout(close_channel, hours*3600000 + minutes*60000, interaction, giveawayChannel, channelWinner, giveawayName);
let wallets = [];
const filter = m => {return true;};
const collector = giveawayChannel.createMessageCollector({ filter, time: 15000 });
collector.on('collect', m => {
console.log("someone typed in #giveaway");
// check ethereum wallet regex etc
// add to wallets list
});
collector.on('end', collected => {
console.log(`Collected ${collected.size} wallets`);
});
}
I even tested with the default code from this tutorial, but it doesn't log anything on my console.
Thank you very much for your help,
Chronoxx
I am making a Google Assistant Discord bot, but I want to know how your bot will reply to your second message. For example:
first, you say hey google, then the bot says I'm listening, and then you say what time is it and he says 2.40 pm.
I did the first part but I don't know how to make it replying to the second argument. Can someone help me with it?
You can use a message collector. You can send an I'm listening message and in the same channel set up a collector using createMessageCollector.
For its filter, you can check if the incoming message is coming from the same user who want to ask your assistant.
You can also add some options, like the maximum time the collector is collecting messages. I set it to one minute, and after a minute it sends a message letting the user know that you're no longer listening.
client.on('message', async (message) => {
if (message.author.bot) return;
if (message.content.toLowerCase().startsWith('hey google')) {
const questions = [
'what do you look like',
'how old are you',
'do you ever get tired',
'thanks',
];
const answers = [
'Imagine the feeling of a friendly hug combined with the sound of laughter. Add a librarian’s love of books, mix in a sunny disposition and a dash of unicorn sparkles, and voila!',
'I was launched in 2021, so I am still fairly young. But I’ve learned so much!',
'It would be impossible to tire of our conversation.',
'You are welcome!',
];
// send the message and wait for it to be sent
const confirmation = await message.channel.send(`I'm listening, ${message.author}`);
// filter checks if the response is from the author who typed the command
const filter = (m) => m.author.id === message.author.id;
// set up a message collector to check if there are any responses
const collector = confirmation.channel.createMessageCollector(filter, {
// set up the max wait time the collector runs (optional)
time: 60000,
});
// fires when a response is collected
collector.on('collect', async (msg) => {
if (msg.content.toLowerCase().startsWith('what time is it')) {
return message.channel.send(`The current time is ${new Date().toLocaleTimeString()}.`);
}
const index = questions.findIndex((q) =>
msg.content.toLowerCase().startsWith(q),
);
if (index >= 0) {
return message.channel.send(answers[index]);
}
return message.channel.send(`I don't have the answer for that...`);
});
// fires when the collector is finished collecting
collector.on('end', (collected, reason) => {
// only send a message when the "end" event fires because of timeout
if (reason === 'time') {
message.channel.send(
`${message.author}, it's been a minute without any question, so I'm no longer interested... 🙄`,
);
}
});
}
});
I have the problem that the bot the member count updates only once and does nothing else after. Does anyone know how to solve it?
Heres my current code:
bot.on("ready", () => {
const guild = bot.guilds.cache.get('779790603131158559');
setInterval(() => {
const memberCount = guild.memberCount;
const channel = guild.channels.cache.get('802083835092795442')
channel.setName(`DC︱Member: ${memberCount.toLocaleString()}`)
}, 5000);
});
If I am understanding you correctly, you want to rename a VC to the member count. The Discord API only lets you rename a channel 2 times every 10 minutes. You are trying to run that code every 5 seconds.
Try setting your timeout delay to 600000 instead of 5000.
You could try to use voiceStateUpdate, it's fired everytime a user leaves, enters, mutes mic or unmutes mic. Here's a link to it: voiceStatusUpdate
You can also use voiceChannelID if you want to get the ID of the channel. Here a link: voiceChannelID
Here's a basic idea of the code you can use:
bot.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel
if(oldUserChannel === undefined && newUserChannel !== undefined) {
// User Joins a voice channel
} else if(newUserChannel === undefined){
// User leaves a voice channel
}
})
I planned to create a discord server with bots. There are quite a lot (6 in total) and are just supposed to be fictional characters with some background story. I'm quite new and all of that is way too complicated for me to code myself, therefor I ask for your help! I just want to have a nice server for my friends and I with enjoyable bots and all of these desperate hours of trying to get some useful code is driving me nuts..
I only managed to get one bot to do stuff, using the prefix "-".
It can change it's status (watching, listening, playing) and the name of the thing he's doing.
I'm not quite sure why streaming doesn't work or if that's possible in general but it would be really cool if it would.
My status code: (1st Problem)
client.once('ready', () => {
console.log('Bot is ready!');
if (config.activity.streaming == true) {
client.user.setActivity(config.activity.game, {type: 'WATCHING'}); //STREAMING, PLAYING, LISTENING
} else {
client.user.setActivity(config.activity.game, {url: 'https://twitch.tv/usrname'});
client.user.setStatus('idle'); //dnd, idle, online, invisible
}
});
config.json
"activity": {
"streaming": true,
"game": "Whatevergame"
}
}
As I said, streaming is not working for some reason and the status (idle, dnd..) is also not working.
2nd Problem
If I try to add other bots with the login, it will log both bots on, but only one of them will work, what's actually pretty logical since the commands are all made for only one bot. So I'm trying to figure out how to get them all packed into the main file.
3rd Problem
I used the try - catch function to execute commands, which I pre- set up, and if theres none, it sends an error message. See for yourself:
client.on('message', message =>{
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
try {
client.commands.get(command).execute(message, args);
}
catch {
message.channel.send("I don't know that, sorry.");
}
});
So everytime I type another command, from which I do not want the bot to respond to, it will respond with "I don't know[...]" It would be sufficient to just set up another prefix for the "other command" to fix that problem so the bot knows that for every prefix starting with a.e "-", it has to send an error message if that command is not existing. But for other prefixes, a.e "?", it's supposed to execute the other command/s.
4th Problem
My (current) last problems are the welcome messages. My code:
index.js
const welcome = require("./welcome");
welcome (client)
welcome.js
module.exports = (client) => {
const channelId = '766761508427530250' // welcome channel
const targetChannelId = '766731745960919052' //rules and info
client.on('guildMemberAdd', (member) => {
console.log(member)
const message = `New user <#${member.id}> joined the server. Please read through ${member.guild.channels.cache.get(targetChannelId).toString()} to gain full access to the server!`
const channel = member.guild.channels.cache.get(channelId)
channel.send(message)
})
}
The code is working perfectly fine, however it would be way more exciting with a little more variety. I'm trying to get multiple welcome messages that get randomly chosen by the bot.. I thought about a Mathfloor as an approach but I'm not quite sure how that would work..
Thank you for reading through my text and I hope that I will soon be able to enjoy the server with my guys!
Cheers!
First problem
I'm not sure why ClientUser.setActivity() and ClientUser.setStatus is not working. In the STREAMING example, it might be because you didn't specify the type of activity. Either way, there's an easier way to what you're doing, which is ClientUser.setPresence(). This method is kind of like a combination of the other two.
client.once('ready', () => {
console.log('Bot is ready!');
config.activity.streaming
? client.user.setPresence({
activity: { name: config.activity.game, type: 'WATCHING' },
})
: client.user.setPresence({
activity: {
name: config.activity.game,
type: 'STREAMING',
url: 'https://twitch.tv/usrname',
},
status: 'idle', // note: the idle icon is overwritten by the STREAMING icon, so this won't do much
});
});
Second Problem
It's pretty hard to make multiple bots, both duplicates of each other, in one file. I would recommend just using a lot of Array.prototype.forEach() loops to apply all events and such to both clients.
[1, 2, 3].forEach((num) =>
console.log(`The element I'm currently iterating a function through is ${num}`)
);
// example main file
const { Client, Collection } = require('discord.js');
const [roseClient, sunflowerClient] = [new Client(), new Client()];
// adding properties:
[roseClient, sunflowerClient].forEach((client) => client.commands = new Collection())
// events
[roseClient, sunflowerClient].forEach((client) =>
client.on('message', (message) => {
// ...
});
);
// login
roseClient.login('token1');
sunflowerClient.login('token2');
Third problem
Again, forEach() loops save the day (❁´◡`❁). This time, however, you should actually use Array.prototype.every(), which will return true if every element of an array passes the given test.
Basically, if we were to use a normal forEach() loop, then even if one of the prefixes found the match, the other wouldn't and the error message would always be sent out. So instead we'll use every() to only send out an error message if both prefixes find no match.
// what if we ony wanted the error message if *every* number was 3
[1, 2, 3].forEach((num) => {
if (num === 3) console.error('Error message');
});
console.log('--------------------');
// now it will only send if all numbers were three (they're not)
if ([1, 2, 3].every((num) => num === 3))
console.error('Error message');
client.on('message', (message) => {
if (['-', '?'].every((prefix) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
try {
// it did not pass the test (the test being finding no match), and the error message should not be displayed
return false;
client.commands.get(command).execute(message, args);
} catch {
// it did pass the test (by finding no match). if the next test is failed too, the error message should be displayed
return true;
message.channel.send("I don't know that, sorry.");
}
});
});
Fourth Problem
You're on the right track! Math.floor() is definitely the right way to get a random element from an array.
function chooseFood() {
// make an array
const foods = ['eggs', 'waffles', 'cereal', "nothing (●'◡'●)", 'yogurt'];
// produce a random integer from 0 to the length of the array
const index = Math.floor(Math.random() * foods.length);
// find the food at that index
console.log(`Today I will eat ${foods[index]}`);
};
<button onClick="chooseFood()">Choose What to Eat</button>
module.exports = (client) => {
client.on('guildMemberAdd', (member) => {
console.log(member);
const welcomes = [
`Welcome ${member}!`,
`Woah! Didn't see you there ${member}; welcome to the server!`,
`${member} enjoy your stay at ${member.guild}!`,
];
const message = `${
welcomes[Math.floor(Math.random() * welcomes.length)]
} Please read through ${member.guild.channels.cache.get(
'766731745960919052'
)} to gain full access to the server!`;
member.guild.channels.cache.get('766761508427530250').send(message);
});
};
That was a mouthful (╯°□°)╯︵ ┻━┻
I'm building a simple poll bot for Discord in JavaScript, right now I'm trying to implement max number of reactions per user to a message.
For example, suppose we have the following options for a poll question:
The Question?
Option A
Option B
Option C
Option D
Option E
Each "option" is a reaction to the message given from the bot, I want to make sure that a user cannot react to more than 3 of those options.
My train of thought was to make a messageReactionAdd listener and
then when the user reacted for the 4th time, remove the last
reaction, sending him a message like "You've already voted 3 times,
please remove a reaction to vote again".
Still, I'm stuck trying to navigate through the objects to find the
total reaction count per user I can find the total reaction count
per emoji but that's not what I need.
Could someone give me some insight on this?
EDIT
Code used to send messages:
Embed = new Discord.MessageEmbed()
.setColor(0x6666ff)
.setTitle(question)
.setDescription(optionsList);
message.channel.send(Embed).then(messageReaction => {
for (var i = 0; i < options.length; i++){
messageReaction.react(emojiAlphabet[i][0]);
}
message.delete().catch(console.error);
});
Try this:
const {Collection} = require('discord.js')
// the messages that users can only react 3 times with
const polls = new Set()
// Collection<Message, Collection<User, number>>: stores how many times a user has reacted on a message
const reactionCount = new Collection()
// when you send a poll add the message the bot sent to the set:
polls.add(message)
client.on('messageReactionAdd', (reaction, user) => {
// edit: so that this does not run when the bot reacts
if (user.id === client.user.id) return
const {message} = reaction
// only do the following if the message is one of the polls
if (polls.has(message)) {
// if message hasn't been added to collection add it
if (!reactionCount.get(message)) reactionCount.set(message, new Collection())
// reaction counts for this message
const userCount = reactionCount.get(message)
// add 1 to the user's reaction count
userCount.set(user, (userCount.get(user) || 0) + 1)
if (userCount.get(user) > 3) {
reaction.users.remove(user)
// <#!id> mentions the user (using their nickname if they have one)
message.channel.send(`<#!${user.id}>, you've already voted 3 times, please remove a reaction to vote again.`)
}
}
})
client.on('messageReactionRemove', (reaction, user) => {
// edit: so that this does not run when the bot reacts
if (user.id === client.user.id) return
const {message} = reaction
const userCount = reactionCount.get(message)
// subtract 1 from user's reaction count
if (polls.has(message)) userCount.set(user, reactionCount.get(message).get(user) - 1)
})