switched nedb to nedb-promises (#37)

* breaking change: switched to nedb-promises
* Linting
* some dev dependencies
* more tests
* updated package version
* bug fixing
* changed isNaN to isString
* (fix) args[0]
This commit is contained in:
2021-05-03 18:39:33 +02:00
committed by GitHub
parent dc746276ab
commit c6cacdae5e
41 changed files with 16168 additions and 13670 deletions

View File

@ -63,7 +63,13 @@
"no-with": 2, "no-with": 2,
"require-yield": 2, "require-yield": 2,
"use-isnan": 2, "use-isnan": 2,
"valid-typeof": 2 "valid-typeof": 2,
"no-underscore-dangle": 0,
"spaced-comment": 0,
"no-console": 0,
"no-unneeded-ternary": 0,
"object-shorthand": 0,
"no-useless-rename": 0
}, },
"env": { "env": {
"node": true, "node": true,
@ -71,5 +77,14 @@
"commonjs": true, "commonjs": true,
"es2017": true "es2017": true
}, },
"extends": ["prettier"] "plugins": [
"prettier"
],
"extends": [
"airbnb",
"prettier"
],
"settings": {
"import/resolver": "module-alias"
}
} }

View File

@ -1,7 +1,7 @@
require('module-alias/register'); require('module-alias/register');
const rewire = require('rewire'); const rewire = require('rewire');
const rewireUtils = rewire('@Commands/Attack');
const rewireUtils = rewire('@Commands/Attack');
const getWeapon = rewireUtils.__get__('getWeapon'); const getWeapon = rewireUtils.__get__('getWeapon');
const getAttributeLevel = rewireUtils.__get__('getAttributeLevel'); const getAttributeLevel = rewireUtils.__get__('getAttributeLevel');
const getCombatTechniqueLevel = rewireUtils.__get__('getCombatTechniqueLevel'); const getCombatTechniqueLevel = rewireUtils.__get__('getCombatTechniqueLevel');
@ -139,7 +139,7 @@ it('should abort with a message: no entry found', () => {
}; };
const handleAttack = rewireUtils.__get__('handleAttack'); const handleAttack = rewireUtils.__get__('handleAttack');
//expect(handleAttack(err)).toThrowError(); //expect(handleAttack(err)).toThrowError();
expect(handleAttack([], { message: message })).toEqual( expect(handleAttack({}, { message: message })).toEqual(
'Sorry, für dich habe ich leider keinen Eintrag 😥' 'Sorry, für dich habe ich leider keinen Eintrag 😥'
); );
}); });
@ -178,7 +178,7 @@ it('complete run with melee weapon', () => {
}; };
const handleAttack = rewireUtils.__get__('handleAttack'); const handleAttack = rewireUtils.__get__('handleAttack');
const args = ['messer']; const args = ['messer'];
expect(handleAttack([{ character: character }], { message: message, args: args })).toEqual( expect(handleAttack({ character: character }, { message: message, args: args })).toEqual(
expect.any(String) expect.any(String)
); );
}); });
@ -204,7 +204,7 @@ it('complete run with ranged weapon', () => {
}; };
const handleAttack = rewireUtils.__get__('handleAttack'); const handleAttack = rewireUtils.__get__('handleAttack');
const args = ['langbogen']; const args = ['langbogen'];
expect(handleAttack([{ character: character }], { message: message, args: args })).toEqual( expect(handleAttack({ character: character }, { message: message, args: args })).toEqual(
expect.any(String) expect.any(String)
); );
}); });

View File

