Skip to content

Instantly share code, notes, and snippets.

@PhilippIRL
Created July 8, 2022 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PhilippIRL/e8d1f12b4d5a7f77b1b6c0c32646f7aa to your computer and use it in GitHub Desktop.
Save PhilippIRL/e8d1f12b4d5a7f77b1b6c0c32646f7aa to your computer and use it in GitHub Desktop.
import protocol from 'minecraft-protocol'
async function queryMinecraftServerStatus(ip, port) {
try {
const data = await protocol.ping({ host: ip, port, closeTimeout: 3000, noPongTimeout: 3000 })
return { online: true, data }
} catch(e) {
return { online: false, data: null }
}
}
async function getServerStatusText(ip, port) {
const { online, data } = await queryMinecraftServerStatus(ip, port)
if(!online) {
return 'Der Server ist derzeit leider offline.'
}
if(typeof data?.players?.online === 'number') {
const onlinePlayers = data.players.online
const sample = data.players.sample
if(onlinePlayers === 0) {
return 'Es ist derzeit niemand online.'
} else if(onlinePlayers === 1) {
if(sample?.length > 0) {
return `Es ist derzeit nur ${sample[0].name} online.`
}
return 'Es ist derzeit ein:e Spieler:in online.'
} else {
if(sample?.length > 0) {
const difference = onlinePlayers - sample.length
if(difference > 0) {
const sampleNames = sample
.map(player => player.name)
.join(', ')
if(difference === 1) {
return `Es sind derzeit ${sampleNames} und eine weitere Spieler:in online.`
}
return `Es sind derzeit ${sampleNames} und ${difference} weitere Spieler:innen online.`
} else {
const sampleNames = sample
.map(player => player.name)
.map((name, index) => {
if(index === sample.length - 2) { // vorletzter eintrag
return name + ' und '
} else if(index === sample.length - 1) {
return name
} else {
return name + ', '
}
})
.join('')
return `Es sind derzeit ${sampleNames} online.`
}
}
return `Es sind derzeit ${data.players.online} Spieler:innen online.`
}
}
}
console.log(await getServerStatusText(process.argv[2], parseInt(process.argv[3])))
process.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment