Move voice chat users using Discord bot - javascript

I am trying to program a bot that, following a command, moves a user to a room a number of times of your choice.
For configuration and hosting I am using autocode.com, both "userId" and "number" are set correctly.
However, the user is not moved away.
This is the code
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
let isAdmin = (context.params.event.member.permissions & (1<<3)) === (1<<3);
if (isAdmin) {
let userId = context.params.event.data.options[0].value;
let number = context.params.event.data.options[1].value;
let result = await lib.discord.channels['#0.1.0'].messages.create({
channel_id: `${context.params.event.channel_id}`,
content: `It's time to Jump for ` +number+ ' times'
});
for(let i = 0; i < number; i++){
await guild.member(userId).voice.setChannel("789946095341535242");
await sleep(1000)}
} else {
await lib.discord.channels['#0.1.0'].messages.create({
channel_id: `${context.params.event.channel_id}`,
content: `This command is admin only!`,
});
}
I think the problem is at
await guild.member (userId) .voice.setChannel ("789946095341535242");
but I can't solve the problem, does anyone know what the problem could be and how to fix it?

Related

How Would I Make an External Database File? - Discord.JS

I am trying to build a discord bot, that would do leveling and warns and such, but i have no idea how I would link a file to the main javascript file so i can have all the database code be "external". I want to use SQLite for my database.
This is currently what i have
client.on("ready", () => {
// Check if the table "points" exists.
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'scores';").get();
if (!table['count(*)']) {
// If the table isn't there, create it and setup the database correctly.
sql.prepare("CREATE TABLE scores (id TEXT PRIMARY KEY, user TEXT, guild TEXT, points INTEGER, level INTEGER);").run();
// Ensure that the "id" row is always unique and indexed.
sql.prepare("CREATE UNIQUE INDEX idx_scores_id ON scores (id);").run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
// And then we have two prepared statements to get and set the score data.
client.getScore = sql.prepare("SELECT * FROM scores WHERE user = ? AND guild = ?");
client.setScore = sql.prepare("INSERT OR REPLACE INTO scores (id, user, guild, points, level) VALUES (#id, #user, #guild, #points, #level);");
});
client.on("messageCreate", message => {
if (message.author.bot) return;
let score;
if (message.guild) {
score = client.getScore.get(message.author.id, message.guild.id);
if (!score) {
score = { id: `${message.guild.id}-${message.author.id}`, user: message.author.id, guild: message.guild.id, points: 0, level: 1 }
}
score.points++;
const curLevel = Math.floor(0.1 * Math.sqrt(score.points));
if (score.level < curLevel) {
score.level++;
message.reply(`You've leveled up to level **${curLevel}**! Ain't that dandy?`);
}
client.setScore.run(score);
}
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "give") {
// Limited to guild owner - adjust to your own preference!
if (!message.author.id === message.guild.ownerId) return message.reply("You're not the boss of me, you can't do that!");
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply("You must mention someone or give their ID!");
const pointsToAdd = parseInt(args[1], 10);
if (!pointsToAdd) return message.reply("You didn't tell me how many points to give...");
// Get their current points.
let userScore = client.getScore.get(user.id, message.guild.id);
// It's possible to give points to a user we haven't seen, so we need to initiate defaults here too!
if (!userScore) {
userScore = { id: `${message.guild.id}-${user.id}`, user: user.id, guild: message.guild.id, points: 0, level: 1 }
}
userScore.points += pointsToAdd;
// We also want to update their level (but we won't notify them if it changes)
let userLevel = Math.floor(0.1 * Math.sqrt(score.points));
userScore.level = userLevel;
// And we save it!
client.setScore.run(userScore);
return message.channel.send(`${user.tag} has received ${pointsToAdd} points and now stands at ${userScore.points} points.`);
}
if (command === "leaderboard") {
/*const top10 = sql.prepare("SELECT * FROM scores WHERE guild = ? ORDER BY points DESC LIMIT 10;").all(message.guild.id);*/
// Now shake it and show it! (as a nice embed, too!)
const embed = new EmbedBuilder()
.setTitle("Leader board")
.setDescription("Our top 10 points leaders!")
.setColor("#ff0000")
.addFields({ name: '\u200b', value: '\u200b' });
/*for (const data of top10) {
embed.addFields({ name: client.users.cache.get(data.user).tag, value: `${data.points} points (level ${data.level})` });
}*/
return message.channel.send({ embed: embed });
}
// Command-specific code here!
});
The Idea is that when someone messages in chat, the bot will see that message and randomize the amount of XP given to a member. I dont have a full idea on how this can be done externally, if it can.
If i understand this correctly, you want another JS file to be run inside of your current file. Node JS makes this pretty easy!
require('./filename.js')
(also, you might want to use external files to store your commands too!)

