Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix command parsing to use the bot_command entity #20

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 46 additions & 15 deletions src/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,21 +53,52 @@ export default function events (bot, dispatch) {

bot.on('text', (evt) => {
log('message event received: %o', evt)
if (evt.text.charAt(0) === '/') { // example: /np@nowplayingbot username
log(' |-> command detected')
let args = evt.text.substring(1).trim().split(/\s+/) // [ 'np@nowplayingbot', 'username' ]
let cmd = args.shift().split('@') // [ 'np', 'nowplayingbot' ]
// args is now [ 'username' ]
if (validCommand(me, cmd)) {
log(' `-> valid command "%s" with args: %o', cmd[0], args)
return dispatch(command({
chat: getChat(evt), // chat
user: getUser(evt), // user
cmd: cmd[0], // cmd
args, // args
raw: evt // rest of the options
}))
} else log(' !-> wrong recipient "%s", expected "%s"', cmd[1], me.username)

/*
* Check if we're dealing with a command, and emit a `command` event if so.
*
* The entities are parsed to ensure that formatted text beginning with
* a slash isn't erroneously interpreted as a command.
*
* Examples of valid commands:
*
* /np username
* /np@nowplayingbot username
*/

let isCommand = false
let cmdEntity

if (evt.entities) {
for (const entity of evt.entities) {
if (entity.type === 'bot_command' && entity.offset === 0) {
isCommand = true
cmdEntity = entity
break
}
}
}

if (!isCommand) return

log(' |-> command detected')

let cmd = evt.text.slice(1, cmdEntity.length).split('@')

// .filter(Boolean) is used to filter out empty string
let args = evt.text.slice(cmdEntity.length + 1).split(/\s+/).filter(Boolean)

if (validCommand(me, cmd)) {
log(' `-> valid command "%s" with args: %o', cmd[0], args)
return dispatch(command({
chat: getChat(evt), // chat
user: getUser(evt), // user
cmd: cmd[0], // cmd
args, // args
raw: evt // rest of the options
}))
} else {
log(' !-> wrong recipient "%s", expected "%s"', cmd[1], me.username)
}
})

Expand Down