Merge branch 'devbot' into discordjs-v14-upgrade

This commit is contained in:
SileNce5k 2024-06-11 19:37:00 +02:00 committed by GitHub
commit 9784676e06
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 205 additions and 69 deletions

View file

@ -15,7 +15,7 @@ module.exports = {
.setTimestamp() .setTimestamp()
.setAuthor({name: client.user.username, iconURL: client.user.avatarURL({ dynamic: true, size: 4096 })}) .setAuthor({name: client.user.username, iconURL: client.user.avatarURL({ dynamic: true, size: 4096 })})
.addFields({ .addFields({
name: "General info", value: `Name: ${client.user.username}\nPrefix: ${prefix}\nTotal Servers: ${guildCount}\nCreation Date: ${getCreationDate(client)}\nSource: [Click Here](https://github.com/SileNce5k/discord_bot)`, name: "General info", value: `Name: ${client.user.username}\nPrefix: ${prefix}\nTotal Servers: ${guildCount}\nTotal Commands: ${client.commands.size}\nCreation Date: ${getCreationDate(client)}\nSource: [Click Here](https://github.com/SileNce5k/discord_bot)`,
},) },)
message.channel.send({embeds :[embed]}) message.channel.send({embeds :[embed]})

View file

@ -6,7 +6,7 @@ const getSubdirFiles = require('../../util/getSubdirFiles');
module.exports = { module.exports = {
name: 'help', name: 'help',
description: 'List all available commands.', description: 'List all available commands.',
moreHelp: ["Examples:","`<prefix>help` will return help with a small description for each command", moreHelp: ["Examples:","`<prefix>help [optional_page]` will return help with a small description for each command",
"`<prefix>help <another_command>` will return help with a more descriptive description", "`<prefix>help <another_command>` will return help with a more descriptive description",
"The descriptive description isn't available on all commands", "The descriptive description isn't available on all commands",
"`<prefix>help netmodules` to display help for netmodules" "`<prefix>help netmodules` to display help for netmodules"
@ -15,15 +15,29 @@ module.exports = {
let commands = "" let commands = ""
let commandFiles = getSubdirFiles('commands/') let commandFiles = getSubdirFiles('commands/')
let x = false; let x = false;
let fieldName = "General"; let fieldName = `Page [[page]]/${Math.round(client.commands.size / 10)}`;
let iteration = 0;
let num_in_args = false;
let added_commands = 0;
let page = -1;
if (args[0] == "netmodules") { if (args[0] == "netmodules") {
commandFiles = fs.readdirSync('../../netload').filter(file => file.endsWith('.js')); commandFiles = fs.readdirSync('../../netload').filter(file => file.endsWith('.js'));
if (commandFiles.length == 0) { if (commandFiles.length == 0) {
message.channel.send("There are no netmodules currently loaded.") message.channel.send("There are no netmodules currently loaded.")
x = true; x = true;
} }
}else if(!isNaN(parseInt(args[0])) && parseInt(args[0])){
num_in_args = true;
iteration = ( parseInt(args[0]) - 1) * 10;
page = Math.round(parseInt(args[0]))
} }
if(page === -1){
page = 1;
}
fieldName = fieldName.replace("[[page]]", page);
const max_commands = iteration + 10;
if (x) return; if (x) return;
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
@ -32,16 +46,27 @@ module.exports = {
.setTimestamp() .setTimestamp()
.setAuthor({name: client.user.username, iconURL: client.user.avatarURL({ dynamic: true, size: 4096 })}) .setAuthor({name: client.user.username, iconURL: client.user.avatarURL({ dynamic: true, size: 4096 })})
let start = 0;
for (const file of commandFiles) { for (const file of commandFiles) {
if(iteration >= max_commands) break;
const command = require(`../../${file}`); const command = require(`../../${file}`);
if(command.disabled) continue; if(command.disabled) continue;
if (args[0] == "admin") { if (args[0] == "admin") {
if (command.admin) if (command.admin)
commands = commands + `${prefix}${command.name} | ${command.description}\n` commands = commands + `${prefix}${command.name} | ${command.description}\n`
}else if(!args[0]){ }else if(!args[0] || num_in_args){
if (!command.admin) if (!command.admin){
commands = commands + `${prefix}${command.name} | ${command.description}\n` if(start < iteration){
}else{
added_commands++
commands = commands + `${prefix}${command.name} | ${command.description}\n`;
iteration++
}
start++;
}
}else if(args[0] === command.name){ }else if(args[0] === command.name){
commands = commands + `${prefix}${command.name}\n` commands = commands + `${prefix}${command.name}\n`
embed.setTitle(command.name.charAt(0).toUpperCase() + command.name.slice(1)) embed.setTitle(command.name.charAt(0).toUpperCase() + command.name.slice(1))
@ -65,6 +90,10 @@ module.exports = {
embed.addFields( embed.addFields(
{ name: fieldName, value: commands }, { name: fieldName, value: commands },
) )
if(embed.fields[0].value.length > 1023){
message.channel.send(`There are more than 1023 characters`)
}else {
message.channel.send({embeds :[embed]}); message.channel.send({embeds :[embed]});
}
}, },
}; };

View file

@ -1,25 +1,41 @@
const fmlogin = require("../../util/lastfm/fmlogin"); const fmlogin = require("../../util/lastfm/fmlogin");
const displayCurrentScrobble = require("../../util/lastfm/displayCurrentScrobble"); const getCurrentScrobble = require("../../util/lastfm/getCurrentScrobble");
const getTopTracks = require("../../util/lastfm/getTopTracks");
const help = require("../info/help");
module.exports = { module.exports = {
name: 'fm', name: 'fm',
description: 'Last fm commands. See `<prefix>help fm` for more info.', description: 'Last fm commands. See `<prefix>help fm` for more info.',
moreHelp: ["Set username: `<prefix>fm set <lastfm_username>`",], moreHelp: ["Info: Having a space between fm and the subcommand makes no difference.",
async execute({ message, args }) { "They behave the same (for example: `<prefix>fmtt` and `<prefix>fm tt`)",
let sendText = "Something went wrong."; "Set username: `<prefix>fmset <lastfm_username>`",
"Get current scrobble: `<prefix>fm`",
"Get top tracks: `<prefix>fmtt`"
],
async execute({ message, args, prefix, client }) {
let sendText = {text: "Something went wrong.", embed: null};
switch (args[0]) { switch (args[0]) {
case "help": case "help":
sendText = this.moreHelp; help.execute({ message: message, args: ["fm"], prefix: prefix, client: client });
break; return;
case "set": case "set":
sendText = await fmlogin(message.author.id, args[1]); sendText.text = await fmlogin(message.author.id, args[1]);
break;
case "toptracks":
case "tt":
args.shift();
sendText.text = await getTopTracks(message.author.id, args);
break; break;
default: default:
sendText.text = `${args[0]} is not a valid subcommand.\nSee \`${prefix}help fm\` for more info.`;
break; break;
} }
if(args.length < 1){ if(args.length < 1){
sendText = await displayCurrentScrobble(message.author.id); sendText = await getCurrentScrobble(message.author.id, message.guild);
}
if(sendText.embed != null){
message.channel.send({embeds :[sendText.embed]})
}else{
message.channel.send(sendText.text);
} }
message.channel.send(sendText);
} }
}; };

2
package-lock.json generated
View file

@ -3923,4 +3923,4 @@
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="
} }
} }
} }

View file

@ -7,16 +7,22 @@ module.exports = function(client, owners, message, globalPrefix){
if (serverPrefix) { if (serverPrefix) {
prefix = serverPrefix; prefix = serverPrefix;
} }
if(message.content.startsWith(`<@${client.user.id}>`)){ if(message.content.startsWith(`<@${client.user.id}>`)){
let regex = new RegExp("(<@" + client.user.id + ">) *") let regex = new RegExp("(<@" + client.user.id + ">) *")
message.content = message.content.replace(regex, prefix); message.content = message.content.replace(regex, prefix);
} }
if (!message.guild || message.author.bot || !message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).split(" ") let args = message.content.slice(prefix.length).split(" ")
if(args[0] !== "fm" && args[0].startsWith("fm")){
let firstElement = args[0];
args.splice(0, 1, firstElement.substring(0, 2), firstElement.substring(2));
}
const commandName = args.shift().toLowerCase(); const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName); const command = client.commands.get(commandName);
const netModule = client.netmodules.get(commandName); const netModule = client.netmodules.get(commandName);
if (!message.guild || message.author.bot || !message.content.startsWith(prefix)) return;
if (!command){ if (!command){
if (netModule){ if (netModule){
try { try {

View file

@ -1,48 +0,0 @@
require("dotenv").config();
module.exports = async function(userID) {
let sendText = "";
let scrobble = {};
const apiKey = process.env.LAST_FM_API_KEY;
let lastfmUsername = await new Promise((resolve, reject)=>{
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('data/database.db');
db.get(
`SELECT * FROM lastfm WHERE userID = ?`,
[userID],
(error, row) => {
if (error) {
console.error(error);
reject(error);
} else {
if (row == undefined) {
resolve(undefined);
}
resolve(row.lastfmUsername);
}
db.close();
}
);
});
if(lastfmUsername != undefined){
scrobble = await new Promise ((resolve, reject) => {
fetch(`https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=${lastfmUsername}&api_key=${apiKey}&format=json`)
.then(response => response.json())
.then(data => {
let scrobble = {};
let track = data.recenttracks.track[0];
scrobble.artist = track.artist["#text"];
scrobble.song = track.name;
scrobble.album = track.album["#text"];
resolve(scrobble);
})
.catch(error => {
console.error(error);
reject(error);
});
});
sendText = `Currently scrobbling:\n${scrobble.artist} - ${scrobble.song}\nAlbum: ${scrobble.album}`;
} else {
sendText = "You haven't set your last.fm username yet. Use `fm set <lastfm_username>` to set it.";
}
return sendText;
}

View file

@ -33,7 +33,6 @@ module.exports = async function(userID, lastfmUsername) {
reject(sendText); reject(sendText);
} else { } else {
let sendText = `Your last.fm username has been set to '${lastfmUsername}'.`; let sendText = `Your last.fm username has been set to '${lastfmUsername}'.`;
console.log(sendText);
resolve(sendText); resolve(sendText);
} }
db.close(); db.close();
@ -53,7 +52,6 @@ module.exports = async function(userID, lastfmUsername) {
reject(sendText); reject(sendText);
} else { } else {
let sendText = `Your last.fm username has been updated to '${lastfmUsername}'.`; let sendText = `Your last.fm username has been updated to '${lastfmUsername}'.`;
console.log(sendText);
resolve(sendText); resolve(sendText);
} }
db.close(); db.close();

View file

@ -0,0 +1,56 @@
const getNickname = require("../getNickname");
const parseMention = require("../parseMention");
const getFmUsername = require("./getFmUsername");
const Discord = require('discord.js');
require("dotenv").config();
module.exports = async function(userID, guild) {
let parse = parseMention(userID, guild)
let user = guild.members.cache.get(parse);
let nickname = getNickname(user, guild)
if(nickname == null){
nickname = user.user.username;
}
let isCurrentScrobble = "Current";
let sendText = {text: "", embed: null}
let scrobble = {};
const apiKey = process.env.LAST_FM_API_KEY;
let lastfmUsername = await getFmUsername(userID);
if(lastfmUsername != undefined){
scrobble = await new Promise ((resolve, reject) => {
fetch(`https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=${lastfmUsername}&api_key=${apiKey}&format=json`)
.then(response => response.json())
.then(data => {
let scrobble = {};
let track = data.recenttracks.track[0];
scrobble.artist = track.artist["#text"];
scrobble.song = track.name;
scrobble.album = track.album["#text"];
scrobble.cover = track.image[3]["#text"];
console.log(typeof track['@attr'].nowplaying);
if(track['@attr'].nowplaying === "true"){
isCurrentScrobble = "Last";
}
resolve(scrobble);
})
.catch(error => {
console.error(error);
reject(error);
});
});
const embed = new Discord.MessageEmbed()
.setAuthor(`Now playing - ${nickname}`, user.user.avatarURL({ dynamic: true, size: 4096 }))
.setThumbnail(scrobble.cover)
.setColor(15780145)
.addFields({
name: "Current:", value: `${scrobble.song}\n **${scrobble.artist} • ** ${scrobble.album}`
},
{
name: "Previous:", value: `**TODO: Make this show the previous scrobble**`
},)
sendText.embed = embed;
} else {
sendText.text = "You haven't set your last.fm username yet. Use `fm set <lastfm_username>` to set it.";
}
return sendText;
}

View file

@ -0,0 +1,24 @@
module.exports = async function(userID) {
let lastfmUsername = await new Promise((resolve, reject)=>{
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('data/database.db');
db.get(
`SELECT * FROM lastfm WHERE userID = ?`,
[userID],
(error, row) => {
if (error) {
console.error(error);
reject(error);
} else {
if (row == undefined) {
resolve(undefined);
}else{
resolve(row.lastfmUsername);
}
}
db.close();
}
);
});
return lastfmUsername;
}

View file

@ -0,0 +1,55 @@
// http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=username&api_key=YOUR_API_KEY&format=json
const getFmUsername = require("./getFmUsername")
module.exports = async function (userID, option) {
let lastfmUsername = await getFmUsername(userID);
let sendText = "";
let tracks = [];
const options = {
"alltime": "overall",
"weekly": "7day",
"monthly": "1month",
"quarterly": "3month",
"halfyear": "6month",
"yearly": "12month",
undefined: "7day"
}
if(option.length === 0){
option[0] = "weekly"
}
option[0] = options[option[0]];
if(option[0] === undefined)
option[0] = options[option[0]];
const apiKey = process.env.LAST_FM_API_KEY;
if(lastfmUsername != undefined){
tracks = await new Promise ((resolve, reject) => {
fetch(`https://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=${lastfmUsername}&period=${option[0]}&api_key=${apiKey}&format=json`)
.then(response => response.json())
.then(data => {
for(let i = 0; i < 10; i++){
let track = {}
let currentTrack = data.toptracks.track[i];
track.artist = currentTrack.artist.name;
track.song = currentTrack.name;
track.playcount = currentTrack.playcount;
tracks.push(track);
}
resolve(tracks);
})
.catch(error => {
console.error(error);
reject(error);
});
});
sendText = `Top weekly tracks for ${lastfmUsername}:\n`;
for(let i = 0; i < tracks.length; i++){
sendText += `${i}. ${tracks[i].artist} - ${tracks[i].song} (${tracks[i].playcount} plays)\n`;
}
} else {
sendText = "You haven't set your last.fm username yet. Use `fm set <lastfm_username>` to set it.";
}
return sendText;
}