Discord.js bot was working, added one extra command and everything broke. Can anyone help me figure out why?

Tried to venture in to the realm of making discord bots. Followed along with a fairly simple tutorial, tweaking it along the way to fit what I was trying to make. The bot originally worked, but I went back in to add the "Mistake" command, and suddenly it's not working. I added in console.log pretty much everywhere, trying to figure out how far everything was getting.
When I start the bot, it will spit out the "Bot Online" log. When I input a command, it will spit out the "Commands" log, but it won't register the command at all. I've tried looking for any minor typos, missing brackets, etc... but I just can't seem to figure out what's gone wrong. I'm hoping that someone here can help! Thank you!
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
const SQLite = require('better-sqlite3');
const sql = new SQLite('./scores.sqlite');
client.on('ready', () => {
console.log('Bot Online');
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'goals';").get();
if (!table['count(*)']) {
sql.prepare('CREATE TABLE goals (id TEXT PRIMARY KEY, user TEXT, guild TEXT, goals INTEGER);').run();
sql.prepare('CREATE UNIQUE INDEX idx_goals_id ON goals (id);').run();
sql.pragma('synchronous = 1');
sql.pragma('journal_mode = wal');
}
//Statements to get and set the goal data
client.getGoals = sql.prepare('SELECT * FROM goals WHERE user = ? AND guild = ?');
client.setGoals = sql.prepare('INSERT OR REPLACE INTO goals (id, user, guild, goals) VALUES (#id, #user, #guild, #goals);');
});
client.on('message', (message) => {
if (message.author.bot) return;
let goalTotal;
if (message.guild) {
goalTotal = client.getGoals.get(message.author.id, message.guild.id);
if (!goalTotal) {
goalTotal = {
id: `${message.guild.id}-${message.author.id}`,
user: message.author.id,
guild: message.guild.id,
goals: 0,
};
}
}
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
console.log('Commands');
if (command === 'Goals') {
console.log('Goals');
return message.reply(`You Currently Have ${goalTotal.goals} Own Goals.`);
}
if (command === 'OwnGoal') {
console.log('Own Goal');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
userscore = {
id: `${message.guild.id}-${user.id}`,
user: user.id,
guild: message.guild.id,
goals: 0,
};
}
userscore.goals++;
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} has betrayed his team and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Mistake') {
console.log('Mistake');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
return message.reply('This person has no Rocket Bot activity.');
}
if (userscore === 0) {
return message.reply('This player currently has no goals.');
}
if (userscore > 0) {
userscore.goals--;
}
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} was falsely accused and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Leaderboard') {
console.log('Leaderboard');
const leaderboard = sql.prepare('SELECT * FROM goals WHERE guild = ? ORDER BY goals DESC;').all(message.guild.id);
const embed = new Discord.MessageEmbed()
.setTitle('Rocket Bot Leaderboard')
.setAuthor(client.user.username, client.user.avatarURL())
.setDescription('Total Goals Scored Against Own Team:')
.setFooter('Rocket Bot')
.setThumbnail('https://imgur.com/a/S9HN4bT')
.setColor('0099ff');
for (const data of leaderboard) {
embed.addFields({
name: client.users.cache.get(data.user).tag,
value: `${data.goals} goals`,
inline: true,
});
}
return message.channel.send({ embed });
}
if (command === 'RocketHelp') {
console.log('Help');
return message.reply(
'Rocket Bot Commands:' +
'\n' +
'!Goals - See How Many Goals You Have Scored Against Your Own Team' +
'\n' +
'!OwnGoal - Tag Another Player With # To Add One To Their Total' +
'\n' +
'!Mistake - Tag Another Player With # To Subtract One From Their Total' +
'\n' +
'!Leaderboard - Show The Current Leaderboard'
);
}
});
client.login(config.token);
You are improperly splitting the message content. You added g to the regex by accident.
Correct line:
const args = message.content.slice(config.prefix.length).trim().split(/ +/);
Because of improper args split, it could not find any command at all, hence no console log was invoked after Commands.

