Skip to content

Commit

Permalink
Add command module
Browse files Browse the repository at this point in the history
  • Loading branch information
Vahelnir committed Apr 14, 2017
1 parent 235efd2 commit 3b9ab50
Show file tree
Hide file tree
Showing 11 changed files with 527 additions and 1 deletion.
15 changes: 15 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"presets": ["stage-2", ["env", {
"targets": {
"node": "current"
},
"exclude": ["transform-async-to-generator"]
}]],
"plugins": [
"transform-flow-strip-types",
"syntax-flow", ["flow-runtime", {
"assert": true,
"annotate": true
}], "transform-decorators-legacy"
]
}
8 changes: 8 additions & 0 deletions .flowconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[ignore]
.*/node_modules/.*

[include]

[libs]

[options]
134 changes: 134 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@

# Created by https://www.gitignore.io/api/node,intellij,visualstudiocode

### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff:
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries

# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml

# Gradle:
.idea/**/gradle.xml
.idea/**/libraries

# Mongo Explorer plugin:
.idea/**/mongoSettings.xml

## File-based project format:
*.iws

## Plugin-specific files:

# IntelliJ
/out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721

# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr

# Sonarlint plugin
.idea/sonarlint

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env


### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

# End of https://www.gitignore.io/api/node,intellij,visualstudiocode

lib/
.vscode/
3 changes: 2 additions & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<<<<<<< HEAD
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007

Expand Down Expand Up @@ -671,4 +672,4 @@ into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
43 changes: 43 additions & 0 deletions example/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const Discord = require('discord.js');
const {
CommandManager
} = require('../lib/Krobotjs');

const bot = new Discord.Client();
const commands = new CommandManager({
parse: [{
// Match user (<@ID>)
match(message, arg) {
return (/^<@((\d)+)>$/g).test(arg)
},
// Replace it with an instance of Discord.User(ID)
async perform(message, arg) {
const gmember = await message.channel.guild.fetchMember((/^<@((\d)+)>$/g).exec(arg)[1]);
return gmember.user;
}
}]
});
// Create a command group
commands.group().prefix("#").apply(_ => {
commands
.command("test <message> <nb:^[0-9]+$> [opt]", (message, args) => message.reply('test')).register()
.sub("moche", (message, args) => message.reply('t es moche')).register();
commands
.command("lol <message>", (message, args) => message.reply('lol')).register()
.sub("test", (message, args) => message.reply('lol test')).register();
commands
.command("test2 <message>", (message, args) => message.reply(args.get('message'))).register()
.sub("moche", (message, args) => message.reply('t es moche 2')).register();
});

bot.on('message', message => {
// If the message is a command, then it will be executed and will return "true"
// yet, if there is no command, it will return "false"
if (!commands.dispatch(message))
// continue actions
});
bot.on('ready', _ => console.log('Connected'));
bot.on('reconnecting', _ => console.log('Reconnecting'));
bot.on('error', error => console.error(error));

bot.login(process.env.DISCORD_TOKEN);
25 changes: 25 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "krobotjs",
"version": "1.0.0",
"description": "A library that helps you create a discord bot with DiscordJS",
"main": "lib/Krobotjs.js",
"scripts": {
"build": "babel src/ -d lib/",
"prepublish": "npm run build"
},
"author": "Vavaballz",
"license": "GPL-3.0",
"dependencies": {
"discord.js": "^11.0.0"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-plugin-flow-runtime": "^0.10.0",
"babel-plugin-syntax-flow": "^6.18.0",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-plugin-transform-flow-strip-types": "^6.22.0",
"babel-preset-env": "^1.3.3",
"babel-preset-stage-2": "^6.24.1",
"flow-runtime": "^0.10.0"
}
}
82 changes: 82 additions & 0 deletions src/Commands/Builders/CommandBuilder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
const Command = require('../Command');

class CommandBuilder {

constructor(commandManager) {
this._commandManager = commandManager;
this._prefix = '';
this._middlewares = [];
this._command = '';
this._args = [];
this._parent = null;
this._handler = null;
}

parent(parent) {
this._parent = parent;
return this;
}

middleware(middleware: Function | Array<Function>) {
if (typeof middleware === 'function')
this._middlewares.push(middleware);
else if (middleware instanceof Array)
this._middlewares = this._middlewares.concat(middleware);
return this;
}

prefix(prefix: string) {
if (!this._parent || (this.parent && !this._parent.prefix))
this._prefix = prefix;
return this;
}

command(cmd: string) {
const split = cmd.split(' ');
this._command = split.shift();
split.forEach(arg => {
let optional = false;
let list = false;
let regex = new RegExp('', 'g');

if (arg === '*') arg = '[dynamic...]';
if (arg[0] === '[') optional = true;

arg = arg.slice(1, arg.length - 1);

if (arg.includes(':'))
[arg, regex] = arg.split(':')
regex = new RegExp(regex, 'g');

if (arg.endsWith('...'))
[list, arg] = [true, arg.replace('...')]

this._args.push({
key: arg,
optional,
list,
regex
});
});
return this;
}

handler(handler: Function) {
this._handler = handler;
return this;
}

build() {
return new Command(this._prefix + this._command, this._args, this._middlewares, this._handler);
}

register() {
const cmd = this.build();
if (this._parent) this._parent.sub(cmd);
else this._commandManager.register(cmd);
return cmd;
}

}

module.exports = CommandBuilder;
43 changes: 43 additions & 0 deletions src/Commands/Builders/GroupBuilder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// @flow
class GroupBuilder {

constructor(commandManager, defaultPrefix) {
this._commandManager = commandManager;
this._middlewares = [];
this._prefix = defaultPrefix;
this._parent = null;
}

parent(parent) {
console.log(parent)
this._parent = parent;
return this;
}

prefix(prefix: string) {
if (!this._parent || (this.parent && !this._parent.prefix))
this._prefix = prefix;
return this;
}

middleware(middleware: Function | Array<Function>) {
if (typeof middleware === 'function')
this._middlewares.push(middleware);
else if (middleware instanceof Array)
this._middlewares.concat(middleware);
return this;
}

apply(cb: Function) {
this._commandManager.push({
prefix: this._prefix,
middlewares: this._middlewares,
parent: this._parent
});
cb();
this._commandManager.pop();
}

}

module.exports = GroupBuilder;
Loading

0 comments on commit 3b9ab50

Please sign in to comment.