Server Boost Tracker Bot Discord [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Help me to send a message when someone Boost The Server, here some code for example.
Please help me, guys :)
bot.on('guildMemberUpdate', (oldMember, newMember) => {
if(oldMember.roles.size < newmember.roles.size) {
const fetchedLogs = await oldMember.guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_ROLE_UPDATE',
});
const roleAddLog = fetchedLogs.entries.first();
if (!roleAddLog ) return;
const { executor, target, extra } = kickLog;
console.log(`Role ${extra.name} added to ${<#target.id>} by ${<#executor.id>}`)
}
});

You can use GuildMember#premiumSince for an approach that does not rely on roles:
bot.on('guildMemberUpdate', (oldMember, newMember) => {
if (oldMember.premiumSince !== newMember.premiumSince) {
//your code here
}
});

You can check if the Nitro Booster role gets assigned to a member:
bot.on('guildMemberUpdate', async (oldMember, newMember) => {
const hadRole = oldMember.roles.find(role => role.name === 'Nitro Booster');
const hasRole = newMember.roles.find(role => role.name === 'Nitro Booster');
if (!hadRole && hasRole) {
newMember.guild.channels.get(/* channel ID */).send('Someone boosted the server');
}
// if you want to check which members are boosted, you can check how many have the `Nitro Booster` role:
const boostedUsers = newMember.guild.members.array().filter(member => member.roles.find(role => role.name === 'Nitro Booster'));
console.log(boostedUsers.length); // how many members are boosted
});

Related

