Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
},
"homepage": "https://github.com/SwitchbladeBot/switchblade-next#readme",
"dependencies": {
"axios": "^0.19.2",
"chalk": "^3.0.0",
"eris": "^0.11.2",
"winston": "^3.2.1"
Expand Down
23 changes: 23 additions & 0 deletions src/apis/Deezer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const { ApiWrapper } = require('../structures/api')
const axios = require('axios')

class DeezerAPI extends ApiWrapper {
constructor(client) {
super({ name: 'deezer' }, client)
}

load () {
return axios.create({
baseURL: 'https://api.deezer.com/',
responseType: 'json'
})
}

search(q) {
return this.request.get('search', {
params: { q }
}).then(r => r.data)
}
}

module.exports = DeezerAPI
15 changes: 13 additions & 2 deletions src/listeners/MessageListener.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,18 @@ module.exports = class MessageListener extends Listener {
super({ discordEvents }, client)
}

onMessageCreate (message) {
this.client.logger.info(message.content, { label: 'Message' })
onMessageCreate ({ content, channel }) {
// isso é só pra teste até lançar as nova parada do discord e a gente fazer com base nelas

if (!content) return

if (content.startsWith('psh!user get')) {
const query = content.replace('psh!user get ', '')
console.log(query)
this.client.apis.deezer.search(query).then(a => {
console.log(a.data[0])
this.client.createMessage(channel.id, a.data[0].artist.picture_big)
})
}
}
}
24 changes: 24 additions & 0 deletions src/loaders/ApiLoader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const { Loader, ApiWrapper } = require('../structures')

module.exports = class ApiLoader extends Loader {
constructor(client) {
super({ critical: true, name: 'APIs', priority: Loader.LoaderPriority.HIGH }, client)
this.client = client
this.client.apis = {}
}

load() {
return this.loadFiles('src/apis')
}

loadFile(NewAPI) {
const api = new NewAPI(this.client)
if (!(api instanceof ApiWrapper)) throw new Error(`Failed to load ${api.name}: not an api`)

if (api.preLoad()) {
this.client.apis[api.name] = api
return true
}
return false
}
}
2 changes: 1 addition & 1 deletion src/loaders/ListenerLoader.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const { Loader, Listener } = require('../structures')

module.exports = class ListenerLoader extends Loader {
constructor(client) {
super({ critical: true, name: 'Listeners' }, client)
super({ critical: true, name: 'Listeners', priority: Loader.LoaderPriority.LOW }, client)
this.listeners = []
}

Expand Down
3 changes: 2 additions & 1 deletion src/loaders/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
module.exports = {
ListenerLoader: require('./ListenerLoader.js')
ListenerLoader: require('./ListenerLoader.js'),
ApiLoader: require('./ApiLoader.js')
}
25 changes: 20 additions & 5 deletions src/structures/Loader.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
const { createOptionHandler, FileUtils } = require('../utils')

/**
* Loader priority, in this order:
* HIGH
* NORMAL
* LOW
*/
const LoaderPriority = {
HIGH: 0,
NORMAL: 1,
LOW: 2
}

module.exports = class Loader {
/**
* @param {Object} opts
Expand All @@ -12,6 +24,7 @@ module.exports = class Loader {
this.critical = options.optional('critical', false)

this.name = options.optional('name', this.constructor.name)
this.priority = options.optional('priority', LoaderPriority.NORMAL)

this.client = client
}
Expand All @@ -22,7 +35,7 @@ module.exports = class Loader {
if (!success) throw new Error(`Unhandled error`)
return success
} catch (e) {
this.client.logger.error(`Failed to load ${this.name}`, { label: 'Loader' })
this.client.logger.error(`Failed to load ${this.name}`, { label: 'Loaders' })
return false
}
}
Expand All @@ -32,7 +45,7 @@ module.exports = class Loader {
let success = 0
let fails = 0
const errorFunction = e => {
this.client.logger.error(e)
this.client.logger.error(e, { label: 'Loaders'})
fails++
}
const successFunction = file => {
Expand All @@ -45,8 +58,8 @@ module.exports = class Loader {
}
}
await FileUtils.requireDirectory(path, successFunction, errorFunction, recursive).then(() => {
if (fails) this.client.logger.warn(`${success} types of ${this.name} loaded, ${fails} failed.`, { label: this.name })
else this.client.logger.info(`All ${success} types of ${this.name} loaded without errors.`, { label: this.name })
if (fails) this.client.logger.warn(`${success} types of ${this.name} loaded, ${fails} failed.`, { label: 'Loaders' })
else this.client.logger.info(`All ${success} types of ${this.name} loaded without errors.`, { label: 'Loaders' })
})
return true
}
Expand All @@ -58,4 +71,6 @@ module.exports = class Loader {
loadFile(file) {
throw new Error(`The ${this.name} loader has not implemented the loadFile() function`)
}
}
}

module.exports.LoaderPriority = LoaderPriority
28 changes: 28 additions & 0 deletions src/structures/api/ApiWrapper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const { createOptionHandler } = require('../../utils')

module.exports = class ApiWrapper {
constructor (options, client) {
options = createOptionHandler('Loader', options)

this.name = options.optional('name', this.constructor.name)
this.provider = options.optional('provider', null)
this.envVars = options.optional('envVars', null)
this.request = null
}

preLoad () {
if (this.envVars) {
for (const envVar of this.envVars)
if (!process.env[envVar]) return false
}

this.request = this.load();

if (!this.request) return false;
return true
}

load () {
return null;
}
}
3 changes: 3 additions & 0 deletions src/structures/api/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
ApiWrapper: require('./ApiWrapper.js')
}
32 changes: 22 additions & 10 deletions src/structures/base/Switchblade.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const { CommandClient } = require('eris')
const Loaders = require('../../loaders')
const { LoaderPriority } = require('../Loader.js')
const { readFileSync } = require('fs')
const chalk = require('chalk')
const winston = require('winston')
const chalk = require('chalk')

module.exports = class Switchblade extends CommandClient {
constructor(token, options, commandOptions) {
Expand All @@ -15,7 +16,7 @@ module.exports = class Switchblade extends CommandClient {
if (process.env.NODE_ENV !== 'production') console.log(readFileSync('bigtitle.txt', 'utf8').toString().replace(/{UNICODE}/g, '\u001b['))
this.logger.info('Starting switchblade...', { label: 'Switchblade' })
this.initializeLoaders()

this.connect()
}

Expand All @@ -38,16 +39,27 @@ module.exports = class Switchblade extends CommandClient {
}
}

async initializeLoaders () {
async initializeLoaders() {
const loaders = [[], [], []]
for (let file in Loaders) {
const loader = new Loaders[file](this)
let success = true
try {
success = await loader.preLoad()
} catch (error) {
this.logger.error(error.stack, { label: 'Loaders', stack: error.stack })
} finally {
if (!success && loader.critical) process.exit(1)
loaders[loader.priority].push(loader)
}

for (let loaderPriority of loaders) {
const priority = Object.keys(LoaderPriority)[loaders.indexOf(loaderPriority)]
this.logger.info(`Starting to load ${chalk.yellow(priority)}`, { label: 'Loaders' })

for (let loader of loaderPriority) {
let success = true

try {
success = await loader.preLoad()
} catch (error) {
this.logger.error(error.stack, { label: 'Loaders', stack: error.stack })
} finally {
if (!success && loader.critical) process.exit(1)
}
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/structures/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module.exports = {
// Loader
Loader: require('./Loader.js'),
Listener: require('./Listener.js')
Listener: require('./Listener.js'),
ApiWrapper: require('./api/ApiWrapper.js')
}