Skip to content

Commit

Permalink
Expose MongoDB to new command architecture, work on tests and warn.
Browse files Browse the repository at this point in the history
  • Loading branch information
retrixe committed May 23, 2018
1 parent f05a721 commit 3644d18
Show file tree
Hide file tree
Showing 9 changed files with 52 additions and 34 deletions.
1 change: 1 addition & 0 deletions server/bot/commands/admin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { handleWarn } from './admin/warn'
17 changes: 17 additions & 0 deletions server/bot/commands/admin/warn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { IveBotCommand } from '../../imports/types'

export const handleWarn: IveBotCommand = (client, tempDB, DB) => ({
name: 'warn',
opts: {
description: 'Warn someone.',
fullDescription: 'Warn someone.',
usage: '/warn <user by ID/username/mention> <reason>'
},
generator: (message, args) => {
// Check user for permissions.
if (!message.member.permission.has('manageMessages')) {
return '**Thankfully, you don\'t have enough permissions for that, you ungrateful bastard.**'
// Or if improper arguments were provided, then we must inform the user.
} else if (args.length < 2) return 'Correct usage: /warn <user> <reason>'
}
})
7 changes: 3 additions & 4 deletions server/bot/imports/types.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// Flow our types.
/* eslint-disable no-undef */
import { CommandClient, Member, Message, CommandOptions, CommandGenerator } from 'eris'
import { Db } from 'mongodb' // eslint-disable-line no-unused-vars

// eslint-disable-next-line no-use-before-define
export type IveBotCommand = (client: CommandClient, db?: DB) => {
export type IveBotCommand = (client: CommandClient, db?: DB, mongoDB?: Db) => {
generator: CommandGenerator,
opts: CommandOptions,
name: string
Expand All @@ -30,7 +31,5 @@ export type DB = {
},
leave: Array<string>
}
export type mongoDB = {
collection: Function
}
export type mongoDB = Db
/* eslint-enable no-undef */
18 changes: 4 additions & 14 deletions server/bot/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Tokens and stuff.
import 'json5/lib/require'
import { testPilots, host, mongoURL } from '../../config.json5'
import { testPilots, host } from '../../config.json5'
import { version } from '../../package.json'
import { execSync } from 'child_process'
import { randomBytes } from 'crypto'
Expand All @@ -25,17 +25,7 @@ import { client, DB, mongoDB, member, message } from './imports/types'
import { PrivateChannel } from 'eris'
import { getArguments, getServerSettings } from './imports/tools'
import help from './oldCommands/help'

// MongoDB.
// Get MongoDB.
import { MongoClient } from 'mongodb'
// Create a MongoDB instance.
let db: mongoDB
MongoClient.connect(mongoURL === 'dotenv' ? process.env.MONGO_URL : mongoURL, (err, client) => {
if (err) throw new Error('Error:\n' + err)
console.log('Bot connected successfully to MongoDB.')
db = client.db('ivebot')
})
import { Db } from 'mongodb'

// All commands which take (message, sendResponse) as args and can be appended and interpreted.
const appendableCommandMaps: { [index: string]: Function } = {
Expand Down Expand Up @@ -65,7 +55,7 @@ const appendableCommandMaps: { [index: string]: Function } = {
}

// When client gains/loses a member, it will callback.
export const guildMemberEditCallback = (client: client, event: string) => async (
export const guildMemberEditCallback = (client: client, event: string, db: Db) => async (
guild: { id: string }, member: member
) => { // eslint-disable-line indent
// WeChill specific configuration.
Expand Down Expand Up @@ -111,7 +101,7 @@ export const guildMemberEditCallback = (client: client, event: string) => async
}

// When client recieves a message, it will callback.
export default (client: client, tempDB: DB) => async (event: message) => {
export default (client: client, tempDB: DB, db: mongoDB) => async (event: message) => {
// Disable bots and webhooks from being responded to.
try { if (event.author.bot) return } catch (e) { return }
try {
Expand Down
2 changes: 0 additions & 2 deletions server/bot/oldCommands/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ export function handleDefine (message: string, sendResponse: Function) {
if (!getArguments(message)) {
sendResponse('Enter a valid word for me to define.')
return
} else if (getArguments(message).toLowerCase()) {
sendResponse('someone you don\'t deserve to know about, haha'); return
}
// Fetch the definition.
const headers = { 'app_id': oxfordAPI.appId, 'app_key': oxfordAPI.appKey, Accept: 'application/json' }
Expand Down
28 changes: 18 additions & 10 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ import { DB, IveBotCommand } from './bot/imports/types'

// Tokens and stuff.
import { CommandClient } from 'eris'
// Get MongoDB.
import { MongoClient, Db } from 'mongodb'
// Import fs.
import { readdir, statSync } from 'fs'
// Import the bot.
import botCallback, { guildMemberEditCallback } from './bot'
// Get the token needed.
import 'json5/lib/require'
import { token, host } from '../config.json5'
import { token, host, mongoURL } from '../config.json5'

// If production is explicitly specified via flag..
if (process.argv[2] === '--production') process.env.NODE_ENV = 'production'
Expand All @@ -44,6 +46,21 @@ const client = new CommandClient(token === 'dotenv' ? process.env.IVEBOT_TOKEN :
// Connect ASAP, hopefully before the server starts.
client.connect()

// Create a MongoDB instance.
let db: Db
MongoClient.connect(mongoURL === 'dotenv' ? process.env.MONGO_URL : mongoURL, (err, mongoDB) => {
if (err) throw new Error('Error:\n' + err)
console.log('Bot connected successfully to MongoDB.')
db = mongoDB.db('ivebot')
// When a server loses a member, it will callback.
client.on('guildMemberAdd', guildMemberEditCallback(client, 'guildMemberAdd', db))
client.on('guildMemberRemove', guildMemberEditCallback(client, 'guildMemberRemove', db))
// When a message is sent, the function should be called.
// This is here for temporary compatibility with older commands which have not been re-written.
// Avoid usage, submit PRs to bot/commands and not bot/index and bot/oldCommands.
client.on('messageCreate', botCallback(client, tempDB, db))
})

// On connecting..
client.on('ready', () => {
console.log('Connected to Discord.')
Expand Down Expand Up @@ -84,15 +101,6 @@ readdir('./server/bot/commands', (err, commandFiles) => {
})
})

// When a message is sent, the function should be called.
// This is here for temporary compatibility with older commands which have not been re-written.
// Avoid usage, submit PRs to bot/commands and not bot/index and bot/oldCommands.
client.on('messageCreate', botCallback(client, tempDB))

// When a server loses a member, it will callback.
client.on('guildMemberAdd', guildMemberEditCallback(client, 'guildMemberAdd'))
client.on('guildMemberRemove', guildMemberEditCallback(client, 'guildMemberRemove'))

/* SERVER CODE STARTS HERE */
// Initialize Next.js app.
const app = next({ dev })
Expand Down
9 changes: 7 additions & 2 deletions tests/bot/commands/games.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import test from 'ava'
import {
handleReverse, handle8Ball, handleChoose, handleRandom
} from '../../../lib/commands/games'
handleReverse as hr, handle8Ball as h8, handleChoose as hc, handleRandom as hrand
} from '../../../lib/bot/commands/games'

const handleReverse = hr({}).generator
const handle8Ball = h8({}).generator
const handleChoose = hc({}).generator
const handleRandom = hrand({}).generator

test('/reverse works as expected', t => handleReverse('/reverse ab', result => t.is(result, 'ba')))
test('/8ball works as expected', t => handle8Ball('/8ball hi', result => {
Expand Down
2 changes: 1 addition & 1 deletion tests/bot/imports/permissions.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import test from 'ava'
import {
checkUserForPermission as cufp, checkRolePosition as crp
} from '../../../lib/imports/permissions'
} from '../../../lib/bot/imports/permissions'

const client = {
servers: {
Expand Down
2 changes: 1 addition & 1 deletion tests/bot/imports/tools.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import test from 'ava'
import {
getArguments as ga, getIdFromMention as gifm
} from '../../../lib/imports/tools'
} from '../../../lib/bot/imports/tools'

test('getArguments returns proper arguments', t => t.is(ga('/test command args'), 'command args'))
test('getIdFromMention returns a correct ID for users', t => {
Expand Down

0 comments on commit 3644d18

Please sign in to comment.