@ -1,7 +1,8 @@
require('module-alias/register'); require('module-alias/register');
const rewire = require('rewire'); const rewire = require('rewire');
const rewireUtils = rewire('@Commands/Attribute');
const Attribute = require('@Commands/Attribute'); const Attribute = require('@Commands/Attribute');
const rewireUtils = rewire('@Commands/Attribute');
const HandleNamedAttributes = rewireUtils.__get__('HandleNamedAttributes'); const HandleNamedAttributes = rewireUtils.__get__('HandleNamedAttributes');
const getAttributeLevel = rewireUtils.__get__('getAttributeLevel'); const getAttributeLevel = rewireUtils.__get__('getAttributeLevel');
const getAttribute = rewireUtils.__get__('getAttribute'); const getAttribute = rewireUtils.__get__('getAttribute');
@ -44,9 +45,9 @@ it('should return with no errors', () => {
tag: 'test', tag: 'test',
}, },
}; };
const docs = [{ character: { attributes: [{ id: 'mut', level: 8 }] } }]; const doc = { character: { attributes: [{ id: 'mut', level: 8 }] } };
const args = ['mut']; const args = ['mut'];
expect(handleAttributeCheck(docs, { message, args })).toEqual(expect.any(String)); expect(handleAttributeCheck(doc, { message, args })).toEqual(expect.any(String));
}); });
it('should return with no errors', () => { it('should return with no errors', () => {
const reply = jest.fn(str => str); const reply = jest.fn(str => str);
@ -56,7 +57,7 @@ it('should return with no errors', () => {
tag: 'test', tag: 'test',
}, },
}; };
const docs = [{ character: { attributes: [{ id: 'mut', level: 8 }] } }]; const docs = { character: { attributes: [{ id: 'mut', level: 8 }] } };
const args = ['MU']; const args = ['MU'];
expect(handleAttributeCheck(docs, { message, args })).toEqual(expect.any(String)); expect(handleAttributeCheck(docs, { message, args })).toEqual(expect.any(String));
}); });
@ -70,7 +71,7 @@ it('should return with no errors', () => {
}; };
const docs = [{ character: { attributes: [{ id: 'mut', level: 8 }] } }]; const docs = [{ character: { attributes: [{ id: 'mut', level: 8 }] } }];
const args = [8]; const args = [8];
for (let i = 0; i < 30; i++) { for (let i = 0; i < 30; i += 1) {
expect(handleAttributeCheck(docs, { message, args })).toEqual(expect.any(String)); expect(handleAttributeCheck(docs, { message, args })).toEqual(expect.any(String));
} }
}); });
@ -84,15 +85,18 @@ it('should return with no errors', () => {
}; };
const docs = [{ character: { attributes: [{ id: 'mut', level: 8 }] } }]; const docs = [{ character: { attributes: [{ id: 'mut', level: 8 }] } }];
const args = [8, '+2']; const args = [8, '+2'];
for (let i = 0; i < 30; i++) { for (let i = 0; i < 30; i += 1) {
expect(handleAttributeCheck(docs, { message, args })).toEqual(expect.any(String)); expect(handleAttributeCheck(docs, { message, args })).toEqual(expect.any(String));
} }
}); });
it('should return empty', () => { it('should return empty', () => {
const message = { author: { tag: 'test' } }; const message = { author: { tag: 'test' }, reply: jest.fn(str => str) };
const args = ['MU']; const args = ['MU'];
expect(Attribute.exec(message, args)).toEqual(expect.objectContaining({})); expect(Attribute.exec(message, args)).toBeInstanceOf(Promise);
//expect(Attribute.exec(message, args)).resolves.toBeUndefined();
}); });
/* /*
const reply = jest.fn(str => str); const reply = jest.fn(str => str);

View File

@ -0,0 +1,17 @@
require('module-alias/register');
// const { List } = require('@Commands/List');
const rewire = require('rewire');
const reWireUtils = rewire('@Commands/List');
// const getStats = reWireUtils.__get__('getStats');
const getAttribute = reWireUtils.__get__('getAttribute');
it('should return an attribute object', () => {
expect(getAttribute({ id: 'mut', level: 9 })).toEqual(
expect.objectContaining({
id: expect.any(String),
Name: expect.any(String),
Level: expect.any(Number),
})
);
});

View File

@ -3,7 +3,7 @@ require('module-alias/register');
const { CompareResults } = require('@dsabot/CompareResults'); const { CompareResults } = require('@dsabot/CompareResults');
it('should return an object', () => { it('should return an object', () => {
let Obj = { const Obj = {
Passed: 0, Passed: 0,
CriticalHit: 0, CriticalHit: 0,
Fumbles: 0, Fumbles: 0,
@ -15,7 +15,7 @@ it('should return an object', () => {
}); });
it('should match No. of Fumbles', () => { it('should match No. of Fumbles', () => {
let Obj = { const Obj = {
Passed: 0, Passed: 0,
CriticalHit: 0, CriticalHit: 0,
Fumbles: 2, Fumbles: 2,
@ -26,7 +26,7 @@ it('should match No. of Fumbles', () => {
}); });
it('should match No. of Passed', () => { it('should match No. of Passed', () => {
let Obj = { const Obj = {
Passed: 3, Passed: 3,
CriticalHit: 0, CriticalHit: 0,
Fumbles: 0, Fumbles: 0,
@ -37,7 +37,7 @@ it('should match No. of Passed', () => {
}); });
it('should match No. of Critical Hits', () => { it('should match No. of Critical Hits', () => {
let Obj = { const Obj = {
Passed: 3, Passed: 3,
CriticalHit: 2, CriticalHit: 2,
Fumbles: 0, Fumbles: 0,
@ -48,7 +48,7 @@ it('should match No. of Critical Hits', () => {
}); });
it('should decrease Points remaining', () => { it('should decrease Points remaining', () => {
let Obj = { const Obj = {
Passed: 3, Passed: 3,
CriticalHit: 0, CriticalHit: 0,
Fumbles: 0, Fumbles: 0,

View File

@ -0,0 +1,6 @@
require('module-alias/register');
const { findMessage } = require('@dsabot/findMessage');
it('should capitalize the first letter.', () => {
expect(findMessage('ERROR')).toBe('Irgendwas ist schief gelaufen. 🤔');
});

View File

@ -0,0 +1,12 @@
require('module-alias/register');
const { isEmpty } = require('@dsabot/isEmpty');
it('should return true statements', () => {
expect(isEmpty({})).toBeTruthy();
expect(isEmpty()).toBeTruthy();
expect(isEmpty('')).toBeTruthy();
expect(isEmpty([])).toBeTruthy();
expect(isEmpty({ key: 'value' })).toBeFalsy();
expect(isEmpty([null])).toBeFalsy();
expect(isEmpty([''])).toBeFalsy();
});

3
babel.config.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
plugins: ['babel-plugin-rewire'],
};

View File

@ -1,112 +1,27 @@
require('module-alias/register'); require('module-alias/register');
const globals = require('../globals');
const db = globals.db;
const { roll } = require('@dsabot/Roll'); const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const { isEmpty } = require('@dsabot/isEmpty');
module.exports = { const { db } = require('../globals');
name: 'attack', const { CombatTechniques } = require('../globals');
description: 'Würfelt den Attackewert auf eine Nahkampfwaffe.', const { Werte } = require('../globals');
aliases: ['angriff', 'attacke'], const { Weapons } = require('../globals');
usage: '<Waffe>', const { MeleeWeapons } = require('../globals');
needs_args: true,
async exec(message, args) {
try {
db.find({ user: message.author.tag }, (err, docs) => {
if (err) {
message.reply(findMessage('ERROR'));
throw new Error(err);
}
handleAttack(docs, { message: message, args: args });
});
} catch (e) {
message.reply(findMessage('ERROR'));
throw e;
}
},
};
function handleAttack(docs, { message: message, args: args }) {
if (docs.length === 0) {
return message.reply(findMessage('NOENTRY'));
}
const Player = docs[0].character;
const Weapon = getWeapon(args[0]);
if (!Weapon) {
return message.reply(findMessage('NO_SUCH_WEAPON'));
}
// Determining Both Attack and Ranged Attack Values.
let CombatTechnique = getCombatTechniqueLevel(Player, getCombatTechnique(Weapon)); //?+
let Attribute = isMeleeWeapon(Weapon)
? getAttributeLevel(Player, 'mut')
: getAttributeLevel(Player, 'fingerfertigkeit');
let AttackValue = isMeleeWeapon(Weapon)
? CombatTechnique.level + Weapon.at_mod
: CombatTechnique.level;
AttackValue += Math.floor((Attribute - 8) / 3);
let dice = roll(2, 20).dice;
let Bonus = parseInt(args[1]) || 0;
let Comparison = Math.floor(AttackValue + Bonus);
const AttackResult = CompareAttackResult(dice, Comparison);
let Reply = `Du greifst mit ${Weapon.name} an.\n Dein Angriffswert für ${CombatTechnique.name} ist ${AttackValue} (KtW: ${CombatTechnique.level})\n`;
Reply += 'Deine 🎲: ` ' + AttackResult.Dice.join(', ') + ' `.\n\n';
Reply += !AttackResult.Ok ? findMessage('COMBAT_FAIL') : findMessage('COMBAT_SUCCESS');
Reply += AttackResult.Patzer ? findMessage('COMBAT_CRIT_FAIL') : '';
Reply += AttackResult.CriticalHit ? findMessage('COMBAT_CRIT_SUCCESS') : '';
Reply += AttackResult.DoubleDamage ? findMessage('COMBAT_DOUBLEDAMAGE') : '';
if (AttackResult.Ok) {
// adding 1 to damage for every point above weapon's "Leiteigenschaft"
// applies only to Melee Weapons.
let AttackBonus = 0;
if (isMeleeWeapon(Weapon) && Weapon.DmgThreshold) {
CombatTechnique.Leiteigenschaft.forEach(abbr => {
let Attribute = getAttribute(abbr);
let AttributeValue = getAttributeLevel(Player, Attribute.id);
if (Weapon.DmgThreshold < AttributeValue) {
AttackBonus += Math.floor(AttributeValue - Weapon.DmgThreshold);
}
});
}
let DamageDice = roll(1, 6).dice;
let Damage = Weapon.diemodificator + AttackBonus + DamageDice.reduce((p, v) => p + v);
Damage = AttackResult.DoubleDamage ? (Damage *= 2) : Damage;
Reply += '\n\nHier aufklappen, wenn der Gegner nicht parieren/Ausweichen konnte:\n';
Reply += `|| ${Weapon.name} (${Weapon.dice}W6+${
Weapon.diemodificator
}) richtet ${Damage} schaden an. ${
AttackBonus ? `(+${AttackBonus} Bonus auf Leiteigenschaft)` : ''
}`;
Reply += '\nDeine 🎲: ` ' + DamageDice.join(',') + ' `.||\n';
}
return message.reply(Reply);
}
function getCombatTechnique(Weapon) { function getCombatTechnique(Weapon) {
if (Weapon) if (Weapon) return CombatTechniques.find(technique => technique.id === Weapon.combattechnique);
return globals.CombatTechniques.find(technique => technique.id === Weapon.combattechnique); return null;
} }
function getAttribute(abbr) { function getAttribute(abbr) {
return globals.Werte.find(attribute => attribute.kuerzel === abbr); return Werte.find(attribute => attribute.kuerzel === abbr);
} }
function CompareAttackResult(dice = [8, 8], Comparison = 6) { function CompareAttackResult(dice = [8, 8], Comparison = 6) {
let ok = false, let ok = false;
crit = false, let crit = false;
dd = false, let dd = false;
fumble = false; let fumble = false;
dice.forEach((val, index) => { dice.forEach((val, index) => {
if (index === 0) { if (index === 0) {
@ -145,16 +60,103 @@ function getCombatTechniqueLevel(Player = {}, CombatTechnique = {}) {
Leiteigenschaft: CombatTechnique.Leiteigenschaft, Leiteigenschaft: CombatTechnique.Leiteigenschaft,
}; };
} }
return null;
} }
function getWeapon(Weapon = '') { function getWeapon(Weapon = '') {
if (Weapon) return Weapons.find(
return globals.Weapons.find(
w => w.id === Weapon.toLowerCase() || w.name.toLowerCase() === Weapon.toLowerCase() w => w.id === Weapon.toLowerCase() || w.name.toLowerCase() === Weapon.toLowerCase()
); );
} }
function isMeleeWeapon(Weapon) { function isMeleeWeapon(Weapon) {
if (globals.MeleeWeapons.find(MeleeWeapon => MeleeWeapon.id === Weapon.id)) return true; if (MeleeWeapons.find(MeleeWeapon => MeleeWeapon.id === Weapon.id)) return true;
else return false; return false;
} }
function handleAttack(doc, { message, args }) {
if (isEmpty(doc)) {
return message.reply(findMessage('NOENTRY'));
}
const Player = doc.character;
const Weapon = getWeapon(args[0]);
if (!Weapon) {
return message.reply(findMessage('NO_SUCH_WEAPON'));
}
// Determining Both Attack and Ranged Attack Values.
const CombatTechnique = getCombatTechniqueLevel(Player, getCombatTechnique(Weapon)); //?+
const Attribute = isMeleeWeapon(Weapon)
? getAttributeLevel(Player, 'mut')
: getAttributeLevel(Player, 'fingerfertigkeit');
let AttackValue = isMeleeWeapon(Weapon)
? CombatTechnique.level + Weapon.at_mod
: CombatTechnique.level;
AttackValue += Math.floor((Attribute - 8) / 3);
const { dice } = roll(2, 20);
const Bonus = parseInt(args[1], 10) || 0;
const Comparison = Math.floor(AttackValue + Bonus);
const AttackResult = CompareAttackResult(dice, Comparison);
let Reply = `Du greifst mit ${Weapon.name} an.\n Dein Angriffswert für ${CombatTechnique.name} ist ${AttackValue} (KtW: ${CombatTechnique.level})\n`;
Reply += `Deine 🎲: \` ${AttackResult.Dice.join(', ')} \`\n\n`;
Reply += !AttackResult.Ok ? findMessage('COMBAT_FAIL') : findMessage('COMBAT_SUCCESS');
Reply += AttackResult.Patzer ? findMessage('COMBAT_CRIT_FAIL') : '';
Reply += AttackResult.CriticalHit ? findMessage('COMBAT_CRIT_SUCCESS') : '';
Reply += AttackResult.DoubleDamage ? findMessage('COMBAT_DOUBLEDAMAGE') : '';
if (AttackResult.Ok) {
// adding 1 to damage for every point above weapon's "Leiteigenschaft"
// applies only to Melee Weapons.
let AttackBonus = 0;
if (isMeleeWeapon(Weapon) && Weapon.DmgThreshold) {
CombatTechnique.Leiteigenschaft.forEach(abbr => {
const attrib = getAttribute(abbr);
const AttributeValue = getAttributeLevel(Player, attrib.id);
if (Weapon.DmgThreshold < AttributeValue) {
AttackBonus += Math.floor(AttributeValue - Weapon.DmgThreshold);
}
});
}
const DamageDice = roll(1, 6).dice;
let Damage = Weapon.diemodificator + AttackBonus + DamageDice.reduce((p, v) => p + v);
Damage = AttackResult.DoubleDamage ? (Damage *= 2) : Damage;
Reply += '\n\nHier aufklappen, wenn der Gegner nicht parieren/Ausweichen konnte:\n';
Reply += `||\n`;
Reply += ` ${Weapon.name} (${Weapon.dice}W6+${
Weapon.diemodificator
}) richtet ${Damage} schaden an. ${
AttackBonus ? `(+${AttackBonus} Bonus auf Leiteigenschaft)` : ''
}`;
Reply += `\nDeine 🎲: ${DamageDice.join(', ')}\n||\n`;
}
return message.reply(Reply);
}
module.exports = {
name: 'attack',
description: 'Würfelt den Attackewert auf eine Nahkampfwaffe.',
aliases: ['angriff', 'attacke'],
usage: '<Waffe>',
needs_args: true,
async exec(message, args) {
db.findOne({ user: message.author.tag })
.then(doc => {
handleAttack(doc, { message, args });
})
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
});
},
};

View File

@ -1,17 +1,41 @@
require('module-alias/register'); require('module-alias/register');
const globals = require('../globals');
const db = globals.db;
const { roll } = require('@dsabot/Roll'); const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const { CompareResults } = require('@dsabot/CompareResults'); const { CompareResults } = require('@dsabot/CompareResults');
const { isEmpty } = require('@dsabot/isEmpty');
const { isString } = require('@dsabot/isString');
const { db } = require('../globals');
const { Werte } = require('../globals');
function handleAttributeCheck(docs, { message, args }) { function getAttributeLevel(Character = {}, Attribute = {}) {
let Attribute = isNaN(args[0]) return Character.attributes.find(attribute => attribute.id === Attribute.id).level;
? HandleNamedAttributes({ Character: docs[0].character, args: args }) }
function getAttribute(attribute = '') {
return attribute.length === 2
? Werte.find(a => a.kuerzel === attribute.toUpperCase())
: Werte.find(a => a.name.toLowerCase() === attribute.toLowerCase());
}
function HandleNamedAttributes({ Character = {}, args = [] } = {}) {
const Attribute = getAttribute(args[0]);
const Level = getAttributeLevel(Character, Attribute) || 8;
return {
Name: Attribute.name,
Level,
};
}
function handleAttributeCheck(doc, { message, args }) {
if (isEmpty(doc)) {
return message.reply(findMessage('NOENTRY'));
}
const Attribute = isString(args[0])
? HandleNamedAttributes({ Character: doc.character, args: args })
: null; : null;
let Level = Attribute ? Attribute.Level : args[0] || 8; const Level = Attribute ? Attribute.Level : args[0] || 8;
let Bonus = parseInt(args[1]) || 0; const Bonus = parseInt(args[1], 10) || 0;
let dice = roll(2, 20, message.author.tag).dice; const { dice } = roll(2, 20, message.author.tag);
const Result = CompareResults(dice, [Level, Level], Bonus); const Result = CompareResults(dice, [Level, Level], Bonus);
// handle crits // handle crits
@ -48,27 +72,6 @@ function handleAttributeCheck(docs, { message, args }) {
}` }`
); );
} }
function HandleNamedAttributes({ Character: Character = [], args: args = [] } = {}) {
let Attribute = getAttribute(args[0]);
let Level = getAttributeLevel(Character, Attribute) || 8;
return {
Name: Attribute.name,
Level: Level,
};
}
function getAttributeLevel(Character = {}, Attribute = {}) {
return Character.attributes.find(attribute => attribute.id === Attribute.id).level;
}
function getAttribute(attribute = '') {
return attribute.length === 2
? globals.Werte.find(a => a.kuerzel === attribute.toUpperCase())
: globals.Werte.find(a => a.name.toLowerCase() === attribute.toLowerCase());
}
module.exports = { module.exports = {
name: 'attribute', name: 'attribute',
description: '', description: '',
@ -76,13 +79,11 @@ module.exports = {
usage: '<Eigenschaft> / <Eigenschaftswert>', usage: '<Eigenschaft> / <Eigenschaftswert>',
needs_args: true, needs_args: true,
async exec(message, args) { async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => { db.findOne({ user: message.author.tag })
if (err) { .then(doc => handleAttributeCheck(doc, { message, args }))
.catch(err => {
message.reply(findMessage('ERROR')); message.reply(findMessage('ERROR'));
throw new Error(err); throw new Error(err);
}
handleAttributeCheck(docs, { message, args });
}); });
}, },
}; };

View File

@ -1,12 +1,16 @@
const globals = require('../globals');
const Discord = require('discord.js'); const Discord = require('discord.js');
const db = globals.db;
const { roll } = require('@dsabot/Roll'); const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const { getSpell } = require('@dsabot/getSpell'); const { getSpell } = require('@dsabot/getSpell');
const { CalculateQuality } = require('@dsabot/CalculateQuality'); const { CalculateQuality } = require('@dsabot/CalculateQuality');
const { CompareResults } = require('@dsabot/CompareResults'); const { CompareResults } = require('@dsabot/CompareResults');
const { CreateResultTable, f } = require('@dsabot/CreateResultTable'); const { CreateResultTable, f } = require('@dsabot/CreateResultTable');
const { isEmpty } = require('@dsabot/isEmpty');
const { isString } = require('@dsabot/isString');
const { db } = require('../globals');
module.exports = { module.exports = {
name: 'cast', name: 'cast',
description: description:
@ -17,25 +21,33 @@ module.exports = {
usage: '<Zaubern> [<-Erschwernis> / <+Erleichterung>]', usage: '<Zaubern> [<-Erschwernis> / <+Erleichterung>]',
needs_args: false, needs_args: false,
async exec(message, args) { async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => { db.findOne({ user: message.author.tag })
if (docs.length === 0) { .then(doc => {
if (isEmpty(doc)) {
return message.reply(findMessage('NOENTRY')); return message.reply(findMessage('NOENTRY'));
} }
if (!docs[0].character.hasOwnProperty('spells')) return message.reply(findMessage('NO_SPELLS')); if (!doc.character.hasOwnProperty('spells'))
if (!isNaN(args[0])) { return message.reply(findMessage('NO_SPELLS'));
if (!isString(args[0])) {
return message.reply(findMessage('WRONG_ARGUMENTS')); return message.reply(findMessage('WRONG_ARGUMENTS'));
} }
const Spell = getSpell({ Character: docs[0].character, spell_name: args[0] }); const Spell = getSpell({ Character: doc.character, spell_name: args[0] });
if (!Spell) { if (!Spell) {
return message.reply(findMessage('SPELL_UNKNOWN')); return message.reply(findMessage('SPELL_UNKNOWN'));
} }
if (!Spell.Level || !Spell.Attributes) { if (!Spell.Level || !Spell.Attributes) {
return; return null;
} }
const Attributes = Spell.Attributes; const { Attributes } = Spell;
const DiceThrow = roll(3, 20, message.author.tag).dice; const DiceThrow = roll(3, 20, message.author.tag).dice;
const Bonus = parseInt(args[1]) || 0; const Bonus = parseInt(args[1], 10) || 0;
let { Passed, CriticalHit, Fumbles, PointsUsed, PointsRemaining } = CompareResults( const {
Passed,
CriticalHit,
Fumbles,
PointsUsed,
PointsRemaining,
} = CompareResults(
DiceThrow, DiceThrow,
Attributes.map(attr => attr.Level), Attributes.map(attr => attr.Level),
Bonus, Bonus,
@ -71,20 +83,26 @@ module.exports = {
} else if (Passed < 3) { } else if (Passed < 3) {
Reply.addFields({ Reply.addFields({
name: findMessage('TITLE_FAILURE'), name: findMessage('TITLE_FAILURE'),
value: `${Passed === 0 ? 'Keine Probe' : `nur ${Passed}/3 Proben`} erfolgreich. 😪`, value: `${
Passed === 0 ? 'Keine Probe' : `nur ${Passed}/3 Proben`
} erfolgreich. 😪`,
inline: false, inline: false,
}); });
} else { } else {
Reply.addFields({ Reply.addFields({
name: findMessage('TITLE_SUCCESS'), name: findMessage('TITLE_SUCCESS'),
value: `Dein verbleibender Bonus: ${PointsRemaining}/${Spell.Level} (QS${CalculateQuality( value: `Dein verbleibender Bonus: ${PointsRemaining}/${
PointsRemaining Spell.Level
)})`, } (QS${CalculateQuality(PointsRemaining)})`,
inline: false, inline: false,
}); });
} }
message.reply(Reply); return message.reply(Reply);
})
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
}); });
}, },
}; };

View File

@ -1,12 +1,15 @@
const globals = require('../globals');
const Discord = require('discord.js'); const Discord = require('discord.js');
const db = globals.db;
const { roll } = require('@dsabot/Roll'); const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const { getChant } = require('@dsabot/getChant'); const { getChant } = require('@dsabot/getChant');
const { CalculateQuality } = require('@dsabot/CalculateQuality'); const { CalculateQuality } = require('@dsabot/CalculateQuality');
const { CompareResults } = require('@dsabot/CompareResults'); const { CompareResults } = require('@dsabot/CompareResults');
const { CreateResultTable, f } = require('@dsabot/CreateResultTable'); const { CreateResultTable, f } = require('@dsabot/CreateResultTable');
const { isEmpty } = require('@dsabot/isEmpty');
const { isString } = require('@dsabot/isString');
const { db } = require('../globals');
module.exports = { module.exports = {
name: 'chant', name: 'chant',
description: description:
@ -17,25 +20,33 @@ module.exports = {
usage: '<Liturgie/Zeremonie> [<-Erschwernis> / <+Erleichterung>]', usage: '<Liturgie/Zeremonie> [<-Erschwernis> / <+Erleichterung>]',
needs_args: false, needs_args: false,
async exec(message, args) { async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => { db.findOne({ user: message.author.tag })
if (docs.length === 0) { .then(doc => {
if (isEmpty(doc)) {
return message.reply(findMessage('NOENTRY')); return message.reply(findMessage('NOENTRY'));
} }
if (!docs[0].character.hasOwnProperty('chants')) return message.reply(findMessage('NO_CHANTS')); if (!doc.character.hasOwnProperty('chants'))
if (!isNaN(args[0])) { return message.reply(findMessage('NO_CHANTS'));
if (!isString(args[0])) {
return message.reply(findMessage('WRONG_ARGUMENTS')); return message.reply(findMessage('WRONG_ARGUMENTS'));
} }
const Chant = getChant({ Character: docs[0].character, chant_name: args[0] }); const Chant = getChant({ Character: doc.character, chant_name: args[0] });
if (!Chant) { if (!Chant) {
return message.reply(findMessage('CHANT_UNKNOWN')); return message.reply(findMessage('CHANT_UNKNOWN'));
} }
if (!Chant.Level || !Chant.Attributes) { if (!Chant.Level || !Chant.Attributes) {
return; return null;
} }
const Attributes = Chant.Attributes; const { Attributes } = Chant;
const DiceThrow = roll(3, 20, message.author.tag).dice; const DiceThrow = roll(3, 20, message.author.tag).dice;
const Bonus = parseInt(args[1]) || 0; const Bonus = parseInt(args[1], 10) || 0;
let { Passed, CriticalHit, Fumbles, PointsUsed, PointsRemaining } = CompareResults( const {
Passed,
CriticalHit,
Fumbles,
PointsUsed,
PointsRemaining,
} = CompareResults(
DiceThrow, DiceThrow,
Attributes.map(attr => attr.Level), Attributes.map(attr => attr.Level),
Bonus, Bonus,
@ -71,19 +82,25 @@ module.exports = {
} else if (Passed < 3) { } else if (Passed < 3) {
Reply.addFields({ Reply.addFields({
name: findMessage('TITLE_FAILURE'), name: findMessage('TITLE_FAILURE'),
value: `${Passed === 0 ? 'Keine Probe' : `nur ${Passed}/3 Proben`} erfolgreich. 😪`, value: `${
Passed === 0 ? 'Keine Probe' : `nur ${Passed}/3 Proben`
} erfolgreich. 😪`,
inline: false, inline: false,
}); });
} else { } else {
Reply.addFields({ Reply.addFields({
name: findMessage('TITLE_SUCCESS'), name: findMessage('TITLE_SUCCESS'),
value: `Dein verbleibender Bonus: ${PointsRemaining}/${Chant.Level} (QS${CalculateQuality( value: `Dein verbleibender Bonus: ${PointsRemaining}/${
PointsRemaining Chant.Level
)})`, } (QS${CalculateQuality(PointsRemaining)})`,
inline: false, inline: false,
}); });
} }
message.reply(Reply); return message.reply(Reply);
})
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
}); });
}, },
}; };

View File

@ -1,9 +1,34 @@
//const globals = require('../globals');
const globals = require('../globals');
const Discord = require('discord.js'); const Discord = require('discord.js');
const db = globals.db;
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const { getChant } = require('@dsabot/getChant'); const { getChant } = require('@dsabot/getChant');
const { isEmpty } = require('@dsabot/isEmpty');
const { db } = require('../globals');
const createChantList = (Character = {}) => {
if (!Character || !Character.hasOwnProperty('chants')) return null;
const ChantList = [];
Character.chants.forEach(chant =>
ChantList.push(getChant({ Character: Character, chant_name: chant.id }))
);
return ChantList.filter(value => value !== undefined);
};
const ReplyChantList = (ChantList = []) => {
if (!ChantList) return null;
return `${ChantList.map(chant => `${chant.Name} ${chant.Level ? `(${chant.Level})` : ''}`).join(
'\n'
)}`;
};
const ReplyChant = (Chant = {}) => {
if (!Chant) return null;
return `Deine Werte für ${Chant.Name} ${Chant.Level ? `(${Chant.Level})` : ''} sind:
${Chant.Attributes.map(attribute => `${attribute.Name}: ${attribute.Level}`).join(' ')}
`;
};
module.exports = { module.exports = {
name: 'chants', name: 'chants',
description: 'Zeigt dir deinen Fertigkeitswert im jeweiligen Magietalent (Götterwirken).', description: 'Zeigt dir deinen Fertigkeitswert im jeweiligen Magietalent (Götterwirken).',
@ -12,12 +37,14 @@ module.exports = {
needs_args: false, needs_args: false,
async exec(message, args) { async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => { db.findOne({ user: message.author.tag })
if (docs.length === 0) { .then(doc => {
if (isEmpty(doc)) {
return message.reply(findMessage('NOENTRY')); return message.reply(findMessage('NOENTRY'));
} }
const Character = docs[0].character; const Character = doc.character;
if (!Character.hasOwnProperty('chants')) return message.reply(findMessage('NO_CHANTS')); if (!Character.hasOwnProperty('chants'))
return message.reply(findMessage('NO_CHANTS'));
if (args.length === 0) { if (args.length === 0) {
const Embed = new Discord.MessageEmbed() const Embed = new Discord.MessageEmbed()
.setColor('#0099ff') .setColor('#0099ff')
@ -34,28 +61,10 @@ module.exports = {
return message.reply(findMessage('SPELL_UNKNOWN')); return message.reply(findMessage('SPELL_UNKNOWN'));
} }
return message.reply(ReplyChant(Chant)); return message.reply(ReplyChant(Chant));
})
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
}); });
}, },
}; };
const createChantList = (Character = {}) => {
if (!Character || !Character.hasOwnProperty('chants')) return;
let ChantList = [];
// todo: send 'chant' to getChant() so we can filter out blessings.
Character.chants.forEach(chant => ChantList.push(getChant({ Character: Character, chant_name: chant.id })));
return ChantList.filter(value => value !== undefined);
};
const ReplyChantList = (ChantList = []) => {
if (!ChantList) return;
return `${ChantList.map(chant => `${chant.Name} ${chant.Level ? `(${chant.Level})` : ''}`).join('\n')}`;
};
const ReplyChant = (Chant = {}) => {
if (!Chant) return;
return `Deine Werte für ${Chant.Name} ${Chant.Level ? '(' + Chant.Level + ')' : ''} sind:
${Chant.Attributes.map(attribute => `${attribute.Name}: ${attribute.Level}`).join(' ')}
`;
};

View File

@ -1,6 +1,6 @@
const globals = require('../globals');
const { roll } = require('@dsabot/Roll'); const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const { Coin } = require('../globals');
module.exports = { module.exports = {
name: 'kopf', name: 'kopf',
@ -9,8 +9,8 @@ module.exports = {
usage: '', usage: '',
needs_args: false, needs_args: false,
async exec(message, args) { async exec(message) {
const coin = roll(1,2,message.author.tag).dice; const { dice } = roll(1, 2, message.author.tag);
message.reply(`${findMessage('HEADS_OR_TAILS')} **${globals.Coin[(coin-1)]}**.`); message.reply(`${findMessage('HEADS_OR_TAILS')} **${Coin[dice - 1]}**.`);
}, },
}; };

87
commands/List.js Normal file
View File

@ -0,0 +1,87 @@
require('module-alias/register');
const { findMessage } = require('@dsabot/findMessage');
const { isEmpty } = require('@dsabot/isEmpty');
const { db } = require('../globals');
const { Werte } = require('../globals');
async function findUser(request = '') {
return db
.findOne({
$or: [
{ user: request.replace('@', '') },
{ uid: request.replaceAll(/[<>!@]/gi, '') },
{ character: { name: request } },
],
})
.then(doc => doc);
}
function doHeading(attributes) {
return `${''.padStart(25)}${attributes
.map(a => `${a.Short}`.padEnd(4).padStart(6))
.join('|')}\n`;
}
function listStats(attributes) {
return `${attributes.map(a => `${a.Level}`.padEnd(4).padStart(6)).join('|')}\n`;
}
function getAttribute(attribute_request = { id: 'mut', level: 9 }) {
const Attribute = Werte.find(a => a.id === attribute_request.id);
return {
id: Attribute.id,
Name: Attribute.name,
Short: Attribute.kuerzel,
Level: attribute_request.level,
};
}
function getStats(user) {
const Attributes = [];
user.character.attributes.forEach(attribute => {
Attributes.push(getAttribute(attribute));
});
Attributes.sort((a, b) => (a.id > b.id ? 1 : a.id < b.id ? -1 : 0));
return Attributes;
}
module.exports = {
name: 'list',
description: 'Gibt eine Liste von Mitspielern aus.',
aliases: ['liste'],
usage: '',
needs_args: false,
exec: async (message, args) => {
if (!args) return;
console.log(args[0].replaceAll(/[<>!@]/gi, ''));
const Characters = []; //?+
Promise.all(
args.map(arg => {
return findUser(arg).then(user => {
if (!isEmpty(user)) {
Characters.push({
Name: user.character.name,
Attributes: getStats(user),
});
}
});
})
).then(() => {
if (isEmpty(Characters)) return findMessage('NO_CHARACTERS');
let Reply = `\`\`\`\n${doHeading(Characters[0].Attributes)}`;
Characters.forEach(c => {
Reply += `${c.Name.toString().padEnd(24)} ${listStats(c.Attributes)}`;
});
Reply += `\`\`\``;
return message.reply(Reply);
});
},
};
/*
(async () => {
db.loadDatabase();
const l = require('./List');
const msg = { author: { tag: 'tagged!' }, reply: e => console.log(e) };
l.exec(msg, ['tobenderzephyr#2509', 'ElManu#8438']);
})();
*/

