There's a joke on the server where when we use the command +h kidnap, and then we change the nickname to User (Kidnapper's Property), how would I go about automatically changing the nickname via the command?
var rand = [
'https://tenor.com/view/anime-kidnap-shh-reading-walking-gif-16716474',
'https://tenor.com/view/kidnap-crazy-anime-animation-cartoon-gif-5137884',
'https://media.tenor.com/images/5ae68746d329f3102d72d2ecc20ec1b0/tenor.gif',
'https://i.kym-cdn.com/photos/images/newsfeed/001/010/345/e2d.gif',
'https://media1.tenor.com/images/0cb215fd5530a8e3c127095c987e455f/tenor.gif?itemid=5869143',
'https://cdn.discordapp.com/attachments/576014006280519701/772153347742367784/1538820468_2e00f539e9a47173911f2af39ae5ecfe96f32ae4_hq.gif',
'https://cdn.discordapp.com/attachments/576014006280519701/772153350057623622/1512286824_1472546756_tumblr_ockwd0wF3R1qz64n4o1_540.gif'
];
return rand[Math.floor(Math.random() * rand.length)];
}
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'kidnap':
const personTagged = message.mentions.members.first();
if(!args[1]) {
message.channel.send('You are missing arguments!')
}else{
message.channel.send('`' + message.author.username + '`' + ' is kidnapping ' + personTagged.displayName + '! Quick! Run! ' + doKidnapAction())
}
break;
}
})
Again, how would I go about changing the nickname?
You could do it like this I belive: personTagged.setNickname("Kidnapper's Property")
Related
This is my first post here, sorry in advance if the formatting isn't great.
I'll try to keep it short and sweet. I've made a small bot with discord.js v13 and it's main purpose is to check if new people that join is part of another guild, if they are they get a role and if they had a nickname, they'll get that assigned. The bot is on both servers with full admin rights and the server members intent is enabled. I've tried all sorts of things.
Currently, the code looks like this:
const {other_server_ID, role_ID, text_channel_ID} = require("../config.json");
module.exports = {
name: 'guildMemberAdd',
async execute( member, bot ) {
//Log the newly joined member to console
console.log(member.user.tag + ' has joined the server!');
if(member.bot) return
const text_channel = member.guild.channels.cache.get(text_channel_ID)
const role = member.guild.roles.cache.get(role_ID)
text_channel.send(member.user.tag + ' has joined the server!')
const other_server = bot.guilds.cache.get(other_server_ID)
const other_server_member = other_server.members.cache.get(member.user.id)
console.log(other_server_member)
if (other_server_member === null) text_channel.send(member.user.tag + " was not a member of other_server :(")
else {
text_channel.send(member.user.tag + " was a member of other_server!")
if(!other_server_member.nickname){
text_channel.send(member.tag + " had no nickname on other_server.")
}
else {
await member.setNickname(other_server_member.nickname)
text_channel.send("Their old nickname, " + other_server_member.nickname + ", was returned to them! :)")
}
if(!member.guild.roles.cache.get(role_ID)){
text_channel.send("Role not found.")}
else{
await member.roles.add(role)
text_channel.send("They were given the role " + role.name)
}
}
}
}
As you can see, I am trying to get the other server (it works that far) and then try to grab the user from the other server's cache. Currently I try with get and the user.id but I have also tried:
const other_server_member = other_server.members.cache.find(mem => mem.user.id === member.user.id) || other_server.members.cache.find(mem => mem.user.tag === member.user.tag) || null
I found that code snippet during my search for a solution. So far I always got errors because other_server_member was always undefined/null. I also tried putting await infront of the find/get part.
Thanks for your help and time.
UPDATE:
It works fine with fetch(), code now looks like this:
const {other_server_ID, role_ID, text_channel_ID} = require("../config.json");
module.exports = {
name: 'guildMemberAdd',
async execute( member, bot ) {
//Log the newly joined member to console
console.log(member.user.tag + ' has joined the server!');
if(member.bot) return
const text_channel = member.guild.channels.cache.get(text_channel_ID)
const role = member.guild.roles.cache.get(role_ID)
text_channel.send(member.user.tag + ' has joined the server!')
const other_server = bot.guilds.cache.get(other_server_ID)
const other_server_member = null
try {
other_server_member = await other_server.members.fetch(member.user.id)
} catch (e) {
console.log(e)
return text_channel.send(member.user.tag + " was not a member of " + pluto.name + ".")
}
console.log(other_server_member)
if (other_server_member === null) text_channel.send(member.user.tag + " was not a member of other_server :(")
else {
text_channel.send(member.user.tag + " was a member of other_server!")
if(!other_server_member.nickname){
text_channel.send(member.tag + " had no nickname on other_server.")
}
else {
await member.setNickname(other_server_member.nickname)
text_channel.send("Their old nickname, " + other_server_member.nickname + ", was returned to them! :)")
}
if(!member.guild.roles.cache.get(role_ID)){
text_channel.send("Role not found.")}
else{
await member.roles.add(role)
text_channel.send("They were given the role " + role.name)
}
}
}
}
I want to make it so that if I do [prefix] [command] it will give the same effect as [mention bot] [command] but the way I create commands and args makes that difficult:
The prefix is stored as var prefix = '!3';
And this is how I create commands:
bot.on('message', msg => {
if (!msg.content.startsWith(prefix) || msg.author.bot)
return;
//the first message after '!13 '
//!
let args = msg.content.toLowerCase().substring(prefix.length).split(" ");
//^
//any capitalisation is allowed (ping,Ping,pIng etc.)
switch(args[1]) {
case 'ping': //if user inputs '!3 ping'
msg.channel.send('Pong!') //send a message to the channel 'Pong!'
}//switch (command) ends here
};//event listener ends here
You can have a list of predefined prefixes and loop over that to determine if the msg has a prefix from that list.
let prefixList = ['!31 ', '!asdf ', `<#${bot.user.id}> `, `<#!${bot.user.id}> `]
function hasPrefix(str) {
for(let pre of prefixList)
if(str.startsWith(pre))
return true;
return false;
}
<#${bot.user.id}> , <#!${bot.user.id}> will set up bot mention as a prefix.
Here's the shorter version of secretlyrice's answer:
const startsWithPrefix = (command) =>
['!prefix1 ', '!prefix2', <#botId>, <#!botId>].some(p => command.startsWith(p))
Nice code, but change it 1 to 0
switch(args[0]) {
case 'ping': //if user inputs '!3 ping'
msg.channel.send('Pong!') //send a message to the channel 'Pong!'
}
I assume you are running on an older version of Discord.js cause if you are using v13 message is depricated and should be messageCreate but this is what I used when I wasn't using slash commands.
const escapeRegex = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const prefix = '!'
bot.on('message', async msg => {
const prefixRegex = new RegExp(`^(<#!?${bot.user.id}>|${escapeRegex(prefix)})\\s*`)
if (!prefixRegex.test(message.content)) return
// checks for bot mention or prefix
const [, matchedPrefix] = message.content.match(prefixRegex)
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/)
// removes prefix or bot mention
const command = args.shift().toLowerCase()
// gets command from next arg
if (command === 'ping') {
msg.channel.send('Pong!')
}
})
I am trying to create a discord community bot for our FiveM server that handles the discord roles.
I want the bot to restrict that ROLECHANNEL, so only the role commands can be posted. Other trash i want deleted so the channel stays clean.
The command is working and the role is assigned, but the bot also fires message.reply('Wrong role, type ' + prefix +'roles'); Why?
client.on('message', message => {
if (message.channel.id === ROLECHANNEL) {
if (message.author.bot) return;
if (!message.content.includes("fivem", "ark", "arma3", "roles", "stream",)) {
message.delete([1]);
message.reply('Wrong role, type ' + prefix +'roles');
}
if(message.content.startsWith(prefix + "fivem")){
message.delete([1]);
let fivemrole = message.member.guild.roles.find("name", "fivem");
message.member.addRole(fivemrole);
message.channel.send('Gives ' + message.author + ' fivem role...');
}
if(message.content.startsWith(prefix + "arma3")){
message.delete([1])
let armarole = message.member.guild.roles.find("name", "Arma3");
message.member.addRole(armarole);
message.channel.send('Gives ' + message.author + ' Arma3 role...');
}
if(message.content.startsWith(prefix + "ark")){
message.delete([1]);
let arkrole = message.member.guild.roles.find("name", "Ark");
message.member.addRole(arkrole);
message.channel.send('Gives ' + message.author + ' Ark role...');
}
if(message.content.startsWith(prefix + "stream")){
message.delete([1]);
let streamerrole = message.member.guild.roles.find("name", "Streamer");
message.member.addRole(streamerrole);
message.channel.send('Gives ' + message.author + ' Streamer role...');
}
if (message.content.startsWith(prefix + "roles")) {
message.delete([1]);
message.channel.send('Help: ' + message.author + ' roles are. ' + roles);
}
};
your problem in this part !message.content.includes("fivem", "ark", "arma3", "roles", "stream",)
because message includes listen only fist argument "fivem", you need add or block to your code
V2
As fist variant:
if(!message.content.includes("fivem") && !message.content.includes("ark") && !message.content.includes("arma3"))
or you can set allowed varible array and check it
let allowedCommands = ["fivem", "ark", "arma3", "roles", "stream"]
if (!allowedCommands.find(command => message.content.indexOf(command) !== -1)) {
message.delete([1]);
message.reply('Wrong role, type ' + prefix +'roles');
}
For my Discord.js bot, I am attempting to create an audit log that sends messages to a specific log channel within every server it is in for user changes. I have a working 'message deleted' audit log function, but when I attempt to carry it over to role adding and deletion, usernames, nicknames, and avatar changes, the bot fails to log this and crashes. How do I fix this issue within my code?
I have included both the message delete audit log message send, and the role add/remove/username change
client.on('messageDelete', function (message) {
if (message.channel.type === 'text') {
// post in the server's log channel, by finding the accuratebotlog channel (SERVER ADMINS **MUST** CREATE THIS CHANNEL ON THEIR OWN, IF THEY WANT A LOG)
var log = message.guild.channels.find('name', CHANNEL)
if (log != null) {
log.sendMessage('**Message Deleted** ' + message.author + '\'s message: ' + message.cleanContent + ' has been deleted.')
}
}
})
// sends message when important (externally editable) user statuses change (for example nickname)
// user in a guild has been updated
client.on('guildMemberUpdate', function (guild, oldMember, newMember) {
// declare changes
var Changes = {
unknown: 0,
addedRole: 1,
removedRole: 2,
username: 3,
nickname: 4,
avatar: 5
}
var change = Changes.unknown
// check if roles were removed
var removedRole = ''
oldMember.roles.every(function (value) {
if (newMember.roles.find('id', value.id) == null) {
change = Changes.removedRole
removedRole = value.name
}
})
// check if roles were added
var addedRole = ''
newMember.roles.every(function (value) {
if (oldMember.roles.find('id', value.id) == null) {
change = Changes.addedRole
addedRole = value.name
}
})
// check if username changed
if (newMember.user.username != oldMember.user.username) {
change = Changes.username
}
// check if nickname changed
if (newMember.nickname != oldMember.nickname) {
change = Changes.nickname
}
// check if avatar changed
if (newMember.user.avatarURL != oldMember.user.avatarURL) {
change = Changes.avatar
}
// post in the guild's log channel
var log = guild.channels.find('name', CHANNEL)
if (log != null) {
switch (change) {
case Changes.unknown:
log.sendMessage('**[User Update]** ' + newMember)
break
case Changes.addedRole:
log.sendMessage('**[User Role Added]** ' + newMember + ': ' + addedRole)
break
case Changes.removedRole:
log.sendMessage('**[User Role Removed]** ' + newMember + ': ' + removedRole)
break
case Changes.username:
log.sendMessage('**[User Username Changed]** ' + newMember + ': Username changed from ' +
oldMember.user.username + '#' + oldMember.user.discriminator + ' to ' +
newMember.user.username + '#' + newMember.user.discriminator)
break
case Changes.nickname:
log.sendMessage('**[User Nickname Changed]** ' + newMember + ': ' +
(oldMember.nickname != null ? 'Changed nickname from ' + oldMember.nickname +
+newMember.nickname : 'Set nickname') + ' to ' +
(newMember.nickname != null ? newMember.nickname + '.' : 'original username.'))
break
case Changes.avatar:
log.sendMessage('**[User Avatar Changed]** ' + newMember)
break
}
}
})
I expected the bot to send a message to my channel saying 'User Role Removed: memberName + their old role', and vise versa for role adding, but my bot fails to send these messages to the bot log channel I had set up.
There is no guild parameter in a GuildMemberUpdate event. Therefore, newMember is undefined because only two parameters are passed.
client.on('guildMemberUpdate', (oldMember, newMember) => {
const guild = newMember.guild;
// continue with code
});
I don't know how to do this and I have been looking for answer but am unable to find it.
if message.content.startswith('^trivia autostart'):
await client.send_message(message.channel, "Game is starting!\n" +
str(player1) + "\n" + str(player2) + "\n" + str(player3) + "\n" +
str(player4) + "\n" + str(player5) + "\n" + str(player6) )
--
I have this code and i'm trying to make it so it when that code gets run that it calls my ^trivia play command without typing it in chat.
Is this possible?
The solution to that would be defining functions for each command you need to be called globally by your bot. Take the following example:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('error' => console.log);
bot.on('message', message => {
let prefix = '!';
let sender = message.author;
let msg = message.content;
let cont = msg.split(' ');
let args = cont.slice(1);
let cmd = msg.startsWith(prefix) ? cont[0].slice(prefix.length).toUpperCase() : undefined;
// Ping function
// can be: function pingCommand () {...}
let pingCommand = () => {
message.channel.send(`Pong!\nTime: ${bot.ping} ms`);
}
// Main command
if (cmd === 'PING') {
pingCommand();
}
// Calling command in another command
if (cmd === 'TEST') {
message.channel.send('Running a ping test on the bot');
pingCommand();
}
});
bot.login(token);
Hope you understand how it would work