Permalink
Browse files

Bot extends Client, Bot.setAvatar

  • Loading branch information...
1 parent ad873c0 commit f8c98b54275565403e56360c18f096d4f8835d4d @brussell98 committed Nov 19, 2016
View
@@ -1,32 +1,32 @@
{
- "tags": {
- "allowUnknownTags": true,
- "dictionaries": ["jsdoc"]
- },
- "source": {
+ "tags": {
+ "allowUnknownTags": true,
+ "dictionaries": ["jsdoc"]
+ },
+ "source": {
"include": ["lib/"],
- "includePattern": ".js$",
- "excludePattern": "(node_modules/|docs)"
- },
- "plugins": [
- "plugins/markdown"
- ],
- "templates": {
+ "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"
- }
+ "cleverLinks": false,
+ "monospaceLinks": true
+ },
+ "opts": {
+ "destination": "./docs/",
+ "encoding": "utf8",
+ "private": true,
+ "recurse": true,
+ "template": "./node_modules/docdash"
+ }
}
@@ -11,6 +11,10 @@ class GeneralCommands extends AbstractCommandPlugin {
return 'general';
}
+ get help() {
+ return 'General: ' + Object.keys(this.commands).join(', ');
+ }
+
load(bot) {
return new Promise((resolve, reject) => {
super.load(bot);
@@ -24,7 +28,7 @@ class GeneralCommands extends AbstractCommandPlugin {
this.commands[command.name] = command;
});
} catch (e) {
- this.bot.logger.error(`Error loading ${file}: ${e.stack}`);
+ this.logger.error(`Error loading ${file}: ${e.stack}`);
}
}
resolve();
@@ -33,7 +37,7 @@ class GeneralCommands extends AbstractCommandPlugin {
}
handle(message) {
- if (message[0] === '!') {
+ if (message.content[0] === '!') {
let command = message.content.substr(1);
for (let name in this.commands) {
if (command.startsWith(name))
@@ -0,0 +1,23 @@
+var AbstractCommand = require('../../../../lib/base/AbstractCommand');
+
+class SetAvatarCommand extends AbstractCommand {
+ constructor() {
+ super();
+ }
+
+ get name() {
+ return 'setAvatar';
+ }
+
+ handle(message, args) {
+ if (message.author.id === '95286900801146880') {
+ this.parent.bot.setAvatar(args).then(() => {
+ this.sendMessage(message, 'Avatar updated');
+ }).catch(error => {
+ this.sendMessage(message, error);
+ });
+ }
+ }
+}
+
+module.exports = SetAvatarCommand;
@@ -5,5 +5,5 @@ var GeneralCommands = new (require('./commands/GeneralCommands'));
var mirai = new Mirai(config);
mirai.loadCommandPlugin(GeneralCommands)
- .then(() => mirai.run())
+ .then(() => mirai.connect())
.catch(console.error);
@@ -9,13 +9,11 @@ class AbstractCommand {
}
load(parent) {
- this.client = parent.bot.client;
this.parent = parent;
return Promise.resolve(this);
}
destroy() {
- this.client = undefined;
this.parent = undefined;
return Promise.resolve();
}
@@ -24,7 +22,7 @@ class AbstractCommand {
if (!message || !content)
return;
- if (options.deleteTrigger && message.channel.guild && message.channel.permissionsOf(this.client.user.id).has('manageMessages'))
+ 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)); // TODO
if (options.tts)
@@ -13,11 +13,13 @@ class AbstractCommandPlugin {
}
load(bot) {
+ this.logger = bot.logger;
this.bot = bot;
return Promise.resolve(this);
}
destroy() {
+ this.logger = undefined;
this.bot = undefined;
return Promise.resolve();
}
View
@@ -3,12 +3,7 @@ const Logger = require('./Logger.js'),
Eris = require('eris'),
request = require('unirest');
-var EventEmitter, Promise;
-try {
- EventEmitter = require("eventemitter3");
-} catch(err) {
- EventEmitter = require("events").EventEmitter;
-}
+var Promise;
try {
Promise = require("bluebird");
} catch(err) {
@@ -17,62 +12,55 @@ try {
/**
* Manages the connection to Discord and interaction between plugins
- * @extends EventEmitter
+ * @extends {@link http://eris.tachibana.erendale.abal.moe/docs/Client|Eris.Client}
* @example <caption>Create a new instance of Mirai</caption>
* const Mirai = require('mirai-bot-discord');
* var config = require('./config.json');
* var mirai = new Mirai(config);
*/
-class Bot extends EventEmitter {
+class Bot extends Eris.Client {
constructor(config) {
- super();
+ super(config.token, config.eris);
config = config || {};
this.carbonBotsKey = config.carbonBotsKey;
this.discordBotsKey = config.discordBotsKey;
this.logger = new Logger();
- this.client = new Eris(config.token, config.erisOptions);
this.chatHandler = new ChatHandler(this, config.chatHandler);
this.blacklistedGuilds = config.blacklistedGuilds || [];
this.blacklistedUsers = config.blacklistedUsers || [];
this.commandPlugins = [];
this.eventPlugins = [];
this.middleware = [];
- this.client.on('ready', () => {
+ this.on('ready', () => {
this.chatHandler.run();
this.logger.info('ready'); // TODO
- this.emit('ready');
});
- this.client.on('error', (error, shard) => {
- this.logger.error('error', error); // TODO
- this.emit('error', error, shard)
+ this.on('error', (error, shard) => {
+ this.logger.error('error', error, shard); // TODO
});
- this.client.on('disconnected', () => {
+ this.on('disconnected', () => {
this.logger.error('disconnected'); // TODO
- this.emit('disconnected');
});
- this.client.on('shardReady', shard => {
+ this.on('shardReady', shard => {
this.logger.info('shard', shard, 'ready'); // TODO
- this.emit('shardReady', shard);
});
- this.client.on('shardDisconnect', (error, shard) => {
+ this.on('shardDisconnect', (error, shard) => {
this.logger.warn('shard', shard, 'disconnected'); // TODO
- this.emit('shardDisconnect', error, shard);
});
- this.client.on('shardResume', shard => {
+ this.on('shardResume', shard => {
this.logger.info('shard', shard, 'resumed'); // TODO
- this.emit('shardResume', shard);
});
if (this.blacklistedGuilds.length !== 0) {
- this.client.on('guildCreate', guild => {
+ this.on('guildCreate', guild => {
if (this.blacklistedGuilds.includes(guild.id)) {
guild.leave();
this.logger.info('left', guild.name); // TODO
@@ -81,13 +69,6 @@ class Bot extends EventEmitter {
}
}
- /** Runs the bot, connecting to Discord */
- run() {
- this.client.connect().catch(error => {
- this.emit('error', error);
- });
- }
-
/**
* @param {Function} plugin The plugin to load. Must have a load() method which is passed <code>this</code>.
* @example <caption>Loading a Command Plugin</caption>
@@ -183,7 +164,7 @@ class Bot extends EventEmitter {
.type('application/json')
.send({
key: key || this.carbonBotsKey,
- servercount: this.client.guilds.size
+ servercount: this.guilds.size
})
.end(response => {
if (response.ok) {
@@ -199,10 +180,10 @@ class Bot extends EventEmitter {
updateDiscordBots(key) {
return new Promise((resolve, reject) => {
- request.post(`https://bots.discord.pw/api/bots/${this.client.user.id}/stats`)
+ request.post(`https://bots.discord.pw/api/bots/${this.user.id}/stats`)
.header('Authorization', key || this.discordBotsKey)
.type('application/json')
- .send({server_count: this.client.guilds.size})
+ .send({server_count: this.guilds.size})
.end(response => {
if (response.ok) {
this.logger.debug(); // TODO
@@ -214,6 +195,29 @@ class Bot extends EventEmitter {
});
});
}
+
+ setAvatar(url) {
+ return new Promise((resolve, reject) => {
+ request.get(url)
+ .header('Accept', 'image/*')
+ .encoding('base64')
+ .end(response => {
+ if (response.ok) {
+ this.editSelf({avatar: `data:${response.headers['content-type']};base64,${response.body}`})
+ .then(() => {
+ this.logger.debug('Updated avatar'); // TODO
+ resolve();
+ }).catch(error => {
+ this.logger.warn('Failed to update avatar: ' + error); // TODO
+ reject(error);
+ });
+ } else {
+ this.logger.warn('Failed to fetch avatar: ' + (response.error.code || response.error)); // TODO
+ reject(response.error.code || response.error);
+ }
+ });
+ });
+ }
}
module.exports = Bot;
View
@@ -18,7 +18,7 @@ class ChatHandler {
}
this.messageHandler = message => {
- if ((message.author.id === this.bot.client.user.id && this.allowSelf === false) ||
+ 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))
@@ -43,15 +43,15 @@ class ChatHandler {
}
run() {
- this.bot.client.on('messageCreate', this.messageHandler);
+ this.bot.on('messageCreate', this.messageHandler);
}
stop() {
- this.bot.client.removeListener('messageCreate', this.messageHandler);
+ this.bot.removeListener('messageCreate', this.messageHandler);
}
getHelp(message) {
- message.channel.createMessage(`${this.help.before || ''}${this.bot.commandPlugins.map(plugin => plugin.help).filter(help => !!help).join('\n')}${this.help.after ? '\n' + this.help.after : ''}`);
+ message.channel.createMessage(`${this.help.before + '\n' || ''}${this.bot.commandPlugins.map(plugin => plugin.help).filter(help => !!help).join('\n')}${this.help.after ? '\n' + this.help.after : ''}`);
}
awaitMessage(trigger, action, timeout) {
Oops, something went wrong.

0 comments on commit f8c98b5

Please sign in to comment.