View File

@ -1,6 +1,12 @@
const globals = require('../globals');
const db = globals.db;
const Random = require('random'); const Random = require('random');
const { findMessage } = require('@dsabot/findMessage');
const { isEmpty } = require('@dsabot/isEmpty');
const { db } = require('../globals');
const { Werte } = require('../globals');
const { Weapons } = require('../globals');
const { CombatTechniques } = require('../globals');
const { MeleeWeapons } = require('../globals');
module.exports = { module.exports = {
name: 'parry', name: 'parry',
@ -10,76 +16,92 @@ module.exports = {
needs_args: true, needs_args: true,
async exec(message, args) { async exec(message, args) {
try { db.find({ user: message.author.tag }).then(docs => {
db.find({ if (isEmpty(docs)) {
user: message.author.tag, return message.reply(findMessage('NOENTRY'));
}, function(err, docs) {
if (docs.length === 0) {
return message.reply(globals.Replies.find(r => r.id === 'NOENTRY').string);
} }
else {
Random.use(message.author.tag); Random.use(message.author.tag);
const Player = docs[0].character; const Player = docs[0].character;
const Weapon = globals.Weapons.find(w => w.id === args[0].toLowerCase()); const Weapon = Weapons.find(w => w.id === args[0].toLowerCase());
if(!Weapon) { return message.reply(globals.Replies.find(r => r.id === 'NO_SUCH_WEAPON').string);} if (!Weapon) {
return message.reply(findMessage('NO_SUCH_WEAPON'));
if(!globals.MeleeWeapons.find(MeleeWeapon => MeleeWeapon.id === Weapon.id)) {
return message.reply(globals.Replies.find(r => r.id === 'PARRY_WRONG_WEAPON').string);
} }
const CombatTechnique = globals.CombatTechniques.find(technique => technique.id === Weapon.combattechnique);
let PlayerCombatTechnique = Player.combattechniques.find(technique => technique.id === CombatTechnique.id); if (!MeleeWeapons.find(MeleeWeapon => MeleeWeapon.id === Weapon.id)) {
return message.reply(findMessage('PARRY_WRONG_WEAPON'));
}
const CombatTechnique = CombatTechniques.find(
technique => technique.id === Weapon.combattechnique
);
const PlayerCombatTechnique = Player.combattechniques.find(
technique => technique.id === CombatTechnique.id
);
let CombatTechniqueValue = null; let CombatTechniqueValue = null;
if (PlayerCombatTechnique) { CombatTechniqueValue = PlayerCombatTechnique.level; } if (PlayerCombatTechnique) {
if(!CombatTechniqueValue) { CombatTechniqueValue = 6; } CombatTechniqueValue = PlayerCombatTechnique.level;
}
if (!CombatTechniqueValue) {
CombatTechniqueValue = 6;
}
let ParryValue = Math.ceil(CombatTechniqueValue / 2); let ParryValue = Math.ceil(CombatTechniqueValue / 2);
CombatTechniqueValue.Leiteigenschaft.forEach(Property => { CombatTechniqueValue.Leiteigenschaft.forEach(Property => {
let Attribute = globals.Werte.find(a => a.kuerzel === Property.id); const Attribute = Werte.find(a => a.kuerzel === Property.id);
ParryValue += Math.floor((Player.attributes.find(a => a.id === Attribute).level - 8)/3); ParryValue += Math.floor(
(Player.attributes.find(a => a.id === Attribute).level - 8) / 3
);
}); });
ParryValue += Weapon.pa_mod; ParryValue += Weapon.pa_mod;
let dice = []; const dice = [];
let Bonus = 0;
if(args[1] && !isNaN(parseInt(args[1]))) { Bonus = parseInt(args[1]); } const Bonus = parseInt(args[1], 10) || 0;
let Comparison = Math.floor(ParryValue + Bonus);
const Comparison = Math.floor(ParryValue + Bonus);
let Patzer = false; let Patzer = false;
let Critical = false; let Critical = false;
let Ok = false; let Ok = false;
for (let i = 0; i < 2; i++) { for (let i = 0; i < 2; i += 1) {
dice.push(Random.int(1, 20)); dice.push(Random.int(1, 20));
} }
// If there is a cleaner way to do these checks, I'm all into it. // If there is a cleaner way to do these checks, I'm all into it.
if((dice[0] == 1) && dice[1] <= Comparison) { Critical = true; Ok = true; } if (dice[0] === 1 && dice[1] <= Comparison) {
else if(dice[0] <= Comparison && !Critical) { Ok = true; dice.pop(); } Critical = true;
else if((dice[0] == 20) && dice[1] > Comparison) { Patzer = true; } Ok = true;
else if(dice[0] > Comparison ) { dice.pop(); } } else if (dice[0] <= Comparison && !Critical) {
Ok = true;
dice.pop();
} else if (dice[0] === 20 && dice[1] > Comparison) {
Patzer = true;
} else if (dice[0] > Comparison) {
dice.pop();
}
let Reply = `Du versuchst, mit ${Weapon.name} zu parieren.\n`;
let Reply = 'Du versuchst, mit ' + globals.Declination[Weapon.article] + ' ' + Weapon.name + ' zu parieren.\n'; Reply += `Dein Paradewert für ${CombatTechnique.name} ist ${Math.floor(
Reply += 'Dein Paradewert für ' + CombatTechnique.name + ' ist ' + Math.floor(ParryValue - Weapon.pa_mod) + '. (Waffe: ' + Weapon.pa_mod + ')\n'; ParryValue - Weapon.pa_mod
Reply += 'Deine 🎲: ` ' + dice.join(', ') + ' `.\n\n'; )}. (Waffe ${Weapon.pa_mod})\n`;
Reply += `Deine 🎲: ${dice.join(', ')}\n\n`;
if (!Ok) { if (!Ok) {
Reply += globals.Replies.find(reply => reply.id === 'PARRY_FAIL').string; Reply += findMessage('PARRY_FAIL');
if(Patzer) { Reply += globals.Replies.find(reply => reply.id === 'PARRY_CRIT_FAIL').string; } if (Patzer) {
Reply += findMessage('PARRY_CRIT_FAIL');
}
} else {
if (Critical) {
Reply += findMessage('PARRY_CRIT_SUCCESS');
}
if (!Critical) {
Reply += findMessage('PARRY_SUCCESS');
} }
else {
if(Critical) { Reply += globals.Replies.find(reply => reply.id === 'PARRY_CRIT_SUCCESS').string; }
if(!Critical) { Reply += globals.Replies.find(reply => reply.id === 'PARRY_SUCCESS').string; }
} }
return message.reply(Reply); return message.reply(Reply);
}
}); });
}
catch (e) {
throw e;
}
}, },
}; };

View File

@ -1,6 +1,6 @@
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const globals = require('../globals'); const { db } = require('../globals');
const db = globals.db;
module.exports = { module.exports = {
name: 'remove', name: 'remove',
description: description:
@ -9,13 +9,12 @@ module.exports = {
usage: '', usage: '',
needs_args: false, needs_args: false,
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
async exec(message, args) { async exec(message) {
db.remove({ user: message.author.tag }, err => { db.remove({ user: message.author.tag })
if (err) { .then(() => message.reply(findMessage('DELETED_DATA')))
.catch(err => {
message.reply(findMessage('ERROR')); message.reply(findMessage('ERROR'));
throw new Error(err); throw new Error(err);
}
return message.reply(findMessage('DELETED_DATA'));
}); });
}, },
}; };

View File

@ -1,24 +1,28 @@
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
const globals = require('../globals');
const { roll } = require('@dsabot/Roll'); const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const { DiceRegex } = require('../globals');
module.exports = { module.exports = {
name: 'roll', name: 'roll',
description: 'Lass die Würfel rollen. Benötigt wird die Anzahl sowie die Augenzahl auf den Würfeln.', description:
'Lass die Würfel rollen. Benötigt wird die Anzahl sowie die Augenzahl auf den Würfeln.',
aliases: ['r'], aliases: ['r'],
usage: '<Anzahl> w <Augenzahl>', usage: '<Anzahl> w <Augenzahl>',
needs_args: true, needs_args: true,
async exec(message, args) { async exec(message, args) {
let params = args.join('').split(globals.DiceRegex); const params = args.join('').split(DiceRegex);
if (params.length >= 2) { if (params.length >= 2) {
const Bonus = parseInt(params[2]) || 0; const Bonus = parseInt(params[2], 10) || 0;
const numberOfDice = parseInt( params[0] ); const numberOfDice = parseInt(params[0], 10);
const diceValues = parseInt( params[1] ); const diceValues = parseInt(params[1], 10);
const result = roll(numberOfDice, diceValues, message.author.tag); const result = roll(numberOfDice, diceValues, message.author.tag);
let total = (Bonus ? Bonus + result.sum : result.sum) const total = Bonus ? Bonus + result.sum : result.sum;
message.reply(`${findMessage('ROLL')} ${result.dice.join(', ')} `+ message.reply(
`(Gesamt: ${result.sum}${Bonus ? `+${Bonus}=${total}` : ``})` ); `${findMessage('ROLL')} ${result.dice.join(', ')} ` +
`(Gesamt: ${result.sum}${Bonus ? `+${Bonus}=${total}` : ``})`
);
} }
}, },
}; };

View File

@ -1,8 +1,8 @@
// eslint-disable-next-line no-unused-vars
const globals = require('../globals');
const Discord = require('discord.js'); const Discord = require('discord.js');
const db = globals.db;
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const { isEmpty } = require('@dsabot/isEmpty');
const { db } = require('../globals');
module.exports = { module.exports = {
name: 'show', name: 'show',
@ -13,22 +13,15 @@ module.exports = {
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
async exec(message, args) { async exec(message, args) {
try { db.find({ user: message.author.tag })
db.find( .then(docs => {
{ if (isEmpty(docs)) {
user: message.author.tag,
},
function (err, docs) {
if (docs.length === 0) {
return message.reply(findMessage('NOENTRY')); return message.reply(findMessage('NOENTRY'));
} else {
const Character = docs[0].character;
let Gender;
if (Character.sex == 'female') {
Gender = '♀️';
} else {
Gender = '♂️';
} }
const Character = docs[0].character;
const Gender = Character.sex === 'female' ? '♀️' : '♂️';
const Reply = new Discord.MessageEmbed(); const Reply = new Discord.MessageEmbed();
Reply.setColor('#0099ff'); Reply.setColor('#0099ff');
Reply.setTitle(`${Gender} ${Character.name}`); Reply.setTitle(`${Gender} ${Character.name}`);
@ -37,13 +30,11 @@ module.exports = {
); );
Reply.addField(Character.professionname, Character.xp.startinglevel); Reply.addField(Character.professionname, Character.xp.startinglevel);
message.reply(Reply); return message.reply(Reply);
} })
} .catch(err => {
);
} catch (e) {
message.reply(findMessage('ERROR')); message.reply(findMessage('ERROR'));
throw e; throw new Error(err);
} });
}, },
}; };

View File

@ -1,7 +1,8 @@
const globals = require('../globals');
const db = globals.db;
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const { getSkill } = require('@dsabot/getSkill'); const { getSkill } = require('@dsabot/getSkill');
const { isEmpty } = require('@dsabot/isEmpty');
const { db } = require('../globals');
module.exports = { module.exports = {
name: 'skill', name: 'skill',
description: 'Zeigt dir deinen Fertigkeitswert im jeweiligen Talent.', description: 'Zeigt dir deinen Fertigkeitswert im jeweiligen Talent.',
@ -10,8 +11,9 @@ module.exports = {
needs_args: true, needs_args: true,
async exec(message, args) { async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => { db.find({ user: message.author.tag })
if (docs.length === 0) { .then(docs => {
if (isEmpty(docs)) {
return message.reply(findMessage('NOENTRY')); return message.reply(findMessage('NOENTRY'));
} }
const Skill = getSkill({ Character: docs[0].character, args: args }); const Skill = getSkill({ Character: docs[0].character, args: args });
@ -19,6 +21,10 @@ module.exports = {
return message.reply(findMessage('TALENT_UNKNOWN')); return message.reply(findMessage('TALENT_UNKNOWN'));
} }
return message.reply(`Du hast folgenden Wert in **${Skill.Name}**: ${Skill.Level}`); return message.reply(`Du hast folgenden Wert in **${Skill.Name}**: ${Skill.Level}`);
})
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
}); });
}, },
}; };

