Return message after mention - javascript

I want to code a game for a Discord bot and I have a little problem with this code:
(async function() {
if (command == "rps") {
message.channel.send("**Please mention a user you want to play with.**");
var member = message.mentions.members.first()
if (!member) return; {
const embed = new Discord.RichEmbed()
.setColor(0xffffff)
.setFooter('Please look in DMs')
.setDescription(args.join(' '))
.setTitle(`<#> **Do you accept** <#>**'s game?**`);
let msg = await message.channel.send(embed);
await msg.react('✅');
await msg.react('❎');
}
}
})();
I want to EmbedMessage return after mention member. Like this:
User: rps
Bot: Please mention a user
User: mention user
Bot: embed

You can use TextChannel.awaitMessages():
(async function() {
if (command == "rps") {
message.channel.send("**Please mention a user you want to play with.**");
let filter = msg => {
if (msg.author.id != message.author.id) return false; // the message has to be from the original author
if (msg.mentions.members.size == 0) { // it needs at least a mention
msg.reply("Your message has no mentions.");
return false;
}
return msg.mentions.members.first().id != msg.author.id; // the mention should not be the author itself
};
let collected = await message.channel.awaitMessages(filter, {
maxMatches: 1,
time: 60000
});
// if there are no matches (aka they didn't reply)
if (collected.size == 0) return message.edit("Command canceled.");
// otherwise get the member
let member = collected.first().mentions.members.first();
const embed = new Discord.RichEmbed()
.setColor(0xffffff)
.setFooter('Please look in DMs')
.setDescription(args.join(' '))
.setTitle(`<#> **Do you accept** <#>**'s game?**`);
let msg = await message.channel.send({
embed
});
await msg.react('✅');
await msg.react('❎');
}
})();

Related

Discord.js v12.5.3 Anyone know why this doesn't work?

EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
Code:
const discord = require('discord.js')
const newEmbed = require('embedcord')
const randomHex = require('random-hex')
module.exports = (client, message, options) => {
let links = require('./links.json')
let foundLink = false
let banReason = (options && options.banReason) || 'Sent a phishing link.'
let logs = (options && options.logs)
let member = message.mentions.members.first()
for(var i in links) {
if(message.content.toLowerCase().includes(links[i])) foundLink = true
}
if(foundLink) {
if(message.author.hasPermission('ADMINISTRATOR'))
return
message.delete()
member.ban({reason: banReason})
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
)
logs.send(embed)
}
}
Your return position might be preventing anything below if from running try changing this
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) return;
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
Or this if you want if/else
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) {
return;
} else {
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
}
EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
foundLink variable is unnecessary, you can move your code inside the loop.
Use message.member.hasPermission() instead of message.author.hasPermission().
Example code for v12.5.3(Message Event):
client.on('message', (message) => {
if (message.author.bot) return; // Ignore bot messages
const { member, channel, guild } = message; // Get the message author, channel, and guild
if (!member || !channel || !guild) return; // Ignore messages without a member, channel or guild
const { links } = require('./links.json'); // Get links from json file
for (let i = 0; i < links.length; i++) { // Check if the message contains a link in the links.json file
if (message.content.toLowerCase().includes(links[i])) { // If the message contains a link
if (member.hasPermission('ADMINISTRATOR')) return; // If the member has the administrator permission, don't ban them
const banReason = 'Sent a phishing link'; // Reason for the ban
message.delete(); // Delete the message
guild.member(member).ban({ reason: banReason }); // Ban the member
channel.send(`${member.displayName} has been banned for sending a phishing link.`) // Send a message to the channel
break;
}
}
})

Receiving massive latency on a recursive function(s) for awaiting input