Trying to make a fish command /discord.js

Now, I have my shop and all the items already. I want the user so when they buy the FishingRod, they get put in a new Set();, and once they are in that set they can use the fish command. Here's my code for the 'buy' command:
else if (command === 'buy') {
const args = message.content.slice(PREFIX.length).trim().split(' ');
if (isDead.has(message.author.id)) {
message.channel.send('You\'re dead right now lmao you need to wait 5 more minutes before using any more currency and game related commands');
}
const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
if (!item) return message.channel.send('That item doesn\'t exist.');
if (args === 'FishingRod') {
hasRod.add(message.author.id);
}
if (item.cost > currency.getBalance(message.author.id)) {
return message.channel.send(`You don't have enough currency, ${message.author}`);
}
const user = await Users.findOne({ where: { user_id: message.author.id } });
currency.add(message.author.id, -item.cost);
await user.addItem(item);
message.channel.send(`You've bought a ${item.name}`);
}
As you can see, I've already made it so when the args are 'FishingRod', it puts them in the Set. The problem is that when this happens, and I try running the fish command, it still says I haven't got a FishingRod and need to buy one. Any help would be appreciated.
Okay, you're trying to compare the command arguments (which is an array) to a string. You could just do args[0] to get the first argument. Also, you're making it so that it has to be "FishingRod" and can't be lowercase. Try args[0].toLowerCase() === "fishingrod".

Cannot Pass Variables Through Different Scopes in DiscordJS

Alright so my problem is that in the first set of console.log(streamXXXX)s, where XXXX are the various variables, when I read their values they all read as they should, while in the second set they read as undefined. Is this a scope issue? Maybe an Async issue? I tried adding awaits to each time I make a web request but nothing seems to work, and one of the most interesting parts about this is the fact that there are no errors?
Anyways, my code is listed below, as well as a link to test it out in Repl using a sample bot I created. Below that is the list of libraries required for said program to run. Thanks!
if (!message.member.voiceChannel) return message.channel.send(`You do realize you have to be in a voice channel to do that, right ${message.author.username}?`)
if (!message.member.voiceConnection) message.member.voiceChannel.join().then(async connection => {
let streamURL = args.slice(1).join(" ")
let streamTitle = "";
let streamThumb = "";
let streamAuth = "";
let streamAuthThumb = "";
if (streamURL.includes("https://www.youtube.com") || streamURL.includes("https://youtu.be/") && !streamURL.includes(' ')) {
youtube.getVideo(streamURL)
.then(async results => {
let {
body
} = await snekfetch.get(`https://www.googleapis.com/youtube/v3/channels?part=snippet&id=${results.channel.id}&fields=items%2Fsnippet%2Fthumbnails&key=${ytapikey}`).query({
limit: 800
})
streamTitle = results.title
streamThumb = results.thumbnails.medium.url
streamAuth = results.channel.title
streamAuthThumb = body.items[0].snippet.thumbnails.medium.url
console.log(streamURL)
console.log(streamTitle)
console.log(streamThumb)
console.log(streamAuth)
console.log(streamAuthThumb)
})
.catch(console.error)
} else if (!streamURL.includes("https://www.youtube.com") || !streamURL.includes("https://youtu.be/")) {
youtube.searchVideos(streamURL)
.then(async results => {
let {
body
} = await snekfetch.get(`https://www.googleapis.com/youtube/v3/channels?part=snippet&id=${results[0].channel.id}&fields=items%2Fsnippet%2Fthumbnails&key=${ytapikey}`).query({
limit: 800
})
streamURL = results[0].url
streamTitle = results[0].title
streamThumb = results[0].thumbnails.default.medium.url
streamAuth = results[0].channel.title
streamAuthThumb = body.items[0].snippet.thumbnails.medium.url
}).catch(console.error)
} else {
return message.reply("I can only play videos from YouTube (#NotSponsored).")
}
console.log(streamURL)
console.log(streamTitle)
console.log(streamThumb)
console.log(streamAuth)
console.log(streamAuthThumb)
const stream = ytdl(streamURL, {
filter: 'audioonly'
})
const dispatcher = connection.playStream(stream)
dispatcher.on("end", end => {
return
})
let musicEmbed = new Discord.RichEmbed()
.setAuthor(streamAuth, streamAuthThumb)
.setTitle(`Now Playing: ${streamTitle}`)
.setImage(streamThumb)
.setColor(embedRed)
.setFooter(`${streamAuth} - ${streamTitle} (${streamURL}`)
await message.channel.send(musicEmbed)
})
Link to test out the program on a sample bot I made
Modules you will need to test this:
discord.js
simple-youtube-api
node-opus
ffmpeg
ffbinaries
ffmpeg-binaries
opusscript
snekfetch
node-fetch
ytdl-core
Thanks again!
The reason why your output is undefined is due to the way promises work and how you structured your code:
let streamTitle = "";
// 1. Promise created
youtube.getVideo(streamURL)
// 2. Promise still pending, skip for now
.then(async results => {
// 4. Promise fulfilled
console.log(results.title); // 5. Logged actual title
});
console.log(streamTitle); // 3. Logged ""
You already have the correct approach for your snekfetch requests, just need to apply it to the YT ones as well:
let streamTitle = "";
const results = await youtube.getVideo(streamURL);
streamTitle = results.title;
console.log(streamTitle); // Desired output