View File

@ -1,9 +1,30 @@
//const globals = require('../globals');
const globals = require('../globals');
const db = globals.db;
const Discord = require('discord.js'); const Discord = require('discord.js');
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const { getSpell } = require('@dsabot/getSpell'); const { getSpell } = require('@dsabot/getSpell');
const { db } = require('../globals');
const ReplySpellList = (SpellList = []) => {
if (!SpellList) return findMessage('NO_SPELLS');
return `${SpellList.map(s => `${s.Name} (${s.Level})`).join('\n')}`;
};
const ReplySpell = (Spell = {}) => {
if (!Spell) return null;
return `Deine Werte für ${Spell.Name} (${Spell.Level}) sind:
${Spell.Attributes.map(attribute => `${attribute.Name}: ${attribute.Level}`).join(' ')}
`;
};
const createSpellList = (Character = {}) => {
if (!Character || !Character.hasOwnProperty('spells')) return null;
const SpellList = [];
Character.spells.forEach(spell =>
SpellList.push(getSpell({ Character: Character, spell_name: spell.id }))
);
return SpellList.filter(value => value !== undefined); //?+
};
module.exports = { module.exports = {
name: 'spells', name: 'spells',
description: 'Zeigt dir deinen Fertigkeitswert im jeweiligen Magietalent.', description: 'Zeigt dir deinen Fertigkeitswert im jeweiligen Magietalent.',
@ -12,12 +33,14 @@ module.exports = {
needs_args: false, needs_args: false,
async exec(message, args) { async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => { db.find({ user: message.author.tag })
.then(docs => {
if (docs.length === 0) { if (docs.length === 0) {
return message.reply(findMessage('NOENTRY')); return message.reply(findMessage('NOENTRY'));
} }
const Character = docs[0].character; const Character = docs[0].character;
if (!Character.hasOwnProperty('spells')) return message.reply(findMessage('NO_SPELLS')); if (!Character.hasOwnProperty('spells'))
return message.reply(findMessage('NO_SPELLS'));
if (args.length === 0) { if (args.length === 0) {
const Embed = new Discord.MessageEmbed() const Embed = new Discord.MessageEmbed()
.setColor('#0099ff') .setColor('#0099ff')
@ -32,28 +55,10 @@ module.exports = {
}); });
if (!Spell) return message.reply(findMessage('SPELL_UNKNOWN')); if (!Spell) return message.reply(findMessage('SPELL_UNKNOWN'));
return message.reply(ReplySpell(Spell)); return message.reply(ReplySpell(Spell));
})
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
}); });
}, },
}; };
const ReplySpellList = (SpellList = []) => {
if (!SpellList) return findMessage('NO_SPELLS');
return `${SpellList.map(s => `${s.Name} (${s.Level})`).join('\n')}`;
};
const ReplySpell = (Spell = {}) => {
if (!Spell) return;
return `Deine Werte für ${Spell.Name} (${Spell.Level}) sind:
${Spell.Attributes.map(attribute => `${attribute.Name}: ${attribute.Level}`).join(' ')}
`;
};
const createSpellList = (Character = {}) => {
if (!Character || !Character.hasOwnProperty('spells')) return;
let SpellList = [];
Character.spells.forEach(spell =>
SpellList.push(getSpell({ Character: Character, spell_name: spell.id }))
);
return SpellList.filter(value => value !== undefined); //?+
};