discord.js channel only command [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
Kepps crashing
const Discord = require("discord.js")
module.exports = {
name: 'not-dropping',
description: 'sets the dropping status!',
if (message.channel.id === '1059798572855476245') {
execute(message, args) {
message.delete(1000);
const name = ("dropping-🔴")
message.channel.setName(name)
message.channel.send(`Successfully set the dropping status to **${name}**`)
}
}
}
I also tried to change it to Role only but it contiunes crashing.
Having an if-statement in the definition of your export won't work. Instead, call the if-statement only when execute() is run, like this:
const Discord = require("discord.js")
module.exports = {
name: 'not-dropping',
description: 'sets the dropping status!',
execute(message, args) {
if (message.channel.id === '1059798572855476245') {
message.delete(1000);
const name = ("dropping-🔴")
message.channel.setName(name)
message.channel.send(`Successfully set the dropping status to **${name}**`)
}
}
}

I'm in need of help registering for all guilds globally, can someone assist me?

I'm looking to register for all guilds globally instead of registering for just my guild ID, just so I can use slash commands in my friend's server (plus any other server it's in), yet I don't know how. I'm a bit new to discord.js.
I was wondering if someone could help me register for all guilds globally...
Extra information - I'm following reconlx's Discord.js v13 tutorials.
This is the part of my code which I need help looking at and modifying. There's a line in his command handler talking about registering for all guilds at await client.application.commands.set(arrayOfSlashCommands);, yet I'm not sure what it means...
client.on("ready", async () => {
// Register for a single guild
const guild = client.guilds.cache.get("938823675535319050")
await guild.commands.set(arrayOfSlashCommands).then((cmd) => {
const getRoles = (commandName) => {
const permissions = arrayOfSlashCommands.find(
(x) => x.name === commandName
).userPermissions;
if(!permissions) return null;
return guild.roles.cache.filter(
(x) => x.permissions.has(permissions) && !x.managed
);
};
const fullPermissions = cmd.reduce((accumulator, x) => {
const roles = getRoles(x.name);
if(!roles) return accumulator;
const permissions = roles.reduce((a, v) => {
return [
...a,
{
id: v.id,
type: 'ROLE',
permission: true,
},
];
}, []);
return [
...accumulator,
{
id: x.id,
permissions,
},
];
}, []);
guild.commands.permissions.set({ fullPermissions });
});
// Register for all the guilds the bot is in
// await client.application.commands.set(arrayOfSlashCommands);
});
Looking forward to some solutions, if you could assist, it would help a lot.
You can register global commands using the Client.application.commands.set() method, passing in an Array of ApplicationCommandDataResolvables into the method. However, please be aware a caveat of global commands is that they take up to an hour for changes to reflect across Discord.
See this:
client.application.commands.set(commands)
// ^^^ ^^^^^^^^
// Client is your Discord.Client Commands is the list of commands

How to solve "Message content must be a non-empty string" in node.js [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Here is my code,
const { Client, Intents } = require('discord.js');
const mineflayer = require("mineflayer");
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
let sending = false
let chatData = []
let prefix = ".";
var settings = {
username: "StilShem_tvink",
host: "mstnw.net",
};
const bot = mineflayer.createBot(settings);
bot.on('kicked', (reason, loggedIn) => console.log(reason, loggedIn));
bot.on('error', err => console.log(err));
client.on("ready", async =>{
console.log("Discord bot is online!")
})
bot.on("login", async =>{
console.log("Minecraft bot is online!")
})
bot.on("message", message => {
if(sending == true) {
chatData.push(`${message}`)
}
})
client.on("messageCreate", async msg => {
let args = msg.content.split(" ").slice(1)
if(msg.content.startsWith(".chat")) {
let toSend = args.join(" ");
if(!toSend) return msg.reply("No args")
bot.chat(toSend)
sending = true
msg.channel.send(`${msg.author.tag} just sent ${toSend}`)
setTimeout(() => {
sending = false
msg.channel.send(chatData.join("\n"))
chatData = []
}, 750)
}
})
This code is for minecraft mineflayer with discord. And this code give me error.
C:\Users\ArtemiiYT\node_modules\discord.js\src\util\Util.js:414
if (!allowEmpty && data.length === 0) throw new error(errorMessage);
^
RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty
string.
at Function.verifyString (C:\Users\ArtemiiYT\node_modules\discord.js\src\util\Util.js:414:49)
at MessagePayload.makeContent (C:\Users\ArtemiiYT\node_modules\discord.js\src\structures\MessagePayload.js:113:22)
at MessagePayload.resolveData (C:\Users\ArtemiiYT\node_modules\discord.js\src\structures\MessagePayload.js:128:26)
at TextChannel.send (C:\Users\ArtemiiYT\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:168:61)
at Timeout._onTimeout (C:\Users\ArtemiiYT\Desktop\Всё\AFK bot\AFKBOTDS\bot.js:46:25)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) { [Symbol(code)]: 'MESSAGE_CONTENT_TYPE' }
Node.js v17.1.0
I didn't go on my way to run the code, but I think the chatData array is empty. so when you try to .join("\n") all the elements inside it together, you just get an empty string which discord just rejects and you get an error.
so you might want to check if there is anything in the array first.
if you are here for the code just add this in the interval function:
if(chatData.length < 1) {
// maybe inform the user there is no new chat message?
return;
}

Job Inquiry Bot for Discord.js

I am trying to create a bot that a user can DM to start a "job" inquiry.
Example:
A user messages the bot with !inquiry, then the bot asks questions about the job such as if it's a personal project or for a company, then what is the company or personal projects twitter, it will then ask what type of service they are requesting by supplying options and based on that option the bot will respond with "Please explain what you have in mind for your new xxx job"
Then once the user answers all those questions the bot sends an embed with what they answered.
I was thinking of using MessageCollector but I got stuck with how to do the logic. I have the bot responding to the user so I understand how to send messages through DM to a user. just don't quite understand how to implement the rest. I need a little push.
client.on("message", async (msg) => {
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
if (msg.channel.type === "dm") {
const args = msg.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
const discordUser = msg.author.tag;
if (command !== "order") {
try {
sendFailMessage(msg, "wrongCommand");
} catch (e) {
console.warn("Failed sending Fail Message");
}
} else {
msg.channel.startTyping(1);
msg.author.send();
I've made something similar before so incase you want the full code and context: https://github.com/karizma/ravenxi/blob/master/commands/showcase/apply.js
But here's it rewritten for your context:
(note it's def not optimized since idk your context code, and you are passing variables for every call, but if you know js decently which you should if you are gonna use a libary, it shouldn't be too hard to better the code)
function sendNexQuestion(index, channel, questions, replys) {
return channel.send(questions[index])
.then(() => channel.awaitMessages(() => true, { max: 1, time: 30000, errors: ["time"] }))
.then(reply => {
const content = reply.first().content;
if (content === prefix + "cancel") throw "Self-Cancel";
if (content === prefix + "redo") {
replys.length = 0;
return sendNextQuestion(0, channel, questions, replys);
}
replys.push(content);
return index >= questions.length - 1 ? new Promise(res => res(replys)) : sendNextQuestion(index + 1, channel, questions, replys);
}).catch(err => {
if (err === "Self-Cancel") {
//user canceled
}
channel.send("Application Canceled");
});
}
client.on("message", async (msg) => {
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
if (msg.channel.type === "dm") {
const args = msg.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
const questions = ["Why do you want this?", "Question 2"];
if (command === "inquiry") {
sendNexQuestion(0, msg.channel, questions, []).then(replys => {
//array of replys
})
}
}
});

Parsing error Javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Getting a parsing error in javascript while deploying firebase functions... Its showing unexpected token which if i'm not mistaken means that there is an unexpected character somewhere... Stuck here for weeks now... Can somone help me out please
Code
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref(`/Notifications/${user_id}/${notification_id}/`).onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to ', user_id);
if (!change.after.val()) {
return console.log("A Notification has been deleted from the database", notification_id);
}
const fromUser = admin.database().ref('/Notifications/${user_id}/${notification_id}').once('value');
return fromUser.then(fromUserResult => {
const fromUserId = fromUserResult.val().from;
console.log('You have a new notification from : ', from_user_id);
const userQuery = admin.database().ref('UserData/${fromUserId}/name').once('value');
return userQuery.then(userResult => {
const userName = userResult.val();
const deviceToken = admin.database().ref(`/UserData/${user_id}/TokenID`).once('value');
return deviceToken.then(result => {
const token_id = result.val();
const payload = {
notification: {
title: '${userName}',
body: "You have recieved a new Message",
icon: "default",
click_action: "com.appmaster.akash.messageplus_TARGET_NOTIFICATION"
},
data: {
from_user_id: fromUserId,
from_user_name: userName
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
return console.log('This was the notofication Feature');
});
});
});
});
You're missing two pairs of }) at the end of the file. So:
...
return admin.messaging().sendToDevice(token_id, payload).then(response =>{
return console.log('This was the notofication Feature');
});
});
});
});
});
It is understandably impossible to see this with your current code.
The lack of indentation makes it incredibly hard to parse. That's why I passed the code through http://jsbeautifier.org/, which makes it much easier to parse.
I also recommend using a tool like https://eslint.org/demo/ to make it easier to find mistakes like this.
you'll still have few bugs in your code. on three places you're using single quote ' instead of back-tick `
...
const fromUser = admin.database().ref(`/Notifications/${user_id}/${notification_id}`).once('value');
...
const userQuery = admin.database().ref(`UserData/${fromUserId}/name`).once('value');
...
const payload = {
notification: {
title: `${userName}`,
body: "You have recieved a new Message",
icon: "default",
click_action: "com.appmaster.akash.messageplus_TARGET_NOTIFICATION"
},
data: {
from_user_id: fromUserId,
from_user_name: userName
}
};

Categories