Repository: brussell98/Mirai Branch: master Commit: 0b2d964013ce Files: 34 Total size: 188.6 KB Directory structure: gitextract_jd2u6nxo/ ├── .codeclimate.yml ├── .eslintrc.json ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── .jsdoc.json ├── .npmignore ├── LICENSE ├── README.md ├── docBeautify.js ├── docs/ │ ├── AbstractCommand.html │ ├── AbstractCommandPlugin.html │ ├── AbstractEventPlugin.html │ ├── AbstractMiddleware.html │ ├── Bot.html │ ├── ChatHandler.html │ ├── Logger.html │ ├── index.html │ ├── scripts/ │ │ ├── linenumber.js │ │ └── prettify/ │ │ ├── Apache-License-2.0.txt │ │ ├── lang-css.js │ │ └── prettify.js │ └── styles/ │ ├── jsdoc.css │ └── prettify.css ├── examples/ │ └── mongoose/ │ ├── MongoMiddle.js │ └── index.js ├── index.js ├── lib/ │ ├── Base/ │ │ ├── AbstractCommand.js │ │ ├── AbstractCommandPlugin.js │ │ ├── AbstractEventPlugin.js │ │ └── AbstractMiddleware.js │ ├── Bot.js │ ├── ChatHandler.js │ └── Logger.js └── package.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .codeclimate.yml ================================================ engines: eslint: enabled: true channel: "eslint-3" config: .eslintrc duplication: enabled: false config: languages: - javascript fixme: enabled: true ratings: paths: - "**.js" exclude_paths: - docs/* - examples/* ================================================ FILE: .eslintrc.json ================================================ { "parserOptions": { "ecmaVersion": 2017 }, "env": { "es6": true, "node": true }, "ecmaFeatures": { "modules": true }, "rules": { "no-console": 0, "no-control-regex": 0, "no-alert": 1, "no-else-return": 1, "no-redeclare": 2, "no-useless-escape": 1, "no-inner-declarations": 0, "array-bracket-spacing": ["warn", "never"], "brace-style": ["warn", "1tbs", { "allowSingleLine": true }], "no-trailing-spaces": 1, "space-before-function-paren": ["warn", "never"], "arrow-spacing": 1, "comma-spacing": ["warn", { "before": false, "after": true }], "indent": ["error", "tab", { "SwitchCase": 1 }], "require-jsdoc": ["warn", { "require": { "MethodDefinition": true, "ClassDeclaration": true } }], "valid-jsdoc": ["warn", { "prefer": { "arg": "param", "argument": "param", "constructor": "class", "return": "returns", "virtual": "abstract" }, "preferType": { "boolean": "Boolean", "number": "Number", "object": "Object", "string": "String" }, "requireReturn": false, "requireParamDescription": true, "requireReturnDescription": true }] }, "extends": "eslint:recommended" } ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: brussell98 # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel custom: # Replace with a single custom sponsorship URL ================================================ FILE: .gitignore ================================================ *.tmp *.env .vscode node_modules config.json .idea/ ================================================ FILE: .jsdoc.json ================================================ { "tags": { "allowUnknownTags": true, "dictionaries": ["jsdoc"] }, "source": { "include": ["lib/"], "includePattern": ".js$", "excludePattern": "(node_modules/|docs)" }, "plugins": [ "plugins/markdown" ], "templates": { "default": { "outputSourceFiles": false, "includeDate": false }, "docdash": { "sort": true }, "cleverLinks": false, "monospaceLinks": true }, "opts": { "destination": "./docs/", "encoding": "utf8", "private": true, "recurse": true, "template": "./node_modules/docdash" } } ================================================ FILE: .npmignore ================================================ *.tmp *.env .vscode node_modules config.json # npm ignore docs examples .jsdoc.json .codeclimate.yml ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2016 Brussell Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Mirai Bot Core Discord server [![David](https://img.shields.io/david/brussell98/Mirai.svg?maxAge=2592000)](https://david-dm.org/brussell98/Mirai) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/brussell98/Mirai/master/LICENSE) [![Code Climate](https://codeclimate.com/github/brussell98/Mirai/badges/gpa.svg)](https://codeclimate.com/github/brussell98/Mirai) [![npm](https://img.shields.io/npm/v/mirai-bot-core.svg)](https://www.npmjs.com/package/mirai-bot-core) A powerful Discord bot core using [Eris](https://github.com/abalabahaha/eris/). #### [Documentation](http://brussell98.github.io/Mirai/index.html) | [Eris Docs](https://abal.moe/Eris/docs/index.html) | [Mirai Bot Website](http://mirai.brussell.me) | [Support me on Patreon](http://patreon.com/brussell98) | [Discord Server](https://discord.gg/rkWPSdu) | [Mirai Bot Combined Todo List](https://trello.com/b/Uw5wZLzJ) mirai-bot-core supports advanced application monitoring with **[sentry.io](http://sentry.io)** using raven. For more information [head over to the docs](http://brussell98.github.io/Mirai/Logger.html). ## Installing ``` yarn add mirai-bot-core ``` ```js const Mirai = require('mirai-bot-core'); const bot = new Mirai(config); ``` ## Abstract Classes Abstract classes are provided to ensure you have the required methods. They can be accessed like so: ```js const AbstractCommand = require('mirai-bot-core/lib/Base/AbstractCommand'); class PingCommand extends AbstractCommand { constructor() { super(); } } ``` ================================================ FILE: docBeautify.js ================================================ const beautify_html = require('js-beautify').html; const fs = require('fs'); fs.readdir(__dirname + '/docs/', (error, files) => { if (error) throw error; files.filter(f => f.endsWith('.html')).map((filename, i) => { fs.readFile(__dirname + '/docs/' + filename, 'utf8', (err, data) => { if (err) throw err; fs.writeFile(__dirname + '/docs/' + filename, beautify_html(data, { brace_style: 'collapse', indent_with_tabs: true, preserve_newlines: false, end_with_newline: true }), e => { if (e) throw e; if (i === files.length - 1) { console.log('HTML files beautified'); process.exit(0); } }); }); }); }); ================================================ FILE: docs/AbstractCommand.html ================================================ AbstractCommand - Documentation

AbstractCommand

AbstractCommand

A command managed by a CommandPlugin

Constructor

(abstract) new AbstractCommand()

Creates a new AbstractCommand

Members

(abstract) description :String

A description of the command

Type:
  • String

(abstract) name :String

The name of the command

Type:
  • String

Methods

(private) _sendMessage(channel, content, optionsopt) → {Promise.<Message>}

Parameters:
Name Type Attributes Description
channel Channel

The channel to create the message in

content String | Object

The content to be passed to Eris.Client#createMessage

options Object <optional>

Options for sending the message

Returns:

The sent message

Type
Promise.<Message>

awaitMessage(trigger, action, timeoutopt) → {Number}

Await a message, the trigger a function

Parameters:
Name Type Attributes Description
trigger function

A function that takes a Message and returns a Boolean

action function

A function to be executed when trigger returns true

timeout Number <optional>

Delete the await after this many milliseconds

Returns:

The unique id of the await

Type
Number

destroy() → {Promise}

Destroys/unloads the command

Returns:

Resolves with no value

Type
Promise

escapeMarkdown(text) → {String}

Escape any discord markdown present in a string

Parameters:
Name Type Description
text String

The text to escape

Returns:

The escaped text

Type
String

load(parent) → {Promise}

Loads the command

Parameters:
Name Type Description
parent AbstractCommandPlugin

The plugin managing this command

Returns:

Resolves with this

Type
Promise

sendMessage(message, content, optionsopt) → {Promise.<Message>}

See:

Send a message to discord

Parameters:
Name Type Attributes Description
message Message

The message to respond to

content String | Object

The content to be passed to Eris.Client#createMessage

options Object <optional>

Options for sending the message

Properties
Name Type Attributes Default Description
deleteTrigger Boolean <optional>
false

Delete the message that triggered the command

deleteAfter Number <optional>
0

Delete the created message after this many milliseconds

DM Boolean <optional>
false

Send in a Direct Message

file Object <optional>

The file to be sent with the message. Format as shown in the Eris docs

paginate Boolean <optional>

Split the message at 2000 character intervals. Used to send log messages that would normally fail

Returns:

The sent message, or nothing if pagination is true

Type
Promise.<Message>

userOnCooldown(userID, waitTime) → {Boolean}

Check if a user is on cooldown

Parameters:
Name Type Description
userID String

The id of the user to check for

waitTime Number

If not on cooldown, put them on cooldown for this many milliseconds

Returns:

If the user is still on cooldown

Type
Boolean

================================================ FILE: docs/AbstractCommandPlugin.html ================================================ AbstractCommandPlugin - Documentation

AbstractCommandPlugin

AbstractCommandPlugin

A set of commands

Constructor

(abstract) new AbstractCommandPlugin()

Creates a new AbstractCommandPlugin

Members

(abstract) description :String

A description of the plugin

Type:
  • String

(abstract) help :Array

An array containing, in this order: name, description, array of command names, array of command descriptions

Type:
  • Array

(abstract) name :String

The name of the plugin

Type:
  • String

Methods

destroy() → {Promise}

Destroys/unloads the plugin

Returns:

Resolves with no value

Type
Promise

(abstract) handle()

Handle a message

load(bot) → {Promise}

Loads the plugin

Parameters:
Name Type Description
bot Bot

The main client

Returns:

Resolves with this

Type
Promise

================================================ FILE: docs/AbstractEventPlugin.html ================================================ AbstractEventPlugin - Documentation

AbstractEventPlugin

AbstractEventPlugin

Handles events emitted from eris

Constructor

(abstract) new AbstractEventPlugin()

Creates a new AbstractEventPlugin

Members

(abstract) name :String

The name of the plugin

Type:
  • String

Methods

destroy() → {Promise}

Destroys/unloads the plugin

Returns:

Resolves with no value

Type
Promise

load(bot) → {Promise}

Loads the plugin

Parameters:
Name Type Description
bot Bot

The main client

Returns:

Resolves with this

Type
Promise

================================================ FILE: docs/AbstractMiddleware.html ================================================ AbstractMiddleware - Documentation

AbstractMiddleware

AbstractMiddleware

Manages external connections to and from the bot

Constructor

(abstract) new AbstractMiddleware()

Creates a new AbstractMiddleware

Members

(abstract) name :String

The name of the middleware

Type:
  • String

Methods

destroy() → {Promise}

Destroys/unloads the middleware

Returns:

Resolves with no value

Type
Promise

load(bot) → {Promise}

Loads the middleware

Parameters:
Name Type Description
bot Bot

The main client

Returns:

Resolves with this

Type
Promise

================================================ FILE: docs/Bot.html ================================================ Bot - Documentation

Bot

Bot

Manages the connection to Discord and interaction between plugins

Constructor

new Bot(options, rLoggeropt, rChatHandleropt)

See:
Properties:
Name Type Description
carbonBotsKey String

The API key for carbon bot list

discordBotsKey String

The API key for bots.discord.pw

discordBotsOrgKey String

The API key for discordbots.org

botsOnDiscordKey String

The API key for bots.ondiscord.xyz

logger function

The logging wrapper

chatHandler function

The class handling chat messages

blacklistedGuilds Array.<String>

Guilds that are banned from using the bot

blacklistedUsers Array.<String>

Users that are banned from using the bot

commandPlugins Object

The loaded command plugins

eventPlugins Object

The loaded event plugins

middleware Object

The loaded middleware

Creates a new instance of Mirai

Parameters:
Name Type Attributes Description
options Object

An object defining the configuration for Mirai

Properties
Name Type Attributes Description
token String

The token for your bot

carbonBotsKey String <optional>

An API key for carbon bot list

discordBotsKey String <optional>

An API key for bots.discord.pw

discordBotsOrgKey String <optional>

An API key for discordbots.org

botsOnDiscordKey String <optional>

An API key for bots.ondiscord.xyz

blacklistedGuilds Array.<String> <optional>

Guilds that are banned from using the bot

blacklistedUsers Array.<String> <optional>

Users that are banned from using the bot

gracefulExit Boolean <optional>

When SIGINT is received, destroy all plugins and middleware, and disconnect the bot

eris Object <optional>

The options to pass to the eris client. See the Eris docs

logger Object <optional>

The options to pass to the logger

chatHandler Object <optional>

The options to pass to the chatHandler

rLogger function <optional>

A replacement Logger. Must implement log info debug warn and error. Is passed this and options.logger

rChatHandler function <optional>

A replacement ChatHandler. Must implement run and stop. Is passed this and options.chatHandler

Extends

  • Eris.Client

Methods

findMember(query, members) → (nullable) {Member}

See:

Resolve a name or ID to a guild member

Parameters:
Name Type Description
query String

The name or ID to match

members Collection

The Collection of guild members

Returns:

The member the was found

Type
Member

findUser(query) → (nullable) {User}

See:

Resolve a name or ID to a user

Parameters:
Name Type Description
query String

The name or ID to match

Returns:

The user the was found

Type
User

(async) loadCommandPlugin(plugin) → {Promise}

See:
Example

Loading a Command Plugin

var funCommands = new FunCommandsPlugin();
mirai.loadCommandPlugin(funCommands);
Parameters:
Name Type Description
plugin function

The plugin to load. Must have a load method which is passed this

Returns:

The return value of plugin.load

Type
Promise

(async) loadEventPlugin(plugin) → {Promise}

Parameters:
Name Type Description
plugin function

The plugin to load. Must have a load method which is passed this

Returns:

The return value of plugin.load

Type
Promise

(async) loadMiddleware(middleware) → {Promise}

Parameters:
Name Type Description
middleware function

The middleware to load. Must have a load method which is passed this

Returns:

The return value of middleware.load

Type
Promise

(async) reloadCommandPlugin(plugin) → {Promise}

Reload a plugin by searching for a plugin with the same name and replacing it

Parameters:
Name Type Description
plugin function

The plugin to load. Must have a load method which is passed this

Returns:

The return value of plugin.load

Type
Promise

(async) reloadEventPlugin(plugin) → {Promise}

Reload a plugin by searching for a plugin with the same name and replacing it

Parameters:
Name Type Description
plugin function

The plugin to load. Must have a load method which is passed this

Returns:

The return value of plugin.load

Type
Promise

(async) reloadMiddleware(middleware) → {Promise}

Reload middleware by searching for middleware with the same name and replacing it

Parameters:
Name Type Description
middleware function

The middleware to load. Must have a load method which is passed this

Returns:

The return value of middleware.load

Type
Promise

(async) setAvatar(url) → {Promise}

Sets the bot's avatar from a url

Parameters:
Name Type Description
url String

A direct link to an image

Returns:

Resolves on completion

Type
Promise

(async) updateBotsOnDiscord(keyopt) → {Promise}

See:

Updates information on bots.ondiscord.xyz

Parameters:
Name Type Attributes Description
key String <optional>

bots.ondiscord.xyz API key

Returns:

The axios request result or error

Type
Promise

(async) updateCarbon(keyopt) → {Promise}

See:

Updates information on carbonitex.net

Parameters:
Name Type Attributes Description
key String <optional>

Carbon API key

Returns:

The axios request result or error

Type
Promise

(async) updateDiscordBots(keyopt) → {Promise}

See:

Updates information on bots.discord.pw

Parameters:
Name Type Attributes Description
key String <optional>

bots.discord.pw API key

Returns:

The axios request result or error

Type
Promise

(async) updateDiscordBotsOrg(keyopt) → {Promise}

See:

Updates information on discordbots.org

Parameters:
Name Type Attributes Description
key String <optional>

discordbots API key

Returns:

The axios request result or error

Type
Promise

================================================ FILE: docs/ChatHandler.html ================================================ ChatHandler - Documentation

ChatHandler

ChatHandler

Handles messages received by the client

Constructor

new ChatHandler(botopt, optionsopt)

Properties:
Name Type Description
bot Bot

The bot

awaits Object

The active awaits

Creates a new ChatHandler

Parameters:
Name Type Attributes Description
bot Bot <optional>

The main client

options Object <optional>

The configuration to use

Properties
Name Type Attributes Default Description
allowSelf Boolean <optional>
false

Allow messages from the bot to be handled

allowBots Boolean <optional>
false

Allow messages from bots to be handled

defaultHelpCommand Object <optional>

Enable the default help command

Properties
Name Type Attributes Default Description
prefix String <optional>
"!"

The prefix to use for the help command

before String <optional>

The text to put as a header

after String <optional>

The text to put as a footer

title String <optional>

The text to put as a title (bolded)

style String <optional>
"extended"

One of the following: basic, extended, embed

Methods

awaitMessage(trigger, action, timeoutopt) → {Number}

Add an await, which will trigger under certain conditions

Parameters:
Name Type Attributes Description
trigger function

A function that takes a Message and returns a Boolean

action function

A function to be executed when trigger returns true

timeout Number <optional>

Delete the await after this many milliseconds

Returns:

The unique id of the await

Type
Number

getHelp(message) → {Promise}

Generate and send a help message

Parameters:
Name Type Description
message Message

The message to respond to

Returns:

The sent message

Type
Promise

run()

Starts listening for messages

stop()

Stops listening for messages


================================================ FILE: docs/Logger.html ================================================ Logger - Documentation

Logger

Logger

Displays text to the console. Also supports sentry

Constructor

new Logger(optionsopt)

Properties:
Name Type Description
raven RavenClient

The Raven client used for sentry, if enabled.

Creates a new Logger

Parameters:
Name Type Attributes Description
options Object <optional>

The configuration for the logger

Properties
Name Type Attributes Default Description
timestamps Boolean <optional>
false

Add a timestamp to each message logged

levels Object <optional>

An object deciding what log levels should display

Properties
Name Type Attributes Default Description
log Boolean <optional>
true

Show log()

info Boolean <optional>
true

Show info()

debug Boolean <optional>
false

Show debug()

warning Boolean <optional>
true

Show warn()

error Boolean <optional>
true

Show error()

raven Object <optional>

Raven options. If falsy, raven will not be required.

Properties
Name Type Attributes Default Description
url String

Your project's sentry.io url

config Object <optional>

A custom raven config. For more info check their docs

info Boolean <optional>
false

Send info() messages to sentry

debug Boolean <optional>
false

Send debug() messages to sentry

warning Boolean <optional>
false

Send warn() messages to sentry. If an Error is passed in the arguments, that will be sent alone.

error Boolean <optional>
true

Send error() errors to sentry. If an Error is passed in the arguments, that will be sent alone.

Members

timestamp :String

A formatted timestamp

Type:
  • String

Methods

debug()

Log debugging information

error()

Log an error

info()

Log informal text

log()

Log generic text

warn()

Log a warning


================================================ FILE: docs/index.html ================================================ Home - Documentation

Mirai Bot Core

Discord server David GitHub license Code Climate npm

A powerful Discord bot core using Eris.

Documentation | Eris Docs | Mirai Bot Website | Support me on Patreon | Discord Server | Mirai Bot Combined Todo List

mirai-bot-core supports advanced application monitoring with sentry.io using raven. For more information head over to the docs.

Installing

yarn add mirai-bot-core
const Mirai = require('mirai-bot-core');
const bot = new Mirai(config);

Abstract Classes

Abstract classes are provided to ensure you have the required methods. They can be accessed like so:

const AbstractCommand = require('mirai-bot-core/lib/Base/AbstractCommand');

class PingCommand extends AbstractCommand {
    constructor() {
        super();
    }
}

================================================ FILE: docs/scripts/linenumber.js ================================================ /*global document */ (function() { var source = document.getElementsByClassName('prettyprint source linenums'); var i = 0; var lineNumber = 0; var lineId; var lines; var totalLines; var anchorHash; if (source && source[0]) { anchorHash = document.location.hash.substring(1); lines = source[0].getElementsByTagName('li'); totalLines = lines.length; for (; i < totalLines; i++) { lineNumber++; lineId = 'line' + lineNumber; lines[i].id = lineId; if (lineId === anchorHash) { lines[i].className += ' selected'; } } } })(); ================================================ FILE: docs/scripts/prettify/Apache-License-2.0.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: docs/scripts/prettify/lang-css.js ================================================ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n "]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com", /^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); ================================================ FILE: docs/scripts/prettify/prettify.js ================================================ var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p ul { padding: 0 10px; } nav > ul > li > a { color: #ec4963; } nav ul ul { margin-bottom: 10px } nav ul ul + ul { margin-top: -10px; } nav ul ul a { color: hsl(207, 1%, 60%); border-left: 1px solid hsl(207, 10%, 86%); } nav ul ul a, nav ul ul a:active { padding-left: 20px } nav h2 { font-size: 12px; margin: 0; padding: 0; } nav > h2 > a { display: block; margin: 10px 0 -10px; color: #ec4963 !important; } footer { color: hsl(0, 0%, 28%); margin-left: 250px; display: block; padding: 15px; font-style: italic; font-size: 90%; } .ancestors { color: #999 } .ancestors a { color: #999 !important; } .clear { clear: both } .important { font-weight: bold; color: #950B02; } .yes-def { text-indent: -1000px } .type-signature { color: #c8d2ff } .type-signature:last-child { color: #eee; } .name, .signature { font-family: Consolas, Monaco, 'Andale Mono', monospace } .signature { color: #adbcff; } .details { margin-top: 6px; border-left: 2px solid #DDD; line-height: 20px; font-size: 14px; } .details dt { width: 120px; float: left; padding-left: 10px; } .details dd { margin-left: 70px; margin-top: 6px; margin-bottom: 6px; } .details ul { margin: 0 } .details ul { list-style-type: none } .details pre.prettyprint { margin: 0 } .details .object-value { padding-top: 0 } .description { margin-bottom: 1em; margin-top: 1em; } .code-caption { font-style: italic; font-size: 107%; margin: 0; } .prettyprint { font-size: 14px; overflow: auto; } .prettyprint.source { width: inherit; line-height: 18px; display: block; background-color: #2d2d2d; color: #aeaeae; } .prettyprint code { line-height: 18px; display: block; background-color: #2d2d2d; color: #4D4E53; } .prettyprint > code { padding: 15px; } .prettyprint .linenums code { padding: 0 15px } .prettyprint .linenums li:first-of-type code { padding-top: 15px } .prettyprint code span.line { display: inline-block } .prettyprint.linenums { padding-left: 70px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .prettyprint.linenums ol { padding-left: 0 } .prettyprint.linenums li { border-left: 3px #34446B solid; } .prettyprint.linenums li.selected, .prettyprint.linenums li.selected * { background-color: #34446B; } .prettyprint.linenums li * { -webkit-user-select: text; -moz-user-select: text; -ms-user-select: text; user-select: text; } .params, .props { border-spacing: 0; border: 1px solid #ddd; border-collapse: collapse; border-radius: 3px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); width: 100%; font-size: 14px; margin: 1em 0; } .params .type { white-space: nowrap; } .params code { white-space: pre; } .params td, .params .name, .props .name, .name code { color: #4D4E53; font-family: Consolas, Monaco, 'Andale Mono', monospace; font-size: 100%; } .params td, .params th, .props td, .props th { margin: 0px; text-align: left; vertical-align: top; padding: 10px; display: table-cell; } .params td { border-top: 1px solid #eee } .params thead tr, .props thead tr { background-color: #fff; font-weight: bold; } .params .params thead tr, .props .props thead tr { background-color: #fff; font-weight: bold; } .params td.description > p:first-child, .props td.description > p:first-child { margin-top: 0; padding-top: 0; } .params td.description > p:last-child, .props td.description > p:last-child { margin-bottom: 0; padding-bottom: 0; } span.param-type, .params td .param-type, .param-type dd { color: #475ab3; font-family: Consolas, Monaco, 'Andale Mono', monospace } .param-type dt, .param-type dd { display: inline-block } .param-type { margin: 14px 0; } .disabled { color: #454545 } /* navicon button */ .navicon-button { display: none; position: relative; padding: 2.0625rem 1.5rem; transition: 0.25s; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; opacity: .8; } .navicon-button .navicon:before, .navicon-button .navicon:after { transition: 0.25s; } .navicon-button:hover { transition: 0.5s; opacity: 1; } .navicon-button:hover .navicon:before, .navicon-button:hover .navicon:after { transition: 0.25s; } .navicon-button:hover .navicon:before { top: .825rem; } .navicon-button:hover .navicon:after { top: -.825rem; } /* navicon */ .navicon { position: relative; width: 2.5em; height: .3125rem; background: #000; transition: 0.3s; border-radius: 2.5rem; } .navicon:before, .navicon:after { display: block; content: ""; height: .3125rem; width: 2.5rem; background: #000; position: absolute; z-index: -1; transition: 0.3s 0.25s; border-radius: 1rem; } .navicon:before { top: .625rem; } .navicon:after { top: -.625rem; } /* open */ .nav-trigger:checked + label:not(.steps) .navicon:before, .nav-trigger:checked + label:not(.steps) .navicon:after { top: 0 !important; } .nav-trigger:checked + label .navicon:before, .nav-trigger:checked + label .navicon:after { transition: 0.5s; } /* Minus */ .nav-trigger:checked + label { -webkit-transform: scale(0.75); transform: scale(0.75); } /* × and + */ .nav-trigger:checked + label.plus .navicon, .nav-trigger:checked + label.x .navicon { background: transparent; } .nav-trigger:checked + label.plus .navicon:before, .nav-trigger:checked + label.x .navicon:before { -webkit-transform: rotate(-45deg); transform: rotate(-45deg); background: #FFF; } .nav-trigger:checked + label.plus .navicon:after, .nav-trigger:checked + label.x .navicon:after { -webkit-transform: rotate(45deg); transform: rotate(45deg); background: #FFF; } .nav-trigger:checked + label.plus { -webkit-transform: scale(0.75) rotate(45deg); transform: scale(0.75) rotate(45deg); } .nav-trigger:checked ~ nav { left: 0 !important; } .nav-trigger:checked ~ .overlay { display: block; } .nav-trigger { position: fixed; top: 0; clip: rect(0, 0, 0, 0); } .overlay { display: none; position: fixed; top: 0; bottom: 0; left: 0; right: 0; width: 100%; height: 100%; background: hsla(0, 0%, 0%, 0.5); z-index: 1; } @media only screen and (min-width: 320px) and (max-width: 680px) { body { overflow-x: hidden; } nav { background: #FFF; width: 250px; height: 100%; position: fixed; top: 0; right: 0; bottom: 0; left: -250px; z-index: 3; padding: 0 10px; transition: left 0.2s; } .navicon-button { display: inline-block; position: fixed; top: 1.5em; right: 0; z-index: 2; } #main { width: 100%; min-width: 360px; } #main h1.page-title { margin: 1em 0; } #main section { padding: 0; } footer { margin-left: 0; } } /** Add a '#' to static members */ [data-type="member"] a::before { content: '#'; display: inline-block; margin-left: -14px; margin-right: 5px; } ================================================ FILE: docs/styles/prettify.css ================================================ /*! Color themes for Google Code Prettify | MIT License | github.com/jmblog/color-themes-for-google-code-prettify */ .prettyprint { background: #2d2d2d; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; border: 0 !important; } .pln { color: #cccccc; } /* Specify class=linenums on a pre to get line numbering */ ol.linenums { margin-top: 0; margin-bottom: 0; color: #999999; } li.L0, li.L1, li.L2, li.L3, li.L4, li.L5, li.L6, li.L7, li.L8, li.L9 { padding-left: 1em; background-color: #2d2d2d; list-style-type: decimal; } @media screen { /* string content */ .str { color: #99cc99; } /* keyword */ .kwd { color: #cc99cc; } /* comment */ .com { color: #999999; } /* type name */ .typ { color: #6699cc; } /* literal value */ .lit { color: #f99157; } /* punctuation */ .pun { color: #cccccc; } /* lisp open bracket */ .opn { color: #cccccc; } /* lisp close bracket */ .clo { color: #cccccc; } /* markup tag name */ .tag { color: #f2777a; } /* markup attribute name */ .atn { color: #f99157; } /* markup attribute value */ .atv { color: #66cccc; } /* declaration */ .dec { color: #f99157; } /* variable name */ .var { color: #f2777a; } /* function name */ .fun { color: #6699cc; } } ================================================ FILE: examples/mongoose/MongoMiddle.js ================================================ /* eslint-disable require-jsdoc */ // Middleware example // Allows plugins to access a Mongo database // Includes caching with options.mUseCache to reduce delay const Mongoose = require('mongoose'); const Schema = Mongoose.Schema; var exampleSchema = new Schema({ id: String, uses: { type: Number } }, { collection: 'guildSettings' }); class MongoDBMiddleware { constructor(options = { URI: 'mongodb://admin:pass@localhost:27017/example' }) { this.URI = options.URI; this.models = { examples: Mongoose.model('examples', exampleSchema) }; this.cache = { examples: { } }; } get name() { return 'MongoDatabase'; } load(bot) { return new Promise(resolve => { this.bot = bot; Mongoose.Promise = global.Promise; Mongoose.connect(this.URI, { useNewUrlParser: true }); Mongoose.connection.on('error', this.bot.logger.error.bind(this.bot.logger, 'Mongoose error:')); Mongoose.connection.once('open', () => this.bot.logger.info('Mongoose Connected')); Mongoose.set('useCreateIndex', true); return resolve(this); }); } destroy() { return new Promise(resolve => { this.bot = undefined; Mongoose.disconnect(); Mongoose.connection.removeAllListeners('error'); Mongoose.connection.removeAllListeners('open'); return resolve(); }); } invalidate(collection, id) { if (this.cache.hasOwnProperty(collection) && this.cache[collection].hasOwnProperty(id)) delete this.cache[collection][id]; } findOne(collection, conditions, projection, options = {}) { if (options.mUseCache === true && options.lean === true && !projection) { if (this.cache[collection].hasOwnProperty(conditions.id)) return Promise.resolve(this.cache[collection][conditions.id]); return this.models[collection].findOne(conditions, projection, options).then(resp => { this.cache[collection][conditions.id] = resp; return resp; }); } return this.models[collection].findOne(conditions, projection, options); } update(collection, conditions, doc, options) { if (conditions.hasOwnProperty('id')) this.invalidate(collection, conditions.id); return this.models[collection].updateOne(conditions, doc, options); } remove(collection, conditions) { if (conditions.hasOwnProperty('id')) this.invalidate(collection, conditions.id); return this.models[collection].deleteOne(conditions); } } module.exports = MongoDBMiddleware; ================================================ FILE: examples/mongoose/index.js ================================================ /* eslint-disable require-jsdoc */ global.Promise = require("bluebird"); const Mirai = require('mirai-bot-core'); const mirai = new Mirai({ /* config here */ }); const MongoDB = require('./MongoMiddle'); const AbstractCommandPlugin = require('mirai-bot-core/lib/Base/AbstractCommandPlugin'); mirai.connect() .then(() => mirai.loadMiddleware(MongoDB)) .then(() => mirai.loadCommandPlugin(MongoTest)) .catch(e => mirai.logger.error('Error during setup:', e)); class MongoTest extends AbstractCommandPlugin { constructor() { super(); this.prefix = 'mt '; } get name() { return 'mongo test'; } get description() { return 'mongo test commands'; } get database() { if (!this._databaseIndex) this._databaseIndex = this.bot.middleware.findIndex(m => m.name === 'MongoDatabase'); return this.bot.middleware[this._databaseIndex]; } load(bot) { super.load(bot); return Promise.resolve(this); } destroy() { super.destroy(); return Promise.resolve(); } handle(message) { if (message.content === this.prefix + 'find') this.database.findOne('examples', { id: message.author.id }, null, { mUseCache: true, lean: true }).then(doc => { console.log(doc); }); else if (message.content === this.prefix + 'create') this.database.models.examples.create({ id: message.author.id, uses: 0 }).then(() => { console.log('Created document'); }); else if (message.content === this.prefix + 'update') this.database.update('examples', { id: message.author.id }, { $inc: { uses: 1 } }).then(() => { console.log('Increased uses by 1'); }); } } ================================================ FILE: index.js ================================================ module.exports = require('./lib/Bot.js'); ================================================ FILE: lib/Base/AbstractCommand.js ================================================ /** * A command managed by a CommandPlugin * @abstract */ class AbstractCommand { /** * Creates a new AbstractCommand * @abstract */ constructor() { if (this.constructor === AbstractCommand) throw new Error("Can't instantiate an abstract class!"); } /** * The name of the command * @type {String} * @abstract */ get name() { throw new Error('name must be overwritten'); } /** * A description of the command * @type {String} * @abstract */ get description() { return ''; } /** * Loads the command * @param {AbstractCommandPlugin} parent The plugin managing this command * @returns {Promise} Resolves with `this` */ load(parent) { this.parent = parent; return Promise.resolve(this); } /** * Destroys/unloads the command * @returns {Promise} Resolves with no value */ destroy() { this.parent = undefined; return Promise.resolve(); } /** * Send a message to discord * @param {Message} message The message to respond to * @param {String|Object} content The content to be passed to Eris.Client#createMessage * @param {Object} [options] Options for sending the message * @param {Boolean} [options.deleteTrigger=false] Delete the message that triggered the command * @param {Number} [options.deleteAfter=0] Delete the created message after this many milliseconds * @param {Boolean} [options.DM=false] Send in a Direct Message * @param {Object} [options.file] The file to be sent with the message. Format as shown in the Eris docs * @param {Boolean} [options.paginate] Split the message at 2000 character intervals. Used to send log messages that would normally fail * @returns {Promise} The sent message, or nothing if pagination is true * @see {@link http://eris.tachibana.erendale.abal.moe/Eris/docs/Client#function-createMessage|Eris.Client#createMessage} */ sendMessage(message, content, options) { if (!message || (!content && !options)) return Promise.resolve(); options = options || { }; if (options.deleteTrigger && message.channel.guild && message.channel.permissionsOf(this.parent.bot.user.id).has('manageMessages')) message.delete().catch(error => this.parent.logger.warn('Error deleting trigger:', error)); if (typeof content !== 'object') content = { content }; if (content.embed && !message.channel.permissionsOf(this.parent.bot.user.id).has('embedLinks')) return Promise.resolve(this._sendMessage(message.channel, 'Unable to send message. I need the Embed Links permission', { })); if (options.file && !message.channel.permissionsOf(this.parent.bot.user.id).has('attachFiles')) return Promise.resolve(this._sendMessage(message.channel, 'Unable to send message. I need the Attach Files permission', { })); return (options.DM ? message.author.getDMChannel() : Promise.resolve(message.channel)).then(channel => { if (!options.paginate) return this._sendMessage(channel, content, options); let i = 0; while (i < content.content.length) { let _content = JSON.parse(JSON.stringify(content)); // Clone _content.content = content.content.slice(i, i + 2000); this._sendMessage(channel, _content, options); i += 2000; options.file = undefined; } return Promise.resolve(); }).catch(error => this.parent.logger.warn('Error getting DM channel:', error)); } /** * @private * @param {Channel} channel The channel to create the message in * @param {String|Object} content The content to be passed to Eris.Client#createMessage * @param {Object} [options] Options for sending the message * @returns {Promise} The sent message */ _sendMessage(channel, content, options) { return channel.createMessage(content, options.file).then(message => { if (options.deleteAfter > 0) setTimeout(() => { message.delete().catch(error => this.parent.logger.warn('Error deleting message (deleteAfter): ', error)); }, options.deleteAfter); return message; }).catch(error => this.parent.logger.warn('Error creating message:', error)); } /** * Await a message, the trigger a function * @param {Function} trigger A function that takes a Message and returns a Boolean * @param {Function} action A function to be executed when `trigger` returns true * @param {Number} [timeout] Delete the await after this many milliseconds * @returns {Number} The unique id of the await */ awaitMessage(trigger, action, timeout) { return this.parent.bot.chatHandler.awaitMessage(trigger, action, timeout); } /** * Escape any discord markdown present in a string * @param {String} text The text to escape * @returns {String} The escaped text */ escapeMarkdown(text) { return text.replace(/([`*_~])/g, '\\$1'); } /** * Check if a user is on cooldown * @param {String} userID The id of the user to check for * @param {Number} waitTime If not on cooldown, put them on cooldown for this many milliseconds * @returns {Boolean} If the user is still on cooldown */ userOnCooldown(userID, waitTime) { if (!this.cooldownUsers) this.cooldownUsers = new Set(); if (this.cooldownUsers.has(userID)) return true; this.cooldownUsers.add(userID); setTimeout(() => this.cooldownUsers.delete(userID), waitTime); return false; } } module.exports = AbstractCommand; ================================================ FILE: lib/Base/AbstractCommandPlugin.js ================================================ /** * A set of commands * @abstract */ class AbstractCommandPlugin { /** * Creates a new AbstractCommandPlugin * @abstract */ constructor() { if (this.constructor === AbstractCommandPlugin) throw new Error("Can't instantiate an abstract class!"); this.commands = {}; } /** * An array containing, in this order: name, description, array of command names, array of command descriptions * @type {Array} * @abstract */ get help() { return [this.name, this.description, Object.keys(this.commands), Object.keys(this.commands).map(cmd => this.commands[cmd].description)]; } /** * The name of the plugin * @type {String} * @abstract */ get name() { throw new Error('name must be overwritten'); } /** * A description of the plugin * @type {String} * @abstract */ get description() { return ''; } /** * Loads the plugin * @param {Bot} bot The main client * @returns {Promise} Resolves with `this` */ load(bot) { this.logger = bot.logger; this.bot = bot; return Promise.resolve(this); } /** * Destroys/unloads the plugin * @returns {Promise} Resolves with no value */ destroy() { this.logger = undefined; this.bot = undefined; return Promise.resolve(); } /** * Handle a message * @type {String} * @abstract */ handle() { throw new Error('handle must be overwritten'); } } module.exports = AbstractCommandPlugin; ================================================ FILE: lib/Base/AbstractEventPlugin.js ================================================ /** * Handles events emitted from eris * @abstract */ class AbstractEventPlugin { /** * Creates a new AbstractEventPlugin * @abstract */ constructor() { if (this.constructor === AbstractEventPlugin) throw new Error("Can't instantiate an abstract class!"); } /** * The name of the plugin * @type {String} * @abstract */ get name() { throw new Error('name must be overwritten'); } /** * Loads the plugin * @param {Bot} bot The main client * @returns {Promise} Resolves with `this` */ load(bot) { this.logger = bot.logger; this.bot = bot; return Promise.resolve(this); } /** * Destroys/unloads the plugin * @returns {Promise} Resolves with no value */ destroy() { this.logger = undefined; this.bot = undefined; return Promise.resolve(); } } module.exports = AbstractEventPlugin; ================================================ FILE: lib/Base/AbstractMiddleware.js ================================================ /** * Manages external connections to and from the bot * @abstract */ class AbstractMiddleware { /** * Creates a new AbstractMiddleware * @abstract */ constructor() { if (this.constructor === AbstractMiddleware) throw new Error("Can't instantiate an abstract class!"); } /** * The name of the middleware * @type {String} * @abstract */ get name() { throw new Error('name must be overwritten'); } /** * Loads the middleware * @param {Bot} bot The main client * @returns {Promise} Resolves with `this` */ load(bot) { this.logger = bot.logger; this.bot = bot; return Promise.resolve(this); } /** * Destroys/unloads the middleware * @returns {Promise} Resolves with no value */ destroy() { this.logger = undefined; this.bot = undefined; return Promise.resolve(); } } module.exports = AbstractMiddleware; ================================================ FILE: lib/Bot.js ================================================ const Logger = require('./Logger.js'); const ChatHandler = require('./ChatHandler.js'); const Eris = require('eris'); const axios = require('axios'); let Promise; try { Promise = require("bluebird"); } catch(err) { Promise = global.Promise; } /** * Manages the connection to Discord and interaction between plugins * @extends Eris.Client * @prop {String} carbonBotsKey The API key for carbon bot list * @prop {String} discordBotsKey The API key for bots.discord.pw * @prop {String} discordBotsOrgKey The API key for discordbots.org * @prop {String} botsOnDiscordKey The API key for bots.ondiscord.xyz * @prop {Function} logger The logging wrapper * @prop {Function} chatHandler The class handling chat messages * @prop {Array} blacklistedGuilds Guilds that are banned from using the bot * @prop {Array} blacklistedUsers Users that are banned from using the bot * @prop {Object} commandPlugins The loaded command plugins * @prop {Object} eventPlugins The loaded event plugins * @prop {Object} middleware The loaded middleware * @see {@link https://abal.moe/Eris/docs/Client|Eris.Client} */ class Bot extends Eris.Client { /** * Creates a new instance of Mirai * @param {Object} options An object defining the configuration for Mirai * @param {String} options.token The token for your bot * @param {String} [options.carbonBotsKey] An API key for carbon bot list * @param {String} [options.discordBotsKey] An API key for bots.discord.pw * @param {String} [options.discordBotsOrgKey] An API key for discordbots.org * @param {String} [options.botsOnDiscordKey] An API key for bots.ondiscord.xyz * @param {Array} [options.blacklistedGuilds] Guilds that are banned from using the bot * @param {Array} [options.blacklistedUsers] Users that are banned from using the bot * @param {Boolean} [options.gracefulExit] When SIGINT is received, destroy all plugins and middleware, and disconnect the bot * @param {Object} [options.eris] The options to pass to the eris client. See {@link https://abal.moe/Eris/docs/Client|the Eris docs} * @param {Object} [options.logger] The options to pass to the logger * @param {Object} [options.chatHandler] The options to pass to the chatHandler * @param {Function} [rLogger] A replacement Logger. Must implement `log` `info` `debug` `warn` and `error`. Is passed `this` and `options.logger` * @param {Function} [rChatHandler] A replacement ChatHandler. Must implement `run` and `stop`. Is passed `this` and `options.chatHandler` * @example Create a new instance of Mirai * const Mirai = require('mirai-bot-core'); * var config = require('./config.json'); * var mirai = new Mirai(config); */ constructor(options = { }, rLogger, rChatHandler) { super(options.token, options.eris); this.carbonBotsKey = options.carbonBotsKey; this.discordBotsKey = options.discordBotsKey; this.discordBotsOrgKey = options.discordBotsOrgKey; this.botsOnDiscordKey = options.botsOnDiscordKey; this.logger = rLogger ? new rLogger(this, options.logger) : new Logger(options.logger); this.chatHandler = rChatHandler ? new rChatHandler(this, options.chatHandler) : new ChatHandler(this, options.chatHandler); this.blacklistedGuilds = options.blacklistedGuilds || []; this.blacklistedUsers = options.blacklistedUsers || []; this.commandPlugins = { }; this.eventPlugins = { }; this.middleware = { }; this.once('ready', () => { this.chatHandler.run(); return this.logger.info('Mirai: Connected to Discord'); }); this.on('error', (error, shard) => error && this.logger.error(`Mirai: ${shard !== undefined ? `Shard ${shard} error` : 'Error'}:`, error)); this.on('disconnected', () => this.logger.warn('Mirai: Disconnected from Discord')); this.on('shardReady', shard => this.logger.info(`Mirai: Shard ${shard} ready`)); this.on('shardDisconnect', (error, shard) => error && this.logger.warn(`Mirai: Shard ${shard} disconnected with error:`, error.message)); this.on('shardResume', shard => this.logger.info(`Mirai: Shard ${shard} resumed`)); if (this.blacklistedGuilds.length !== 0) { this.on('guildCreate', async guild => { if (this.blacklistedGuilds.includes(guild.id)) { await guild.leave(); return this.logger.info('Mirai: Left blacklisted guild', guild.name); } }); } if (options.gracefulExit === true) { process.on('SIGINT', () => { this.logger.info('SIGINT detected, shutting down'); const destroyAll = Object.values(this.commandPlugins).map(p => p.destroy()) .concat(Object.values(this.eventPlugins).map(p => p.destroy()), Object.values(this.middleware).map(m => m.destroy())); this.disconnect({ reconnect: false }); Promise.all(destroyAll).then(() => process.exit(0)).catch(error => { this.logger.error(error); process.exit(1); }); }); } } /** * @param {Function} plugin The plugin to load. Must have a `load` method which is passed `this` * @see {@link AbstractCommandPlugin} * @example Loading a Command Plugin * var funCommands = new FunCommandsPlugin(); * mirai.loadCommandPlugin(funCommands); * @returns {Promise} The return value of `plugin.load` * @async */ async loadCommandPlugin(plugin) { if (!plugin.name || !!this.commandPlugins[plugin.name]) throw new Error('Plugin must have a unique name'); const result = await plugin.load(this); this.commandPlugins[plugin.name] = plugin; return result; } /** * Reload a plugin by searching for a plugin with the same name and replacing it * @param {Function} plugin The plugin to load. Must have a `load` method which is passed `this` * @returns {Promise} The return value of `plugin.load` * @async */ async reloadCommandPlugin(plugin) { if (!plugin.name) throw new Error('Plugin must have a name'); if (!this.commandPlugins[plugin.name]) throw new Error(`No command plugin with name ${plugin.name} is loaded`); await this.commandPlugins[plugin.name].destroy(); const result = await plugin.load(this); this.commandPlugins[plugin.name] = plugin; return result; } /** * @param {Function} plugin The plugin to load. Must have a `load` method which is passed `this` * @returns {Promise} The return value of `plugin.load` * @async */ async loadEventPlugin(plugin) { if (!plugin.name || !!this.eventPlugins[plugin.name]) throw new Error('Plugin must have a unique name'); const result = await plugin.load(this); this.eventPlugins[plugin.name] = plugin; return result; } /** * Reload a plugin by searching for a plugin with the same name and replacing it * @param {Function} plugin The plugin to load. Must have a `load` method which is passed `this` * @returns {Promise} The return value of `plugin.load` * @async */ async reloadEventPlugin(plugin) { if (!plugin.name) throw new Error('Plugin must have a name'); if (!this.eventPlugins[plugin.name]) throw new Error(`No event plugin with name ${plugin.name} is loaded`); await this.eventPlugins[plugin.name].destroy(); const result = await plugin.load(this); this.eventPlugins[plugin.name] = plugin; return result; } /** * @param {Function} middleware The middleware to load. Must have a `load` method which is passed `this` * @returns {Promise} The return value of `middleware.load` * @async */ async loadMiddleware(middleware) { if (!middleware.name || !!this.middleware[middleware.name]) throw new Error('Middleware must have a unique name'); const result = await middleware.load(this); this.middleware[middleware.name] = middleware; return result; } /** * Reload middleware by searching for middleware with the same name and replacing it * @param {Function} middleware The middleware to load. Must have a `load` method which is passed `this` * @returns {Promise} The return value of `middleware.load` * @async */ async reloadMiddleware(middleware) { if (!middleware.name) throw new Error('Middleware must have a name'); if (!this.middleware[middleware.name]) throw new Error(`No middleware with name ${middleware.name} is loaded`); await this.middleware[middleware.name].destroy(); const result = await middleware.load(this); this.middleware[middleware.name] = middleware; return result; } /** * Updates information on carbonitex.net * @param {String} [key] Carbon API key * @returns {Promise} The axios request result or error * @see {@link https://github.com/mzabriskie/axios/blob/master/README.md#response-schema|Axios response} * @async */ async updateCarbon(key) { try { const response = await axios.post('https://www.carbonitex.net/discord/data/botdata.php', { key: key || this.carbonBotsKey, servercount: this.guilds.size }); this.logger.debug(`Updated carbonitex.net guild count to ${this.guilds.size}. Response: ${response.status}`); return response; } catch (error) { if (error.response) this.logger.warn(`Response status ${error.response.status} from carbonitex.net. Data: ${error.response.data}`); else this.logger.error('Error during axios request:', error.stack); return error; } } /** * Updates information on bots.discord.pw * @param {String} [key] bots.discord.pw API key * @returns {Promise} The axios request result or error * @see {@link https://github.com/mzabriskie/axios/blob/master/README.md#response-schema|Axios response} * @async */ async updateDiscordBots(key) { try { const response = await axios.post(`https://bots.discord.pw/api/bots/${this.user.id}/stats`, { server_count: this.guilds.size }, { headers: { 'Authorization': key || this.discordBotsKey } }); this.logger.debug(`Updated bots.discord.pw guild count to ${this.guilds.size}. Response: ${response.status}`); return response; } catch (error) { if (error.response) this.logger.warn(`Response status ${error.response.status} from bots.discord.pw. Data: ${error.response.data}`); else this.logger.error('Error during axios request:', error.stack); return error; } } /** * Updates information on discordbots.org * @param {String} [key] discordbots API key * @returns {Promise} The axios request result or error * @see {@link https://github.com/mzabriskie/axios/blob/master/README.md#response-schema|Axios response} * @async */ async updateDiscordBotsOrg(key) { try { const response = await axios.post(`https://discordbots.org/api/bots/${this.user.id}/stats`, { server_count: this.guilds.size }, { headers: { 'Authorization': key || this.discordBotsOrgKey } }); this.logger.debug(`Updated discordbots.org guild count to ${this.guilds.size}. Response: ${response.status}`); return response; } catch (error) { if (error.response) this.logger.warn(`Response status ${error.response.status} from discordbots.org. Data: ${error.response.data}`); else this.logger.error('Error during axios request:', error.stack); return error; } } /** * Updates information on bots.ondiscord.xyz * @param {String} [key] bots.ondiscord.xyz API key * @returns {Promise} The axios request result or error * @see {@link https://github.com/mzabriskie/axios/blob/master/README.md#response-schema|Axios response} * @async */ async updateBotsOnDiscord(key) { try { const response = await axios.post(`https://bots.ondiscord.xyz/bot-api/bots/${this.user.id}/guilds`, { guildCount: this.guilds.size }, { headers: { 'Authorization': key || this.botsOnDiscordKey } }); this.logger.debug(`Updated bots.ondiscord.xyz guild count to ${this.guilds.size}. Response: ${response.status}`); return response; } catch (error) { if (error.response) this.logger.warn(`Response status ${error.response.status} from bots.ondiscord.xyz. Data: ${error.response.data}`); else this.logger.error('Error during axios request:', error.stack); return error; } } /** * Sets the bot's avatar from a url * @param {String} url A direct link to an image * @returns {Promise} Resolves on completion * @async */ async setAvatar(url) { try { const response = await axios.get(url, { headers: { 'Accept': 'image/*' }, responseType: 'arraybuffer' }); await this.editSelf({avatar: `data:${response.headers['content-type']};base64,${response.data.toString('base64')}`}); return this.logger.debug('Updated avatar from ' + url); } catch (error) { if (error.response) this.logger.warn('Failed to fetch avatar:', error.response.data || error.response.status); else this.logger.warn('Failed to update avatar from ' + url, error); throw error; } } /** * Resolve a name or ID to a user * @param {String} query The name or ID to match * @returns {User?} The user the was found * @see {@link https://abal.moe/Eris/docs/User|Eris.User} */ findUser(query) { query = query.toLowerCase().trim(); if (/^[0-9]{16,19}$/.test(query)) { // If query looks like an ID try to get by ID const user = this.users.get(query); if (user) return user; } let result = this.users.find(user => user.username.toLowerCase() === query); if (!result) result = this.users.find(user => user.username.toLowerCase().includes(query)); return result || null; } /** * Resolve a name or ID to a guild member * @param {String} query The name or ID to match * @param {Collection} members The Collection of guild members * @returns {Member?} The member the was found * @see {@link https://abal.moe/Eris/docs/Member|Eris.Member} */ findMember(query, members) { query = query.toLowerCase().trim(); if (/^[0-9]{16,19}$/.test(query)) { // If query looks like an ID try to get by ID const member = members.get(query); if (member) return member; } let result = members.find(member => member.user.username.toLowerCase() === query); if (!result) result = members.find(member => member.nick && member.nick.toLowerCase() === query); if (!result) result = members.find(member => member.user.username.toLowerCase().includes(query)); if (!result) result = members.find(member => member.nick && member.nick.toLowerCase().includes(query)); return result || null; } } module.exports = Bot; ================================================ FILE: lib/ChatHandler.js ================================================ /** * Handles messages received by the client * @prop {Bot} bot The bot * @prop {Object} awaits The active awaits */ class ChatHandler { /** * Creates a new ChatHandler * @param {Bot} [bot] The main client * @param {Object} [options] The configuration to use * @param {Boolean} [options.allowSelf=false] Allow messages from the bot to be handled * @param {Boolean} [options.allowBots=false] Allow messages from bots to be handled * @param {Object} [options.defaultHelpCommand] Enable the default help command * @param {String} [options.defaultHelpCommand.prefix="!"] The prefix to use for the help command * @param {String} [options.defaultHelpCommand.before] The text to put as a header * @param {String} [options.defaultHelpCommand.after] The text to put as a footer * @param {String} [options.defaultHelpCommand.title] The text to put as a title (bolded) * @param {String} [options.defaultHelpCommand.style="extended"] One of the following: basic, extended, embed */ constructor(bot, options = { }) { this.bot = bot; this.allowSelf = !!options.allowSelf; this.allowBots = !!options.allowBots; this.awaits = { }; this._nextAwaitId = 0; this.defaultHelpCommand = options.defaultHelpCommand !== undefined; if (this.defaultHelpCommand === true) { this.help = { prefix: options.defaultHelpCommand.prefix || '!', before: options.defaultHelpCommand.before, after: options.defaultHelpCommand.after, title: options.defaultHelpCommand.title, style: options.defaultHelpCommand.style }; } this.messageHandler = message => { if ((message.author.id === this.bot.user.id && this.allowSelf === false) || (message.author.bot && this.allowBots === false) || (message.channel.guild && this.bot.blacklistedGuilds.includes(message.channel.guild.id)) || this.bot.blacklistedUsers.includes(message.author.id)) return; if (this.defaultHelpCommand && message.content === this.help.prefix + 'help') this.getHelp(message); Object.values(this.bot.commandPlugins).forEach(plugin => plugin.handle(message)); for (let id in this.awaits) { if (this.awaits[id].trigger(message)) { this.awaits[id].action(message); delete this.awaits[id]; } } }; } /** Starts listening for messages */ run() { this.bot.on('messageCreate', this.messageHandler); } /** Stops listening for messages */ stop() { this.bot.removeListener('messageCreate', this.messageHandler); } /** * Generate and send a help message * @param {Message} message The message to respond to * @returns {Promise} The sent message */ getHelp(message) { const help = Object.values(this.bot.commandPlugins).map(plugin => plugin.help).filter(help => help); switch (this.help.style) { case 'basic': return message.channel.createMessage( `${this.help.title ? `**${this.help.title}**\n` : ''}${this.help.before ? this.help.before + '\n' : ''}\n${ help.filter(h => h).map(h => `__${h[0]}__: ${h[2].join(', ')}`).join('\n') }${this.help.after ? '\n\n' + this.help.after : ''}` ).catch(error => this.bot.logger.error('Error sending help message:', error)); case 'embed': return message.channel.createMessage({ embed: { title: this.help.title || this.bot.user.username + ' Command List', description: this.help.before || null, fields: help.filter(h => h).map(h => h[2].map((cmd, i) => { return { name: cmd, value: h[3][i] || '\u200B', inline: true }; })).reduce((a, b) => a.concat(b)), footer: this.help.after ? { text: this.help.after } : null } }).catch(error => this.bot.logger.error('Error sending help message:', error)); default: // style: extended return message.channel.createMessage( `${this.help.title ? `**${this.help.title}**\n` : ''}${this.help.before ? this.help.before + '\n' : ''}\n${help.filter(h => h).map(h => { return `**${h[0]}**: ${h[1]}\n\t${h[2].map((cmd, i) => cmd + ': ' + h[3][i]).join('\n\t')}` }).join('\n\n')}${this.help.after ? '\n\n' + this.help.after : ''}` ).catch(error => this.bot.logger.error('Error sending help message:', error)); } } /** * Add an await, which will trigger under certain conditions * @param {Function} trigger A function that takes a Message and returns a Boolean * @param {Function} action A function to be executed when `trigger` returns true * @param {Number} [timeout] Delete the await after this many milliseconds * @returns {Number} The unique id of the await */ awaitMessage(trigger, action, timeout) { if (typeof trigger !== 'function' || typeof action !== 'function') return new Error('Trigger and action must be functions'); let id = this._nextAwaitId++; this.awaits[id] = { trigger, action }; if (timeout) setTimeout(() => { delete this.awaits[id]; }, timeout); return id; } } module.exports = ChatHandler; ================================================ FILE: lib/Logger.js ================================================ const chalk = new (require('chalk')).constructor({enabled: true}); /** * Displays text to the console. Also supports sentry * @prop {RavenClient} raven The Raven client used for sentry, if enabled. */ class Logger { /** * Creates a new Logger * @param {Object} [options] The configuration for the logger * @param {Boolean} [options.timestamps=false] Add a timestamp to each message logged * @param {Object} [options.levels] An object deciding what log levels should display * @param {Boolean} [options.levels.log=true] Show `log()` * @param {Boolean} [options.levels.info=true] Show `info()` * @param {Boolean} [options.levels.debug=false] Show `debug()` * @param {Boolean} [options.levels.warning=true] Show `warn()` * @param {Boolean} [options.levels.error=true] Show `error()` * @param {Object} [options.raven] Raven options. If falsy, raven will not be required. * @param {String} options.raven.url Your project's sentry.io url * @param {Object} [options.raven.config] A custom raven config. For more info check {@link https://docs.sentry.io/clients/node/config/|their docs} * @param {Boolean} [options.raven.info=false] Send `info()` messages to sentry * @param {Boolean} [options.raven.debug=false] Send `debug()` messages to sentry * @param {Boolean} [options.raven.warning=false] Send `warn()` messages to sentry. If an {@link Error} is passed in the arguments, that will be sent alone. * @param {Boolean} [options.raven.error=true] Send `error()` errors to sentry. If an {@link Error} is passed in the arguments, that will be sent alone. */ constructor(options = { }) { this.timestamps = !!options.timestamps; this.levels = { 'log': options.levels && options.levels.log !== undefined ? options.levels.log : true, 'info': options.levels && options.levels.info !== undefined ? options.levels.info : true, 'debug': options.levels && options.levels.debug !== undefined ? options.levels.debug : false, 'warning': options.levels && options.levels.warning !== undefined ? options.levels.warning : true, 'error': options.levels && options.levels.error !== undefined ? options.levels.error : true }; if (options.raven) { this.raven = require('raven'); this.raven.disableConsoleAlerts(); this.raven.config(options.raven.url, options.raven.config || { release: (require('./package.json')).version, autoBreadcrumbs: { 'http': true }, captureUnhandledRejections: true }).install(); this.ravenLevels = { 'info': options.raven.info !== undefined ? options.raven.info : false, 'debug': options.raven.debug !== undefined ? options.raven.debug : false, 'warning': options.raven.warning !== undefined ? options.raven.warning : false, 'error': options.raven.error !== undefined ? options.raven.error : true }; } } /** * A formatted timestamp * @type {String} */ get timestamp() { return this.timestamps ? `[${new Date().toLocaleString()}] ` : ''; } /** Log generic text */ log() { if (this.levels.log) console.log(this.timestamp + Array.prototype.join.call(arguments, ' ')); } /** Log informal text */ info() { if (this.levels.info) console.info(this.timestamp + chalk.cyan(...arguments)); if (this.ravenLevels && this.ravenLevels.info) this.raven.captureMessage(Array.prototype.join.call(arguments, ' '), { level: 'info' }); } /** Log debugging information */ debug() { if (this.levels.debug) console.log(this.timestamp + chalk.gray(...arguments)); if (this.ravenLevels && this.ravenLevels.debug) this.raven.captureMessage(Array.prototype.join.call(arguments, ' '), { level: 'debug' }); } /** Log a warning */ warn() { if (this.levels.warning) console.warn(this.timestamp + chalk.yellow(...arguments)); if (this.ravenLevels && this.ravenLevels.warning) this.raven.captureMessage(Array.prototype.find.call(arguments, a => a instanceof Error) || Array.prototype.join.call(arguments, ' '), { level: 'warning' }); } /** Log an error */ error() { if (this.levels.error) console.error(this.timestamp + chalk.red([...arguments].map(e => e instanceof Error ? e.stack : e).join(' '))); if (this.ravenLevels && this.ravenLevels.error) this.raven.captureException(Array.prototype.find.call(arguments, a => a instanceof Error) || Array.prototype.join.call(arguments, ' ')); } } module.exports = Logger; ================================================ FILE: package.json ================================================ { "name": "mirai-bot-core", "version": "4.4.4", "description": "A Discord bot core allowing easy plugging in of modules", "author": "brussell98", "main": "index.js", "keywords": [ "discord", "bot", "core", "framework", "eris", "es6", "plugins", "middleware", "modules", "mirai" ], "homepage": "https://github.com/brussell98/Mirai#readme", "repository": { "type": "git", "url": "git+https://github.com/brussell98/Mirai.git" }, "bugs": { "url": "https://github.com/brussell98/Mirai/issues" }, "engines": { "node": ">=8.0.0" }, "scripts": { "start": "node index.js", "docs": "node_modules/.bin/jsdoc README.md --configure .jsdoc.json --verbose && node docBeautify.js" }, "license": "MIT", "dependencies": { "axios": "^0.19.0", "chalk": "^2.4.2", "eris": "^0.13.3" }, "optionalDependencies": { "bluebird": "^3.5.5", "bufferutil": "^4.0.1", "eventemitter3": "^3.1.2", "raven": "^2.6.4", "utf-8-validate": "^5.0.2" }, "devDependencies": { "docdash": "https://github.com/brussell98/docdash.git", "eslint": "*", "js-beautify": "^1.10.0", "jsdoc": "^3.6.2" } }