View File

@ -1,12 +1,13 @@
const globals = require('../globals');
const Discord = require('discord.js'); const Discord = require('discord.js');
const db = globals.db;
const { roll } = require('@dsabot/Roll'); const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const { getSkill } = require('@dsabot/getSkill'); const { getSkill } = require('@dsabot/getSkill');
const { CalculateQuality } = require('@dsabot/CalculateQuality'); const { CalculateQuality } = require('@dsabot/CalculateQuality');
const { CompareResults } = require('@dsabot/CompareResults'); const { CompareResults } = require('@dsabot/CompareResults');
const { CreateResultTable } = require('@dsabot/CreateResultTable'); const { CreateResultTable } = require('@dsabot/CreateResultTable');
const { isString } = require('@dsabot/isString');
const { db } = require('../globals');
module.exports = { module.exports = {
name: 'talent', name: 'talent',
description: description:
@ -17,11 +18,12 @@ module.exports = {
usage: '<Talent> [<-Erschwernis> / <+Erleichterung>]', usage: '<Talent> [<-Erschwernis> / <+Erleichterung>]',
needs_args: true, needs_args: true,
async exec(message, args) { async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => { db.find({ user: message.author.tag })
.then(docs => {
if (docs.length === 0) { if (docs.length === 0) {
return message.reply(findMessage('NOENTRY')); return message.reply(findMessage('NOENTRY'));
} }
if (!isNaN(args[0])) { if (!isString(args[0])) {
return message.reply(findMessage('WRONG_ARGUMENTS')); return message.reply(findMessage('WRONG_ARGUMENTS'));
} }
@ -30,10 +32,16 @@ module.exports = {
return message.reply(findMessage('TALENT_UNKNOWN')); return message.reply(findMessage('TALENT_UNKNOWN'));
} }
const Attributes = Skill.Attributes; const { Attributes } = Skill;
const DiceThrow = roll(3, 20, message.author.tag).dice; const DiceThrow = roll(3, 20, message.author.tag).dice;
const Bonus = parseInt(args[1]) || 0; const Bonus = parseInt(args[1], 10) || 0;
let { Passed, CriticalHit, Fumbles, PointsUsed, PointsRemaining } = CompareResults( const {
Passed,
CriticalHit,
Fumbles,
PointsUsed,
PointsRemaining,
} = CompareResults(
DiceThrow, DiceThrow,
Attributes.map(attr => attr.Level), Attributes.map(attr => attr.Level),
Bonus, Bonus,
@ -67,19 +75,25 @@ module.exports = {
} else if (Passed < 3) { } else if (Passed < 3) {
Reply.addFields({ Reply.addFields({
name: findMessage('TITLE_FAILURE'), name: findMessage('TITLE_FAILURE'),
value: `${Passed === 0 ? 'Keine Probe' : `nur ${Passed}/3 Proben`} erfolgreich. 😪`, value: `${
Passed === 0 ? 'Keine Probe' : `nur ${Passed}/3 Proben`
} erfolgreich. 😪`,
inline: false, inline: false,
}); });
} else { } else {
Reply.addFields({ Reply.addFields({
name: findMessage('TITLE_SUCCESS'), name: findMessage('TITLE_SUCCESS'),
value: `Dein verbleibender Bonus: ${PointsRemaining}/${Skill.Level} (QS${CalculateQuality( value: `Dein verbleibender Bonus: ${PointsRemaining}/${
PointsRemaining Skill.Level
)})`, } (QS${CalculateQuality(PointsRemaining)})`,
inline: false, inline: false,
}); });
} }
message.reply(Reply); return message.reply(Reply);
})
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
}); });
}, },
}; };