I have the following code
const Discord = require("discord.js"),
{ MessageEmbed } = Discord,
ms = require("ms"),
module.exports.run = async (client, message) => {
async function awaitMessages(func) {
let output;
const m = await message.channel.awaitMessages({ filter: m => m.author.id === message.author.id, time: 60000 });
if (m.content !== "cancel") output = await func(m);
else return await message.channel.send("cancelled") && null;
if (typeof output === "function") return await output() && awaitMessages(func);
else return output;
}
function makeWaitArg(argName, description) {
const embeds = [new MessageEmbed()
.setTitle(`Giveaway ${argName}`)
.setDescription(description + " within the next 60 seconds.")
.setColor("#2F3136")
.setTimestamp()
.setFooter("Create A Giveaway! | Type cancel to cancel.", message.author.displayAvatarURL())];
return () => message.channel.send({ embeds: embeds })
};
function makeError(title, desc) {
const embeds = [new MessageEmbed().setFooter("type cancel to cancel")];
return () => message.channel.send({ embed: embeds })
}
const channel = await awaitMessages(makeWaitArg("Channel", "Please type the channel you want the giveaway to be in."), ({content}) => {
if (message.guild.channels.cache.has(content) || message.guild.channel.cache.get(content)) return content;
else return makeError("Channel", "That channel doesn't exist. Try Again.");
}),
prize = await awaitMessages(makeWaitArg("Prize.", "Please send what you would like the giveaway prize to be"), ({ content }) => {
if (content.length > 256) return makeError("Giveaway Prize Too Long.", "Please ensure the giveaway prize is less than 256 characters. Try again.");
else return content;
}),
// ill do those just be quick with logic
winnerCount = await awaitMessages(makeWaitArg("Winner Count.","Please send how many winners you would like the giveaway to have"), ({ content }) => {
if (isNaN(content)) return makeError("Invalid Winner Count.", "Please provide valid numbers as the winner count. Try again.");
else if (parseInt(content) > 15) return makeError("You can not have more than 15 winners per giveaway!")
else return content;
}),
time = await awaitMessages(makeWaitArg("Time.", "Please send how long you would like the giveaway to last"), ({ content }) => {
if (!ms(content)) return makeError("Invalid Time.", "Please provide a valid time. Try again.");
else return ms(content);
})
if (!channel || !prize || !winnerCount || !time) return;
// Start the giveaway
};
Recursion is being used to appropriately ask for multiple inputs upon failure to provide a correct input, according to my logic everything should work fine and from what I observe is that I face a massive latency between two of the steps which might be due to unnecessary load on the system while performing recursion, I need to know where that is originating and would like to rectify it.

Discord Bot js reactions

