Skip to content

Commit

Permalink
v0.9.0
Browse files Browse the repository at this point in the history
- Added Activity and status for bot
- No longer need icon url of mc server
- Better Error Logging
- Activity with player Count
  • Loading branch information
NooberPro committed May 10, 2023
1 parent 38b80ac commit f6097e8
Show file tree
Hide file tree
Showing 4 changed files with 180 additions and 60 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ This bot code uses **node-mcstatus npm package** for getting status of Minecraft
- [ ] IP address command
- [ ] Minecraft version command
- [ ] Player list command
- [ ] Web Map command
- [ ] Site command
- [ ] Slash commands
- [ ] Bot status (activity) for players online number
- [x] Bot status (activity) for players online number
- [ ] Help command with all commands listing
- [x] Error detection of config
- [ ] And many other things 😉
Expand Down
19 changes: 15 additions & 4 deletions config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,31 @@ module.exports = {
bot: {
token: 'your-bot-token-here', // Paste Your Bot's Token here
updateInterval: 60, // Time Period between auto changing status in seconds like 60sec = 1min. Recommend is above 60.
presence: {
text: {
// Use {playeronline} for no. of players online and {playermax} for maximum players .
online: '{playeronline}/{playermax} players online', // Custom text of your choice.
offline: 'Server is Offline', // Status text when the server is offline.
},
status: {
// online, idle, dnd (do not disturb), invisible are the options
online: 'online', // The status of the bot when mc server is Online.
offline: 'idle', // The status of the bot when mc server is Offline.
},
activity: 'Watching', // Playing, Listening, Watching, Competing are the options. This comes before the status text.
},
},

mcserver: {
ip: 'demo.mcstatus.io', // Ip Address of your minecraft server like mc.hypixel.net
port: 25565, // Port of your minecraft server like 25565. Default is 25565 if nothing is defined here.
port: 25565, // Port of your minecraft server like 25565 for java and 19132 for bedrock.
type: 'java', // Type of minecraft server, "java" or "bedrock". Default is Java.
name: 'Demo Server', //Name of your Minecraft Server like Hypixel
icon: 'https://i.imgur.com/eBM2SXq.png', //Url of your server icon.
},
status_reply: {
// If a message contains triggerWords and reply if server is online with players or offline.
enabled: false,
triggerWords: [
// Add words by "" and ,
// Add words by '' and ,
'Is the server up ?',
'Is the server online ?',
'Is the server down ?',
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "minecraft-discord-bot",
"version": "0.6.0",
"version": "0.9.0",
"description": "A discord bot that shows info and status of your minecraft server including players, version, and many more features.",
"main": "src/index.js",
"scripts": {
Expand All @@ -25,7 +25,7 @@
"homepage": "https://github.com/NooberPro/minecraft-discord-bot#readme",
"dependencies": {
"chalk": "^4.1.2",
"discord.js": "^14.9.0",
"discord.js": "^14.11.0",
"djs-commander": "^0.0.45",
"node-mcstatus": "^1.0.2"
}
Expand Down
213 changes: 161 additions & 52 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
const fs = require('fs');
const mcs = require('node-mcstatus');
const { statusBedrock, statusJava } = require('node-mcstatus');
const path = require('path');
const { Client, IntentsBitField, EmbedBuilder } = require('discord.js');
const c = require('../config.js');
const {
Client,
IntentsBitField,
EmbedBuilder,
ActivityType,
} = require('discord.js');
const config = require('../config.js');
const { CommandHandler } = require('djs-commander');
const data = JSON.parse(fs.readFileSync('data.json'));
const chalk = require('chalk');
Expand All @@ -18,31 +23,40 @@ const client = new Client({

const errors = [];

if (c.bot.token.startsWith('your-bot-token-here'))
console.log(
chalk.red('Checking for Errors in the config.js file. Please Wait.')
);

if (config.bot.token.startsWith('your-bot-token-here'))
errors.push('Bot Token is Invalid.');
if (c.mcserver.ip === '')

if (!config.mcserver.ip)
errors.push("The Minecraft server's IP address has not been specified.");
if (c.mcserver.type !== 'java' && c.mcserver.type !== 'bedrock')

if (!['java', 'bedrock'].includes(config.mcserver.type))
errors.push('Invalid Minecraft server type. Should be "java" or "bedrock".');

if (c.mcserver.name === '')
if (!config.mcserver.name)
errors.push("The Minecraft server's name has not been specified.");
if (c.mcserver.icon === '')
errors.push("The Minecraft server's icon has not been specified.");

if (errors.length > 0) {
console.error(chalk.red('Config file has the following errors:'));
errors.forEach((item) => console.log(chalk.keyword('orange')(item)));
process.exit(1);
}

new CommandHandler({
client,
eventsPath: path.join(__dirname, 'events'),
});

const offlineStatus = new EmbedBuilder()
.setColor('DarkRed')
.setTitle(':red_circle: OFFLINE')
.setAuthor({ name: c.mcserver.name, iconURL: c.mcserver.icon })
.setAuthor({
name: config.mcserver.name,
iconURL: `https://api.mcstatus.io/v2/icon/${config.mcserver.ip}:${config.mcserver.port}`,
})
.setTimestamp()
.setFooter({ text: 'Updated at' });

Expand All @@ -53,61 +67,119 @@ async function statusEdit(statusEmbed, status) {
await message.edit({ content: '', embeds: [statusEmbed] });
console.log(`The status is updated to ${status}`);
} catch (error) {
console.error(error);
console.error(`Error with editing status message ${error.message}`);
}
}

function presenceText(data) {
let offlineText = config.bot.presence.text.online;
offlineText = offlineText.replace(
/{playeronline}/g,
`${data.players.online}`
);
offlineText = offlineText.replace(/{playermax}/g, `${data.players.max}`);

return offlineText;
}

function statusRetrival() {
if (c.mcserver.type === 'bedrock') {
mcs
.statusBedrock(c.mcserver.ip, c.mcserver.port)
if (config.mcserver.type === 'bedrock') {
statusBedrock(config.mcserver.ip, config.mcserver.port)
.then((data) => {
const onlineEmbedBedrock = new EmbedBuilder()
.setColor('Green')
.setTitle(':green_circle: ONLINE')
.setAuthor({ name: c.mcserver.name, iconURL: c.mcserver.icon })
.addFields(
{
name: '__**PLAYERS**__',
value: `**${data.players.online}**/**${data.players.max}**\n`,
},
{
name: '__**MOTD**__',
value: `**${data.motd.clean}**`,
},
{
name: '__**IP ADDRESS**__',
value: `**${data.host}:${data.port}**`,
},
{
name: '__**INFO**__',
value: `**Version: ${data.version.name}\nGameMode: ${data.gamemode}\n Edition: ${data.edition}**`,
}
)
.setTimestamp()
.setFooter({ text: 'Updated at' });
statusEdit(onlineEmbedBedrock, chalk.green`✔ Online`);
if (data.online === true && data.players.max > 0) {
const onlineEmbedBedrock = new EmbedBuilder()
.setColor('Green')
.setTitle(':green_circle: ONLINE')
.setAuthor({
name: config.mcserver.name,
iconURL: `https://api.mcstatus.io/v2/icon/${config.mcserver.ip}:${config.mcserver.port}`,
})
.addFields(
{
name: '__**PLAYERS**__',
value: `**${data.players.online}**/**${data.players.max}**\n`,
},
{
name: '__**MOTD**__',
value: `**${data.motd.clean}**`,
},
{
name: '__**SERVER ADDRESS**__',
value: `**IP: \`${data.host}\`\nPort: \`${data.port}\`**`,
},
{
name: '__**INFO**__',
value: `**Version: ${data.version.name}\nGameMode: ${data.gamemode}\n Edition: ${data.edition}**`,
}
)
.setTimestamp()
.setFooter({ text: `Updated at` });

statusEdit(
onlineEmbedBedrock,
`${chalk.green('✔ Online')} with ${chalk.green(
data.players.online
)} Players Playing.`
);
const statusText = presenceText(data);
client.user.setStatus(config.bot.presence.status.online);
client.user.setActivity(statusText, {
type: ActivityType[config.bot.presence.activity],
});
console.log(
`Status set to: ${chalk.green(
`${config.bot.presence.activity} ${statusText}`
)}`
);
} else {
statusEdit(offlineStatus, chalk.red`❌ Offline`);
client.user.setActivity(config.bot.presence.text.offline, {
type: ActivityType[config.bot.presence.activity],
});
client.user.setStatus(config.bot.presence.status.offline);
console.log(
`Status set to: ${chalk.green(
`${config.bot.presence.activity} ${config.bot.presence.text.offline}`
)}`
);
}
})
.catch((error) => {
console.log(error);
statusEdit(
offlineStatus,
chalk.red`Setting Offline due to a problem with mcstatus.io API service or your Network.`
);
console.log(
`A Error with Bedrock auto-changing status: \n ${chalk.keyword(
'orange'
)(error)}`
);
client.user.setStatus(config.bot.presence.status.offline);
client.user.setActivity(config.bot.presence.text.offline, {
type: ActivityType[config.bot.presence.activity],
});
console.log(
`Status set to: ${chalk.green(
`${config.bot.presence.activity} ${config.bot.presence.text.offline}`
)}`
);
});
} else {
mcs
.statusJava(c.mcserver.ip, c.mcserver.port)
statusJava(config.mcserver.ip, config.mcserver.port)
.then((data) => {
module.exports = {
data,
};
if (data.online === true && data.players.max > 0) {
const playerList = data.players.list.reduce((acc, item) => {
return acc + item.name_clean + '\n';
return `${acc}${item.name_clean} \n`;
}, '');
const onlineStatus = new EmbedBuilder()
.setColor('DarkGreen')
.setTitle(':green_circle: ONLINE')
.setAuthor({
name: c.mcserver.name,
iconURL: c.mcserver.icon,
name: config.mcserver.name,
iconURL: `https://api.mcstatus.io/v2/icon/${config.mcserver.ip}:${config.mcserver.port}`,
})
.addFields(
{
Expand All @@ -130,17 +202,54 @@ function statusRetrival() {
}
)
.setTimestamp()
.setFooter({
text: 'Updated at',
});
statusEdit(onlineStatus, chalk.green`✔ Online`);
.setFooter({ text: `Updated at` });

statusEdit(
onlineStatus,
`${chalk.green('✔ Online')} with ${chalk.green(
data.players.online
)} Players Playing.`
);
const statusText = presenceText(data);
client.user.setActivity(statusText, {
type: ActivityType[config.bot.presence.activity],
});
client.user.setStatus(config.bot.presence.status.online);
console.log(
`Status set to: ${chalk.green(
`${config.bot.presence.activity} ${statusText}`
)}`
);
} else {
statusEdit(offlineStatus, chalk.red`❌Offline`);
client.user.setActivity(config.bot.presence.text.offline, {
type: ActivityType[config.bot.presence.activity],
});
client.user.setStatus(config.bot.presence.status.offline);
console.log(
`Status set to: ${config.bot.presence.activity} ${config.bot.presence.text.offline}`
);
}
})
.catch((error) => {
statusEdit(offlineStatus, chalk.red`❌Offline`);
console.error(error);
statusEdit(
offlineStatus,
chalk.red`Setting due to a problem with mcstatus.io API service or your Network.`
);
console.log(
s`A Error with Java auto-changing status : \n ${chalk.keyword(
'orange'
)(error)}`
);
client.user.setStatus(config.bot.presence.status.offline);
client.user.setActivity(config.bot.presence.text.offline, {
type: ActivityType[config.bot.presence.activity],
});
console.log(
`Status set to: ${chalk.green(
`${config.bot.presence.activity} ${config.bot.presence.text.offline}`
)}`
);
});
}
}
Expand All @@ -150,4 +259,4 @@ module.exports = {
statusRetrival,
};

client.login(c.bot.token);
client.login(config.bot.token);

0 comments on commit f6097e8

Please sign in to comment.