View File

@ -1,6 +1,23 @@
const globals = require('../globals');
const Discord = require('discord.js'); const Discord = require('discord.js');
const { Capitalize } = require('@dsabot/Capitalize'); const { Capitalize } = require('@dsabot/Capitalize');
const { TalentKategorien } = require('../globals');
const { Talente } = require('../globals');
const GenerateTalentList = () => {
const TalentList = [];
TalentKategorien.forEach(Category => {
TalentList.push({
Category: Category,
Talents: Talente.filter(
Talent => Talent.categoryid === TalentKategorien.indexOf(Category)
)
.map(Talent => Capitalize(Talent.id))
.sort(),
});
});
return TalentList.sort();
};
module.exports = { module.exports = {
name: 'talents', name: 'talents',
@ -9,34 +26,17 @@ module.exports = {
usage: '', usage: '',
needs_args: false, needs_args: false,
async exec(message, args) { async exec(message) {
const Embed = new Discord.MessageEmbed() const Embed = new Discord.MessageEmbed()
.setColor('#0099ff') .setColor('#0099ff')
.setTitle('Talentübersicht') .setTitle('Talentübersicht')
.setDescription('Das sind die Talente, die ich kenne:'); .setDescription('Das sind die Talente, die ich kenne:');
for (let Talent of GenerateTalentList()) {
const TalentList = GenerateTalentList();
TalentList.forEach(Talent => {
Embed.addField(Talent.Category, Talent.Talents.join('\n'), true); Embed.addField(Talent.Category, Talent.Talents.join('\n'), true);
} });
message.author.send(
Embed, return message.author.send(Embed);
);
}, },
}; };
const GenerateTalentList = () => {
const Categories = globals.TalentKategorien;
const Talents = globals.Talente;
const TalentList = [];
Categories.forEach(Category => {
TalentList.push({
Category: Category,
Talents: Talents.filter(Talent => Talent.categoryid === Categories.indexOf(Category))
.map(Talent => Capitalize(Talent.id))
.sort()
});
});
return TalentList.sort();
};

View File

@ -3,6 +3,7 @@ const Discord = require('discord.js');
const { roll } = require('@dsabot/Roll'); const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage'); const { findMessage } = require('@dsabot/findMessage');
const { CompareResults } = require('@dsabot/CompareResults'); const { CompareResults } = require('@dsabot/CompareResults');
module.exports = { module.exports = {
name: 'tp', name: 'tp',
description: description:
@ -15,20 +16,21 @@ module.exports = {
needs_args: true, needs_args: true,
async exec(message, args) { async exec(message, args) {
if (isNaN(args[0])) { if (Number.isNaN(args[0])) {
return message.reply(findMessage('WRONG_ARGUMENTS')); return message.reply(findMessage('WRONG_ARGUMENTS'));
} }
let Bonus = parseInt(args[3]) || 0; const Bonus = parseInt(args[3], 10) || 0;
let Erschwernis = parseInt(args[4]) || 0; const Erschwernis = parseInt(args[4], 10) || 0;
const dice = roll(3, 20, message.author.tag).dice; const { dice } = roll(3, 20, message.author.tag);
const { const { Passed, CriticalHit, Fumbles, PointsRemaining } = CompareResults(
Passed: Passed, dice,
CriticalHit: CriticalHit, [args[0], args[1], args[2]],
Fumbles: Fumbles, Bonus,
PointsRemaining: PointsRemaining} = CompareResults(dice, [args[0], args[1], args[2]], Bonus, Erschwernis); Erschwernis
);
const Reply = new Discord.MessageEmbed(); const Reply = new Discord.MessageEmbed();
Reply.setTitle(`${findMessage('ROLL')} ${dice.join(', ')}.`); Reply.setTitle(`${findMessage('ROLL')} ${dice.join(', ')}.`);
@ -59,6 +61,6 @@ module.exports = {
inline: false, inline: false,
}); });
} }
message.reply(Reply); return message.reply(Reply);
}, },
}; };

View File