How to delete messages and log them back in another channel

I'm wondering how I could delete messages using a command like !clear [number] and have those messages fetched back to a channel including:
The user ID who used the command to delete the message
The user ID of who said the deleted message(s)
The content of the message(s)
The channel it has been deleted from
The timestamp of the message
All this stuff in a discord embed.
I'm relatively new to coding, and I'm developing this bot for a server with 40,000 people and we need to keep logs of all deleted messages.
Please, someone, help me out. I would greatly appreciate it :D. If needed I can explain in further detail if you still aren't sure of what I'm looking to do with this bot :D
To delete messages with a command, you have to use TextChannel.bulkDelete(), in this case maybe after fetching the messages via TextChannel.fetchMessages().
To "log" them, you may want to build a RichEmbed and put your info in the fields.
I would try something like this:
// ASSUMPTIONS:
// logs = the TextChannel in wich you want the embed to be sent
// trigger = the Messages that triggered the command
//
// This is just a sample implementation, it could contain errors or might not be the fastest
// Its aim is not to make it for you, but to give you a model
async function clear(n = 1, logs, trigger) {
let {channel: source, author} = trigger;
if (n < 1 || !logs || !source) throw new Error("One of the arguments was wrong.");
let coll = await source.fetchMessages({ limit: n }), // get the messages
arr = coll.array(),
collected = [],
embeds = [];
// create groups of 25 messages, the field limit for a RichEmbed
let index = 0;
for (let i = 0; i < arr.length; i += 25) {
collected.push([]);
for (let m = i; m < i + 25; m++)
if (arr[m]) collected[index].push(arr[m]);
index++;
}
// for every group of messages, create an embed
// I used some sample titles that you can obviously modify
for (let i = 0; i < collected.length; i++) {
let embed = new Discord.RichEmbed()
.setTitle(`Channel cleaning${collected.length > 1 ? ` - Part ${i+1}` : ""}`)
.setDescription(`Deleted from ${source}`)
.setAuthor(`${author.tag} (${author.id})`, author.displayAvatarURL)
.setTimestamp(trigger.editedAt ? trigger.editedAt : trigger.createdAt),
group = collected[i];
for (let msg of group) {
let a = `${msg.author.tag} (${msg.author.id}) at ${msg.editedAt ? msg.editedAt : msg.createdAt}`,
c = msg.content.length > 1024 ? msg.content.substring(0, msg.content.length - 3) + '...' : msg.content;
embed.addField(a, c);
}
embeds.push(embed);
}
// once the embeds are ready, you can send them
source.bulkDelete(coll).then(async () => {
for (let embed of embeds) await source.send({embed});
}).catch(console.error);
}
// this is a REALLY basic command implementation, please DO NOT use this as yours
client.on('message', async msg => {
let command = 'clear ';
if (msg.content.startsWith(command)) {
let args = msg.content.substring(command.length).split(' ');
if (isNaN(args[0]) || parseInt(args[0]) < 1) msg.reply(`\`${args[0]}\` is not a valid number.`);
else {
await msg.delete(); // delete your message first
let logs; // store your channel here
clear(parseInt(args[0]), logs, msg);
}
}
});
Note: the highlighting for this kind of stuff, with a lot of backtick strings and objects, is pretty bad. I suggest reading the code in another editor or you might end up not understanding anything

Categories