chipmunkbot3/commands/music.js

96 lines
2.5 KiB
JavaScript

const { literal, argument, DynamicCommandExceptionType } = require('brigadier-commands')
const { location, path, isUrl } = require('../util/command/argument/location')
const TextMessage = require('../util/command/text_message')
const fs = require('fs')
const SONG_DIRECTORY = 'songs'
const FILE_DOES_NOT_EXIST_ERROR = new DynamicCommandExceptionType(filename => new TextMessage(['File ', filename, ' does not exist']))
module.exports = {
register (dispatcher) {
const node = dispatcher.register(
literal('music')
.then(
literal('play')
.then(
argument('location', location(SONG_DIRECTORY))
.executes(this.playCommand)
)
)
.then(
literal('skip')
.executes(this.skipCommand)
)
.then(
literal('stop')
.executes(this.stopCommand)
)
.then(
literal('loop')
.executes(this.loopCommand)
)
.then(
literal('list')
.executes(this.listCommand.bind(this))
.then(
argument('location', path(SONG_DIRECTORY))
.executes(this.locationListCommand.bind(this))
)
)
)
node.description = 'Plays songs using note block sounds'
node.permissionLevel = 0
},
playCommand (context) {
const source = context.source
const bot = source.bot
const filepath = context.getArgument('location')
if (!isUrl(filepath) && !fs.existsSync(filepath)) throw FILE_DOES_NOT_EXIST_ERROR.create(filepath)
bot.music.queue.push(filepath)
source.sendFeedback([
{ text: 'Added ', ...bot.styles.primary },
{ text: filepath.replace(/.+\//g, ''), ...bot.styles.secondary },
' to the music queue.'
], false)
},
skipCommand (context) {
const bot = context.bot
bot.music.skip()
},
stopCommand (context) {
const bot = context.bot
bot.music.stop()
},
loopCommand (context) {
const bot = context.bot
bot.music.looping = !bot.music.looping
},
listCommand (context) {
this.listSongs(context, SONG_DIRECTORY)
},
locationListCommand (context) {
this.listSongs(context, context.getArgument('location'))
},
async listSongs (context, path) {
const source = context.source
const bot = source.bot
try {
const list = await bot.listFiles(path)
source.sendFeedback(['', { text: 'Songs - ', ...bot.styles.primary }, ...list], false)
} catch (error) {
source.sendError(error.toString())
}
}
}