@ -1,7 +1,20 @@
const globals = require('../globals');
const Discord = require('discord.js'); const Discord = require('discord.js');
const { Capitalize } = require('@dsabot/Capitalize'); const { Capitalize } = require('@dsabot/Capitalize');
const { CombatTechniques } = require('../globals');
const { Weapons } = require('../globals');
const GenerateWeaponList = () => {
const WeaponList = [];
CombatTechniques.forEach(Technique => {
WeaponList.push({
Technique_Name: Technique.name,
Weapons: Weapons.filter(Weapon => Weapon.combattechnique === Technique.id).map(Weapon =>
Capitalize(Weapon.id)
),
});
});
return WeaponList.sort();
};
module.exports = { module.exports = {
name: 'weapons', name: 'weapons',
@ -10,32 +23,16 @@ module.exports = {
usage: '', usage: '',
needs_args: false, needs_args: false,
async exec(message, args) { async exec(message) {
const Embed = new Discord.MessageEmbed() const Embed = new Discord.MessageEmbed()
.setColor('#0099ff') .setColor('#0099ff')
.setTitle('Waffenübersicht') .setTitle('Waffenübersicht')
.setDescription('Folgende Waffen können für einen Angriff genutzt werden:'); .setDescription('Folgende Waffen können für einen Angriff genutzt werden:');
for (let Technique of GenerateWeaponList()) { const WeaponList = GenerateWeaponList();
WeaponList.forEach(Technique => {
Embed.addField(Technique.Technique_Name, Technique.Weapons.join('\n'), true); Embed.addField(Technique.Technique_Name, Technique.Weapons.join('\n'), true);
} });
message.author.send(
Embed, return message.author.send(Embed);
);
}, },
}; };
const GenerateWeaponList = () => {
let WeaponList = [];
const Techniques = globals.CombatTechniques;
const Weapons = globals.Weapons;
Techniques.forEach(Technique => {
WeaponList.push({
Technique_Name: Technique.name,
Weapons: Weapons.filter(Weapon => Weapon.combattechnique === Technique.id)
.map(Weapon => Capitalize(Weapon.id))
});
});
return WeaponList.sort();
};

View File

@ -1,9 +1,9 @@
const CalculateQuality = (PointsAvailable = 0) => { const CalculateQuality = (PointsAvailable = 0) => {
if (PointsAvailable <= 3) return 1; if (PointsAvailable <= 3) return 1;
else if (PointsAvailable > 3 && PointsAvailable <= 6) return 2; if (PointsAvailable > 3 && PointsAvailable <= 6) return 2;
else if (PointsAvailable > 6 && PointsAvailable <= 9) return 3; if (PointsAvailable > 6 && PointsAvailable <= 9) return 3;
else if (PointsAvailable > 9 && PointsAvailable <= 12) return 4; if (PointsAvailable > 9 && PointsAvailable <= 12) return 4;
else if (PointsAvailable > 12 && PointsAvailable <= 15) return 5; if (PointsAvailable > 12 && PointsAvailable <= 15) return 5;
else return 6; return 6;
}; };
module.exports = { CalculateQuality }; module.exports = { CalculateQuality };

View File

@ -7,24 +7,20 @@
* @param {BigInt} Bonus=0 * @param {BigInt} Bonus=0
* @param {BigInt} PointsRemaining=0 * @param {BigInt} PointsRemaining=0
*/ */
const CompareResults = ( const CompareResults = (Throws = [], AttributeLevels = [8, 8, 8], Bonus = 0, Points = 0) => {
Throws = [],
AttributeLevels = [8, 8, 8],
Bonus = 0,
PointsRemaining = 0
) => {
let Passed = 0; let Passed = 0;
let Fumbles = 0; let Fumbles = 0;
let CriticalHit = 0; let CriticalHit = 0;
let AllPointsUsed = []; let PointsRemaining = Points;
const AllPointsUsed = [];
Throws.forEach((Throw, key) => { Throws.forEach((Throw, key) => {
let PointsUsed = 0; let PointsUsed = 0;
let AttributeLevel = AttributeLevels.find((v, k) => key === k); const AttributeLevel = AttributeLevels.find((v, k) => key === k);
if (Math.floor(AttributeLevel + Bonus) >= Throw) { if (Math.floor(AttributeLevel + Bonus) >= Throw) {
Passed++; Passed += 1;
} else if (Math.floor(AttributeLevel + PointsRemaining + Bonus) >= Throw) { } else if (Math.floor(AttributeLevel + PointsRemaining + Bonus) >= Throw) {
Passed++; Passed += 1;
PointsUsed = Throw - Bonus - AttributeLevel; PointsUsed = Throw - Bonus - AttributeLevel;
PointsRemaining -= PointsUsed; PointsRemaining -= PointsUsed;
} else { } else {
@ -32,10 +28,10 @@ const CompareResults = (
PointsRemaining -= PointsUsed; PointsRemaining -= PointsUsed;
} }
if (Throw === 1) { if (Throw === 1) {
CriticalHit++; CriticalHit += 1;
} }
if (Throw === 20) { if (Throw === 20) {
Fumbles++; Fumbles += 1;
} }
AllPointsUsed.push(PointsUsed); AllPointsUsed.push(PointsUsed);
}); });

View File

@ -1,3 +1,7 @@
function f(n) {
return (n > 0 ? '+' : '') + n;
}
const CreateResultTable = ({ const CreateResultTable = ({
Attributes: Attributes, Attributes: Attributes,
Throws: Throws, Throws: Throws,
@ -21,8 +25,4 @@ const CreateResultTable = ({
`; `;
}; };
const f = n => {
return (n > 0 ? '+' : '') + n;
};
module.exports = { CreateResultTable, f }; module.exports = { CreateResultTable, f };

View File

@ -1,14 +1,12 @@
const Random = { int, use };
function int(min, max) { function int(min, max) {
if (!min || !max) { if (!min || !max) {
return; return undefined;
} }
return Math.floor(Math.random() * (Math.floor(max) - Math.ceil(min) + 1)) + min; return Math.floor(Math.random() * (Math.floor(max) - Math.ceil(min) + 1)) + min;
} }
function use(str) { function use() {
return true; return true;
} }
const Random = { int, use };
module.exports = { Random }; module.exports = { Random };

View File

@ -1,18 +1,17 @@
const { Random } = require("@dsabot/Random"); const { Random } = require('@dsabot/Random');
//const Random = require('random'); //const Random = require('random');
const roll = (numberOfDice, numberOfEyes, tag) => { const roll = (numberOfDice, numberOfEyes, tag) => {
let dice = []; const dice = [];
let sum = 0; let sum = 0;
if (tag) { if (tag) {
Random.use(tag); Random.use(tag);
} }
for (let i = 0; i<numberOfDice; i++ ) { for (let i = 0; i < numberOfDice; i += 1) {
let result = Random.int(1,numberOfEyes); const result = Random.int(1, numberOfEyes);
dice.push(result); dice.push(result);
sum += result; sum += result;
} }
return { dice, sum }; return { dice, sum };
}; };
module.exports = { roll }; module.exports = { roll };

View File

@ -1,7 +1,7 @@
const globals = require('../globals'); const { Replies } = require('../globals');
const findMessage = (value) => { const findMessage = value => {
return globals.Replies.find(r => r.id === value).string; return Replies.find(r => r.id === value).string;
}; };
module.exports = { findMessage }; module.exports = { findMessage };

View File

@ -1,14 +1,13 @@
const globals = require('../globals'); const { Werte } = require('../globals');
const getAttributeLevels = (Attributes = [], Character = {}) => { const getAttributeLevels = (Attributes = [], Character = {}) => {
let AttributeId; const AttributeList = [];
let AttributeLevel; Attributes.forEach(Attribute => {
let AttributeList = []; const { id } = Werte.find(att => att.kuerzel === Attribute);
for (let Attribute of Attributes) { const { level } = Character.attributes.find(att => att.id === id);
AttributeId = globals.Werte.find(att => att.kuerzel === Attribute).id; AttributeList.push({ Name: Attribute, Level: level });
AttributeLevel = Character.attributes.find(att => att.id === AttributeId).level; });
AttributeList.push({ Name: Attribute, Level: AttributeLevel });
}
return AttributeList; return AttributeList;
}; };
module.exports = { getAttributeLevels }; module.exports = { getAttributeLevels };

View File

@ -1,28 +1,24 @@
const { getAttributeLevels } = require('@dsabot/getAttributeLevels'); const { getAttributeLevels } = require('@dsabot/getAttributeLevels');
const Chants = require('@Lib/Chants.json'); const Chants = require('@Lib/Chants.json');
const getChant = ({ Character: Character = [], chant_name: chant_name = '' } = {}) => { const getChant = ({ Character: Character = [], chant_name: chantName = '' } = {}) => {
//if (!Character.hasOwnProperty('chants')) return; //if (!Character.hasOwnProperty('chants')) return;
let chant_entry = const chantEntry =
Chants.find(chant => chant.id.toLowerCase() === chant_name.toLowerCase()) || Chants.find(chant => chant.id.toLowerCase() === chantName.toLowerCase()) ||
Chants.find(chant => chant.name.toLowerCase() === chant_name.toLowerCase()); Chants.find(chant => chant.name.toLowerCase() === chantName.toLowerCase());
if (!chant_entry) { if (!chantEntry) {
console.log(`getChant() Did not find entry for ${chant_name}`); console.log(`getChant() Did not find entry for ${chantName}`);
return; return null;
} }
let Level = 0; // This is the minimum attributes value. let Level = 0; // This is the minimum attributes value.
let Chant = Character.chants.find(chant => chant.id === chant_entry.id) || {}; const Chant = Character.chants.find(chant => chant.id === chantEntry.id) || null;
if (Chant && Chant.hasOwnProperty('level')) { if (Chant && Chant.hasOwnProperty('level')) {
Level = Chant.level || 0; Level = Chant.level || 0;
} }
let Attributes = getAttributeLevels(chant_entry.attributes, Character); const Attributes = getAttributeLevels(chantEntry.attributes, Character);
return { return { Name: chantEntry.name, Level: Level, Attributes: Attributes };
Name: chant_entry.name,
Level: Level,
Attributes: Attributes,
};
}; };
module.exports = { getChant }; module.exports = { getChant };

View File

@ -1,22 +1,22 @@
const globals = require('../globals');
const { getAttributeLevels } = require('@dsabot/getAttributeLevels'); const { getAttributeLevels } = require('@dsabot/getAttributeLevels');
const { Talente } = require('../globals');
const getSkill = ({ Character: Character = [], args: args = [] } = {}) => { const getSkill = ({ Character: Character = [], args: args = [] } = {}) => {
let skill_entry = const skillEntry =
globals.Talente.find(skill => skill.id.toLowerCase() === args[0].toLowerCase()) || Talente.find(skill => skill.id.toLowerCase() === args[0].toLowerCase()) ||
globals.Talente.find(skill => skill.name.toLowerCase() === args[0].toLowerCase()); Talente.find(skill => skill.name.toLowerCase() === args[0].toLowerCase());
if (!skill_entry) { if (!skillEntry) {
return; return null;
} }
let Level = 0; // This is the minimum attributes value. let Level = 0; // This is the minimum attributes value.
let cSkill = Character.skills.find(skill => skill.id === skill_entry.id) || {}; const cSkill = Character.skills.find(skill => skill.id === skillEntry.id) || null;
if (cSkill) { if (cSkill) {
Level = cSkill.level || 0; Level = cSkill.level || 0;
} }
let Name = globals.Talente.find(skill => skill.id === skill_entry.id).name; const Name = Talente.find(skill => skill.id === skillEntry.id).name;
let Attributes = getAttributeLevels(skill_entry.values, Character); const Attributes = getAttributeLevels(skillEntry.values, Character);
return { return {
Name: Name, Name: Name,

View File

@ -1,27 +1,27 @@
const { getAttributeLevels } = require('@dsabot/getAttributeLevels'); const { getAttributeLevels } = require('@dsabot/getAttributeLevels');
const Spells = require('@Lib/Spells.json'); const Spells = require('@Lib/Spells.json');
const getSpell = ({ Character: Character = [], spell_name: spell_name = '' } = {}) => { const getSpell = ({ Character: Character = [], spell_name: spellName = '' } = {}) => {
const spell_entry = const spellEntry =
Spells.find(spell => spell.id.toLowerCase() === spell_name.toLowerCase()) || Spells.find(spell => spell.id.toLowerCase() === spellName.toLowerCase()) ||
Spells.find(spell => spell.name.toLowerCase() === spell_name.toLowerCase()); Spells.find(spell => spell.name.toLowerCase() === spellName.toLowerCase());
if (!spell_entry) { if (!spellEntry) {
console.log(`getSpell() did not find entry for ${spell_name}`); console.log(`getSpell() did not find entry for ${spellName}`);
return; return null;
} }
let Level = 0; // This is the minimum attributes value. let Level = 0; // This is the minimum attributes value.
if (!Character.hasOwnProperty('spells')) return; if (!Character.hasOwnProperty('spells')) return null;
let Spell = Character.spells.find(spell => spell.id === spell_entry.id) || {}; //?+ const Spell = Character.spells.find(spell => spell.id === spellEntry.id) || null; //?+
if (Spell && Spell.hasOwnProperty('level')) { if (Spell && Spell.hasOwnProperty('level')) {
Level = Spell.level || 0; Level = Spell.level || 0;
} }
let ModifiedBy = spell_entry.modified_by; const ModifiedBy = spellEntry.modified_by;
let Attributes = getAttributeLevels(spell_entry.attributes, Character); const Attributes = getAttributeLevels(spellEntry.attributes, Character);
return { return {
Name: spell_entry.name, Name: spellEntry.name,
Level: Level, Level: Level,
Attributes: Attributes, Attributes: Attributes,
ModifiedBy: ModifiedBy, ModifiedBy: ModifiedBy,

6
functions/isEmpty.js Normal file
View File

@ -0,0 +1,6 @@
function isEmpty(document = {}) {
if (!document) return true;
if (document.length === 0) return true;
return Object.keys(document).length === 0 ? true : false;
}
module.exports = { isEmpty };

4
functions/isString.js Normal file
View File

@ -0,0 +1,4 @@
function isString(str) {
return typeof str === 'string' || str instanceof String ? true : false;
}
module.exports = { isString };

View File

@ -1,15 +1,12 @@
const Discord = require('discord.js'); const Discord = require('discord.js');
const Datastore = require('nedb'), const Datastore = require('nedb-promises')
db = new Datastore({
const db = Datastore.create({
filename: 'data/dsabot.db', filename: 'data/dsabot.db',
autoload: false, autoload: false,
}); });
const MessageEmbed = new Discord.MessageEmbed(); const MessageEmbed = new Discord.MessageEmbed();
const money = [{ const DiceRegex = /\s?[DdWw]\s?|(?=-|\+)/;
'GD': 'Golddukaten',
'ST': 'Silbertaler',
}];
const DiceRegex = /\s?[DdWw]\s?|(?=\-|\+)/;
const Coin = ['Kopf', 'Zahl']; const Coin = ['Kopf', 'Zahl'];
const Werte = [ const Werte = [
{ id: 'mut', kuerzel: 'MU', name: 'Mut' }, { id: 'mut', kuerzel: 'MU', name: 'Mut' },
@ -147,7 +144,8 @@ const Replies = [
{ id: 'NO_CHANTS', string: 'Du kennst keine Liturgien.' }, { id: 'NO_CHANTS', string: 'Du kennst keine Liturgien.' },
{ id: 'CHANTS_TITLE', string: 'Liturgien'}, { id: 'CHANTS_TITLE', string: 'Liturgien'},
{ id: 'CHANTS_DESCRIPTION', string: 'Folgende Liturgien beherrschst du:' }, { id: 'CHANTS_DESCRIPTION', string: 'Folgende Liturgien beherrschst du:' },
{ id: 'CHANT_UNKNOWN', string: 'Diese Liturgie kenne ich nicht.'} { id: 'CHANT_UNKNOWN', string: 'Diese Liturgie kenne ich nicht.' },
{ id: 'NO_CHARACTERS', string: 'Keine Benutzer auf dieser Liste gefunden.'}
]; ];
const Declination = ['dem', 'der', 'dem', '']; // Maskulinum, Feminimum, Neutrum, None const Declination = ['dem', 'der', 'dem', '']; // Maskulinum, Feminimum, Neutrum, None
const Articles = ['Der','Die','Das','']; const Articles = ['Der','Die','Das',''];
@ -233,12 +231,4 @@ const RangedWeapons = [
]; ];
const Weapons = MeleeWeapons.concat(RangedWeapons); const Weapons = MeleeWeapons.concat(RangedWeapons);
const Advantages = [
{}
];
const Disadvantages = [
{}
];
module.exports = { Werte, Talente, Coin, TalentKategorien, DiceRegex, Discord, MessageEmbed, db, Replies, MeleeWeapons, Weapons, RangedWeapons, CombatTechniques, Articles, Declination }; module.exports = { Werte, Talente, Coin, TalentKategorien, DiceRegex, Discord, MessageEmbed, db, Replies, MeleeWeapons, Weapons, RangedWeapons, CombatTechniques, Articles, Declination };

123
index.js
View File

@ -2,64 +2,13 @@ require('module-alias/register');
require('dotenv').config(); require('dotenv').config();
const fs = require('fs'); const fs = require('fs');
const fetch = require('node-fetch'); const fetch = require('node-fetch');
const globals = require('./globals');
const db = globals.db;
db.loadDatabase();
const cmdprefix = process.env.CMDPREFIX || '!';
const Discord = require('discord.js'); const Discord = require('discord.js');
const { findMessage } = require('@dsabot/findMessage');
const { db } = require('./globals');
db.load();
const cmdprefix = process.env.CMDPREFIX || '!';
const client = new Discord.Client(); const client = new Discord.Client();
client.commands = new Discord.Collection();
client.on('message', commandHandler);
client.login(process.env.BOT_TOKEN);
client.once('ready', () => {
console.log('Ready!');
});
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
async function commandHandler(message) {
//console.log(`${new Date().toUTCString()} ${message.author.tag} (size: ${message.attachments.size})`);
if (message.attachments.size > 0 && message.channel.type == 'dm' && !message.author.bot) {
try {
const response = await fetch(message.attachments.first().url);
const data = await validateJSON(response);
if (data) await CreateFromFile(message, data);
} catch (e) {
console.log(e);
return message.reply(globals.Replies.find(x => x.id === 'ERROR').string);
}
} else {
if (!message.content.startsWith(cmdprefix) || message.author.bot) {
return;
}
const args = message.content.slice(cmdprefix.length).split(' ');
const commandName = args.shift().toLowerCase();
//if (!client.commands.has(commandName)) return;
try {
const command =
client.commands.get(commandName) ||
client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.needs_args && !args.length) {
return message.reply(
globals.Replies.find(x => x.id === 'TOO_FEW_ARGS').string +
cmdprefix +
commandName +
' ' +
command.usage
);
} else {
command.exec(message, args);
}
} catch (e) {
message.reply(globals.Replies.find(x => x.id === 'ERROR').string);
}
}
}
function validateJSON(body) { function validateJSON(body) {
try { try {
@ -71,26 +20,60 @@ function validateJSON(body) {
} }
async function CreateFromFile(message, data) { async function CreateFromFile(message, data) {
try { db.find({
db.find(
{
user: message.author.tag, user: message.author.tag,
}, }).then(docs => {
function (err, docs) {
if (docs.length === 0) { if (docs.length === 0) {
db.insert( db.insert({
{ uid: `${message.author.id}`,
user: message.author.tag, user: message.author.tag,
character: data, character: data,
}, }).then(() => {
function (err, docs) { message.reply(findMessage('SAVED_DATA'));
message.reply(globals.Replies.find(r => r.id === 'SAVED_DATA').string); });
} }
); });
} }
} async function commandHandler(message) {
); // console.log(`${new Date().toUTCString()} ${message.author.tag} (size: ${message.attachments.size})`);
if (message.attachments.size > 0 && message.channel.type === 'dm' && !message.author.bot) {
try {
const response = await fetch(message.attachments.first().url);
const data = await validateJSON(response);
if (data) await CreateFromFile(message, data);
} catch (e) { } catch (e) {
throw e; console.log(e);
return message.reply(findMessage('ERROR'));
} }
} else {
if (!message.content.startsWith(cmdprefix) || message.author.bot) {
return null;
} }
const args = message.content.slice(cmdprefix.length).split(' ');
const commandName = args.shift().toLowerCase();
const command =
client.commands.get(commandName) ||
client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return null;
if (command.needs_args && !args.length) {
return message.reply(
`${findMessage('TOO_FEW_ARGS')}\n${cmdprefix}${commandName} ${command.usage}`
);
}
command.exec(message, args);
}
return null;
}
client.commands = new Discord.Collection();
client.on('message', commandHandler);
client.login(process.env.BOT_TOKEN);
client.once('ready', () => {
console.log('Ready!');
});
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
commandFiles.forEach(file => {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
});

2298
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "dsabot", "name": "dsabot",
"version": "1.5.2", "version": "1.6.1",
"description": "", "description": "",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
@ -20,14 +20,18 @@
"discord.js": "^12.5.3", "discord.js": "^12.5.3",
"dotenv": "^8.2.0", "dotenv": "^8.2.0",
"module-alias": "^2.2.2", "module-alias": "^2.2.2",
"nedb": "^1.8.0", "nedb-promises": "^4.1.2",
"node-fetch": "^2.6.1", "node-fetch": "^2.6.1",
"random": "^3.0.6" "random": "^3.0.6"
}, },
"devDependencies": { "devDependencies": {
"@types/jest": "^26.0.23", "@types/jest": "^26.0.23",
"babel-plugin-rewire": "^1.2.0",
"eslint": "^6.8.0", "eslint": "^6.8.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-config-prettier": "^6.8.0", "eslint-config-prettier": "^6.8.0",
"eslint-import-resolver-module-alias": "github:tenfold/eslint-import-resolver-module-alias",
"eslint-plugin-prettier": "^3.4.0",
"jest": "^26.6.3", "jest": "^26.6.3",
"rewire": "^5.0.0" "rewire": "^5.0.0"
}, },