Coding a discord bot trying to get it to react to a user adding a reaction and then remove that user's reaction, I managed to get that working but if there is more than one message with the reactions on it, it will run that reaction as well. For reference I'm trying to make a dice rolling bot that reacts to a users reaction and then re-rolls a previously entered roll. I do apologise if there is already a question like this but I could not find it when looking.
Here is an example:
example of bot in action
This is the code
Get command
Client.on('message', message=> {
if(!message.content.startsWith(PREFIX) || message.author.bot) return;
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0].toLowerCase())
{
case "roll": case "r":
if(!args[1] || args[1].indexOf("d") == -1) return message.channel.send('Invalid Roll');
Client.commands.get('torg').RollDice(message, args, Client);
break;
}});
This is then the code it gets.
Run command
module.exports = {
name: 'torg',
description: 'Die roller for Trog',
async RollDice(message, args, client)
{
const channel = 'XXXXXXXXXXXXXXXXXXXXX';
const reRoll = '🔄';
if(!args[2])//untrained
{
var roll = DieRoller(args[1]);
}
else if (args[2] == "t" || args[2] == "T")
{
var roll = DieRoller(args[1], true);
}
let rollEmbed = await message.channel.send(roll);
rollEmbed.react(reRoll);
client.on('messageReactionAdd', async (reaction, user) =>
{
if(reaction.message.partial) await reaction.message.fetch();
if(reaction.partial) await reaction.fetch();
if(user.bot) return;
if(!reaction.message.guild) return;
if(reaction.message.channel.id == channel)
{
if(reaction.emoji.name === reRoll)
{
var newRoll = DieRoller(args[1]);
await message.channel.send(newRoll);
await reaction.users.remove(user);
}
else
{
return;
}
}
});
}
What should I do to make sure that the bot doesn't react twice when it sees two messages with reactions?
Thanks in advance to anyone who reads this and can help, I've only recently tried my hand and coding discord bots.

Discord JS self nickname command

hello guys iam trying to make self role and nickname change command but its not working i dont know where is the problem i earn the role but name not changing can someone tell me what is wrong on my code
client.on('message', (message,member )=> {
if (message.content.toLowerCase() === '*Test') {
if(!message.channel.guild) return;
message.member.addRole(message.guild.roles.find(role => role.name === "Test"));
let member = message.member; //message.guild.members.cache.get(user.id);
let nick = "[PRO] "
// message.guild.member(r=>r.setNickname(nick + r.user.username));
member.setNickname(nick + member.user.username);
}
});
To set Discord nickname. You can use message.member.setNickname("new member") .
as example :
if you want to create #setnick [nickname] and [nickname] is your args.
and you can use this example with role for member
client.on('message', async message => {
let messageArray = message.content.split(" ");
let args = messageArray.slice(1);
var argresult = message.content.split(` `).slice(1).join(' ');
if(message.channel.type === "dm" || message.author.bot) return;
if(message.content.toLowerCase().startsWith('#setnick')) {
if(!message.guild.me.hasPermission('MANAGE_NICKNAMES')) return message.reply('I dont have Permission to do this action.!');
try {
if(!args[0]) {
message.member.setNickname(message.author.username)
} else {
message.member.setNickname(argresult, "Member wants to change nickname")
}
} catch(error) {
return console.error('[ SET_NICKNAME ] Error')
}
}
})

I am trying to show roles in my !!userinfo command but I get errors

I have a !!userinfo command and I am trying to get it to where I can #anyone and it shows there info how I have everything else working but then I came up to this problem here is the error.
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'map' of undefined
I have looked it up no answer, but I did come up with something it said that it usually means that is unpopulated but I don't know how to get it in there.
const Discord = module.require("discord.js");
const fs = require("fs");
const userdata = JSON.parse(fs.readFileSync('commands/storage/userdata.json', 'utf8'));
module.exports.run = async (bot, message, args) => {
let member;
if (message.mentions.users > 0) {
member = message.mentions.user.size()
} else {
member = message.author
}
let user;
if (message.mentions.users > 0) {
user = message.mentions.user.size()
} else {
user = message.author
}
embed = new Discord.RichEmbed()
.setAuthor(message.member.username)
.setDescription("Users Info", true)
.setColor("#64FF00", true)
.addField("Full Username:", `${message.member.username}${message.member.discriminator}`, true)
.addField("ID:", message.member.id, true)
.addField("Created at:", message.member.createdAt, true)
.addField("Status:", `${user.presence.status}`, true)
.addField("Game:", `${user.presence.game}`, true)
.addField("Roles", member.roles.map(r => `${r}`).join('|'), true);
message.channel.send(embed);
}
module.exports.help = {
name: "userinfo"
}
I Would like it so I can #anyone and there info comes up
You can easily make the first part:
let member;
if (message.mentions.users > 0) {
member = message.mentions.user.size()
} else {
member = message.author
}
let user;
if (message.mentions.users > 0) {
user = message.mentions.user.size()
} else {
user = message.author
}
into:
const user = message.mentions.users.first() || message.author;
const member = message.mentions.members.first() || message.member;
if(!member) return message.channel.send('This command can only be run in a guild!')
Also you want to change the embed bit to:
let embed = new Discord.RichEmbed()
.setAuthor(user.tag)
.setDescription("Users Info", true)
.setColor("#64FF00", true)
.addField("Full Username:", user.tag , true)
.addField("ID:", user.id, true)
.addField("Created at:", user.createdAt, true)
.addField("Status:", user.presence.status , true)
.addField("Game:", user.presence.game ? user.presence.game : 'none' , true)
.addField("Roles", member.roles.map(r => `${r}`).join(' | '), true);
message.channel.send(embed);
I believe the problem lies with how you assign a value to the variable member. Adding to that, I think you have some redundant code since you have a variable member and a variable user which you give a value with the same code.
Below you can find your code which I've rewritten. Give it a go and let me know what the result is.
module.exports.run = async (bot, message, args) => {
let guildMember;
if (message.mentions.members.first()) {
guildMember = message.mentions.members.first();
} else {
guildMember = message.member;
}
// We need the User object aswell for different properties
const user = guildMember.user;
let embed = new Discord.RichEmbed()
.setAuthor(user.username)
.setDescription("Users Info", true)
.setColor("#64FF00", true)
.addField("Full Username:", `${user.username}${user.discriminator}`, true)
.addField("ID:", user.id, true)
.addField("Created at:", user.createdAt, true)
.addField("Status:", `${user.presence.status}`, true)
.addField("Game:", `${user.presence.game}`, true)
.addField("Roles", guildMember.roles.map(r => `${r}`).join('|'), true);
message.channel.send(embed);
}
This sets member to a number
member = message.mentions.user.size()
Since member is now a number, trying to access member.roles results in undefined. And since undefined does not have a .map method, you see that exception.

Categories