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,
"require-yield": 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": {
"node": true,
@ -71,5 +77,14 @@
"commonjs": 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');
const rewire = require('rewire');
const rewireUtils = rewire('@Commands/Attack');
const rewireUtils = rewire('@Commands/Attack');
const getWeapon = rewireUtils.__get__('getWeapon');
const getAttributeLevel = rewireUtils.__get__('getAttributeLevel');
const getCombatTechniqueLevel = rewireUtils.__get__('getCombatTechniqueLevel');
@ -139,7 +139,7 @@ it('should abort with a message: no entry found', () => {
};
const handleAttack = rewireUtils.__get__('handleAttack');
//expect(handleAttack(err)).toThrowError();
expect(handleAttack([], { message: message })).toEqual(
expect(handleAttack({}, { message: message })).toEqual(
'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 args = ['messer'];
expect(handleAttack([{ character: character }], { message: message, args: args })).toEqual(
expect(handleAttack({ character: character }, { message: message, args: args })).toEqual(
expect.any(String)
);
});
@ -204,7 +204,7 @@ it('complete run with ranged weapon', () => {
};
const handleAttack = rewireUtils.__get__('handleAttack');
const args = ['langbogen'];
expect(handleAttack([{ character: character }], { message: message, args: args })).toEqual(
expect(handleAttack({ character: character }, { message: message, args: args })).toEqual(
expect.any(String)
);
});

View File

@ -1,7 +1,8 @@
require('module-alias/register');
const rewire = require('rewire');
const rewireUtils = rewire('@Commands/Attribute');
const Attribute = require('@Commands/Attribute');
const rewireUtils = rewire('@Commands/Attribute');
const HandleNamedAttributes = rewireUtils.__get__('HandleNamedAttributes');
const getAttributeLevel = rewireUtils.__get__('getAttributeLevel');
const getAttribute = rewireUtils.__get__('getAttribute');
@ -44,9 +45,9 @@ it('should return with no errors', () => {
tag: 'test',
},
};
const docs = [{ character: { attributes: [{ id: 'mut', level: 8 }] } }];
const doc = { character: { attributes: [{ id: 'mut', level: 8 }] } };
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', () => {
const reply = jest.fn(str => str);
@ -56,7 +57,7 @@ it('should return with no errors', () => {
tag: 'test',
},
};
const docs = [{ character: { attributes: [{ id: 'mut', level: 8 }] } }];
const docs = { character: { attributes: [{ id: 'mut', level: 8 }] } };
const args = ['MU'];
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 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));
}
});
@ -84,15 +85,18 @@ it('should return with no errors', () => {
};
const docs = [{ character: { attributes: [{ id: 'mut', level: 8 }] } }];
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));
}
});
it('should return empty', () => {
const message = { author: { tag: 'test' } };
const message = { author: { tag: 'test' }, reply: jest.fn(str => str) };
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);

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');
it('should return an object', () => {
let Obj = {
const Obj = {
Passed: 0,
CriticalHit: 0,
Fumbles: 0,
@ -15,7 +15,7 @@ it('should return an object', () => {
});
it('should match No. of Fumbles', () => {
let Obj = {
const Obj = {
Passed: 0,
CriticalHit: 0,
Fumbles: 2,
@ -26,7 +26,7 @@ it('should match No. of Fumbles', () => {
});
it('should match No. of Passed', () => {
let Obj = {
const Obj = {
Passed: 3,
CriticalHit: 0,
Fumbles: 0,
@ -37,7 +37,7 @@ it('should match No. of Passed', () => {
});
it('should match No. of Critical Hits', () => {
let Obj = {
const Obj = {
Passed: 3,
CriticalHit: 2,
Fumbles: 0,
@ -48,7 +48,7 @@ it('should match No. of Critical Hits', () => {
});
it('should decrease Points remaining', () => {
let Obj = {
const Obj = {
Passed: 3,
CriticalHit: 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');
const globals = require('../globals');
const db = globals.db;
const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage');
const { isEmpty } = require('@dsabot/isEmpty');
module.exports = {
name: 'attack',
description: 'Würfelt den Attackewert auf eine Nahkampfwaffe.',
aliases: ['angriff', 'attacke'],
usage: '<Waffe>',
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);
}
const { db } = require('../globals');
const { CombatTechniques } = require('../globals');
const { Werte } = require('../globals');
const { Weapons } = require('../globals');
const { MeleeWeapons } = require('../globals');
function getCombatTechnique(Weapon) {
if (Weapon)
return globals.CombatTechniques.find(technique => technique.id === Weapon.combattechnique);
if (Weapon) return CombatTechniques.find(technique => technique.id === Weapon.combattechnique);
return null;
}
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) {
let ok = false,
crit = false,
dd = false,
fumble = false;
let ok = false;
let crit = false;
let dd = false;
let fumble = false;
dice.forEach((val, index) => {
if (index === 0) {
@ -145,16 +60,103 @@ function getCombatTechniqueLevel(Player = {}, CombatTechnique = {}) {
Leiteigenschaft: CombatTechnique.Leiteigenschaft,
};
}
return null;
}
function getWeapon(Weapon = '') {
if (Weapon)
return globals.Weapons.find(
w => w.id === Weapon.toLowerCase() || w.name.toLowerCase() === Weapon.toLowerCase()
);
return Weapons.find(
w => w.id === Weapon.toLowerCase() || w.name.toLowerCase() === Weapon.toLowerCase()
);
}
function isMeleeWeapon(Weapon) {
if (globals.MeleeWeapons.find(MeleeWeapon => MeleeWeapon.id === Weapon.id)) return true;
else return false;
if (MeleeWeapons.find(MeleeWeapon => MeleeWeapon.id === Weapon.id)) return true;
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');
const globals = require('../globals');
const db = globals.db;
const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage');
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 }) {
let Attribute = isNaN(args[0])
? HandleNamedAttributes({ Character: docs[0].character, args: args })
function getAttributeLevel(Character = {}, Attribute = {}) {
return Character.attributes.find(attribute => attribute.id === Attribute.id).level;
}
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;
let Level = Attribute ? Attribute.Level : args[0] || 8;
let Bonus = parseInt(args[1]) || 0;
let dice = roll(2, 20, message.author.tag).dice;
const Level = Attribute ? Attribute.Level : args[0] || 8;
const Bonus = parseInt(args[1], 10) || 0;
const { dice } = roll(2, 20, message.author.tag);
const Result = CompareResults(dice, [Level, Level], Bonus);
// 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 = {
name: 'attribute',
description: '',
@ -76,13 +79,11 @@ module.exports = {
usage: '<Eigenschaft> / <Eigenschaftswert>',
needs_args: true,
async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => {
if (err) {
db.findOne({ user: message.author.tag })
.then(doc => handleAttributeCheck(doc, { message, args }))
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
}
handleAttributeCheck(docs, { message, args });
});
});
},
};

View File

@ -1,12 +1,16 @@
const globals = require('../globals');
const Discord = require('discord.js');
const db = globals.db;
const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage');
const { getSpell } = require('@dsabot/getSpell');
const { CalculateQuality } = require('@dsabot/CalculateQuality');
const { CompareResults } = require('@dsabot/CompareResults');
const { CreateResultTable, f } = require('@dsabot/CreateResultTable');
const { isEmpty } = require('@dsabot/isEmpty');
const { isString } = require('@dsabot/isString');
const { db } = require('../globals');
module.exports = {
name: 'cast',
description:
@ -17,74 +21,88 @@ module.exports = {
usage: '<Zaubern> [<-Erschwernis> / <+Erleichterung>]',
needs_args: false,
async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => {
if (docs.length === 0) {
return message.reply(findMessage('NOENTRY'));
}
if (!docs[0].character.hasOwnProperty('spells')) return message.reply(findMessage('NO_SPELLS'));
if (!isNaN(args[0])) {
return message.reply(findMessage('WRONG_ARGUMENTS'));
}
const Spell = getSpell({ Character: docs[0].character, spell_name: args[0] });
if (!Spell) {
return message.reply(findMessage('SPELL_UNKNOWN'));
}
if (!Spell.Level || !Spell.Attributes) {
return;
}
const Attributes = Spell.Attributes;
const DiceThrow = roll(3, 20, message.author.tag).dice;
const Bonus = parseInt(args[1]) || 0;
let { Passed, CriticalHit, Fumbles, PointsUsed, PointsRemaining } = CompareResults(
DiceThrow,
Attributes.map(attr => attr.Level),
Bonus,
Spell.Level
);
const Reply = new Discord.MessageEmbed();
Reply.addFields({
name: `Du würfelst auf den Zauber **${Spell.Name}** ( Stufe ${Spell.Level} ${
Bonus ? `${f(Bonus)} ` : ''
})`,
value: CreateResultTable({
Attributes: Attributes,
Throws: DiceThrow,
PointsUsed: PointsUsed,
Bonus: Bonus,
}),
inline: false,
});
if (Fumbles >= 2) {
Reply.setColor('#900c3f');
db.findOne({ user: message.author.tag })
.then(doc => {
if (isEmpty(doc)) {
return message.reply(findMessage('NOENTRY'));
}
if (!doc.character.hasOwnProperty('spells'))
return message.reply(findMessage('NO_SPELLS'));
if (!isString(args[0])) {
return message.reply(findMessage('WRONG_ARGUMENTS'));
}
const Spell = getSpell({ Character: doc.character, spell_name: args[0] });
if (!Spell) {
return message.reply(findMessage('SPELL_UNKNOWN'));
}
if (!Spell.Level || !Spell.Attributes) {
return null;
}
const { Attributes } = Spell;
const DiceThrow = roll(3, 20, message.author.tag).dice;
const Bonus = parseInt(args[1], 10) || 0;
const {
Passed,
CriticalHit,
Fumbles,
PointsUsed,
PointsRemaining,
} = CompareResults(
DiceThrow,
Attributes.map(attr => attr.Level),
Bonus,
Spell.Level
);
const Reply = new Discord.MessageEmbed();
Reply.addFields({
name: findMessage('TITLE_CRIT_FAILURE'),
value: findMessage('MSG_CRIT_FAILURE'),
name: `Du würfelst auf den Zauber **${Spell.Name}** ( Stufe ${Spell.Level} ${
Bonus ? `${f(Bonus)} ` : ''
})`,
value: CreateResultTable({
Attributes: Attributes,
Throws: DiceThrow,
PointsUsed: PointsUsed,
Bonus: Bonus,
}),
inline: false,
});
} else if (CriticalHit >= 2) {
Reply.setColor('#1E8449');
Reply.addFields({
name: findMessage('TITLE_CRIT_SUCCESS'),
value: findMessage('MSG_CRIT_SUCCESS'),
inline: false,
});
} else if (Passed < 3) {
Reply.addFields({
name: findMessage('TITLE_FAILURE'),
value: `${Passed === 0 ? 'Keine Probe' : `nur ${Passed}/3 Proben`} erfolgreich. 😪`,
inline: false,
});
} else {
Reply.addFields({
name: findMessage('TITLE_SUCCESS'),
value: `Dein verbleibender Bonus: ${PointsRemaining}/${Spell.Level} (QS${CalculateQuality(
PointsRemaining
)})`,
inline: false,
});
}
if (Fumbles >= 2) {
Reply.setColor('#900c3f');
Reply.addFields({
name: findMessage('TITLE_CRIT_FAILURE'),
value: findMessage('MSG_CRIT_FAILURE'),
inline: false,
});
} else if (CriticalHit >= 2) {
Reply.setColor('#1E8449');
Reply.addFields({
name: findMessage('TITLE_CRIT_SUCCESS'),
value: findMessage('MSG_CRIT_SUCCESS'),
inline: false,
});
} else if (Passed < 3) {
Reply.addFields({
name: findMessage('TITLE_FAILURE'),
value: `${
Passed === 0 ? 'Keine Probe' : `nur ${Passed}/3 Proben`
} erfolgreich. 😪`,
inline: false,
});
} else {
Reply.addFields({
name: findMessage('TITLE_SUCCESS'),
value: `Dein verbleibender Bonus: ${PointsRemaining}/${
Spell.Level
} (QS${CalculateQuality(PointsRemaining)})`,
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 db = globals.db;
const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage');
const { getChant } = require('@dsabot/getChant');
const { CalculateQuality } = require('@dsabot/CalculateQuality');
const { CompareResults } = require('@dsabot/CompareResults');
const { CreateResultTable, f } = require('@dsabot/CreateResultTable');
const { isEmpty } = require('@dsabot/isEmpty');
const { isString } = require('@dsabot/isString');
const { db } = require('../globals');
module.exports = {
name: 'chant',
description:
@ -17,73 +20,87 @@ module.exports = {
usage: '<Liturgie/Zeremonie> [<-Erschwernis> / <+Erleichterung>]',
needs_args: false,
async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => {
if (docs.length === 0) {
return message.reply(findMessage('NOENTRY'));
}
if (!docs[0].character.hasOwnProperty('chants')) return message.reply(findMessage('NO_CHANTS'));
if (!isNaN(args[0])) {
return message.reply(findMessage('WRONG_ARGUMENTS'));
}
const Chant = getChant({ Character: docs[0].character, chant_name: args[0] });
if (!Chant) {
return message.reply(findMessage('CHANT_UNKNOWN'));
}
if (!Chant.Level || !Chant.Attributes) {
return;
}
const Attributes = Chant.Attributes;
const DiceThrow = roll(3, 20, message.author.tag).dice;
const Bonus = parseInt(args[1]) || 0;
let { Passed, CriticalHit, Fumbles, PointsUsed, PointsRemaining } = CompareResults(
DiceThrow,
Attributes.map(attr => attr.Level),
Bonus,
Chant.Level
);
const Reply = new Discord.MessageEmbed();
Reply.addFields({
name: `Du würfelst auf die Liturgie **${Chant.Name}** ( Stufe ${Chant.Level} ${
Bonus ? `${f(Bonus)} ` : ''
})`,
value: CreateResultTable({
Attributes: Attributes,
Throws: DiceThrow,
PointsUsed: PointsUsed,
Bonus: Bonus,
}),
inline: false,
db.findOne({ user: message.author.tag })
.then(doc => {
if (isEmpty(doc)) {
return message.reply(findMessage('NOENTRY'));
}
if (!doc.character.hasOwnProperty('chants'))
return message.reply(findMessage('NO_CHANTS'));
if (!isString(args[0])) {
return message.reply(findMessage('WRONG_ARGUMENTS'));
}
const Chant = getChant({ Character: doc.character, chant_name: args[0] });
if (!Chant) {
return message.reply(findMessage('CHANT_UNKNOWN'));
}
if (!Chant.Level || !Chant.Attributes) {
return null;
}
const { Attributes } = Chant;
const DiceThrow = roll(3, 20, message.author.tag).dice;
const Bonus = parseInt(args[1], 10) || 0;
const {
Passed,
CriticalHit,
Fumbles,
PointsUsed,
PointsRemaining,
} = CompareResults(
DiceThrow,
Attributes.map(attr => attr.Level),
Bonus,
Chant.Level
);
const Reply = new Discord.MessageEmbed();
Reply.addFields({
name: `Du würfelst auf die Liturgie **${Chant.Name}** ( Stufe ${Chant.Level} ${
Bonus ? `${f(Bonus)} ` : ''
})`,
value: CreateResultTable({
Attributes: Attributes,
Throws: DiceThrow,
PointsUsed: PointsUsed,
Bonus: Bonus,
}),
inline: false,
});
if (Fumbles >= 2) {
Reply.setColor('#900c3f');
Reply.addFields({
name: findMessage('TITLE_CRIT_FAILURE'),
value: findMessage('MSG_CRIT_FAILURE'),
inline: false,
});
} else if (CriticalHit >= 2) {
Reply.setColor('#1E8449');
Reply.addFields({
name: findMessage('TITLE_CRIT_SUCCESS'),
value: findMessage('MSG_CRIT_SUCCESS'),
inline: false,
});
} else if (Passed < 3) {
Reply.addFields({
name: findMessage('TITLE_FAILURE'),
value: `${
Passed === 0 ? 'Keine Probe' : `nur ${Passed}/3 Proben`
} erfolgreich. 😪`,
inline: false,
});
} else {
Reply.addFields({
name: findMessage('TITLE_SUCCESS'),
value: `Dein verbleibender Bonus: ${PointsRemaining}/${
Chant.Level
} (QS${CalculateQuality(PointsRemaining)})`,
inline: false,
});
}
return message.reply(Reply);
})
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
});
if (Fumbles >= 2) {
Reply.setColor('#900c3f');
Reply.addFields({
name: findMessage('TITLE_CRIT_FAILURE'),
value: findMessage('MSG_CRIT_FAILURE'),
inline: false,
});
} else if (CriticalHit >= 2) {
Reply.setColor('#1E8449');
Reply.addFields({
name: findMessage('TITLE_CRIT_SUCCESS'),
value: findMessage('MSG_CRIT_SUCCESS'),
inline: false,
});
} else if (Passed < 3) {
Reply.addFields({
name: findMessage('TITLE_FAILURE'),
value: `${Passed === 0 ? 'Keine Probe' : `nur ${Passed}/3 Proben`} erfolgreich. 😪`,
inline: false,
});
} else {
Reply.addFields({
name: findMessage('TITLE_SUCCESS'),
value: `Dein verbleibender Bonus: ${PointsRemaining}/${Chant.Level} (QS${CalculateQuality(
PointsRemaining
)})`,
inline: false,
});
}
message.reply(Reply);
});
},
};

View File

@ -1,9 +1,34 @@
//const globals = require('../globals');
const globals = require('../globals');
const Discord = require('discord.js');
const db = globals.db;
const { findMessage } = require('@dsabot/findMessage');
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 = {
name: 'chants',
description: 'Zeigt dir deinen Fertigkeitswert im jeweiligen Magietalent (Götterwirken).',
@ -12,50 +37,34 @@ module.exports = {
needs_args: false,
async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => {
if (docs.length === 0) {
return message.reply(findMessage('NOENTRY'));
}
const Character = docs[0].character;
if (!Character.hasOwnProperty('chants')) return message.reply(findMessage('NO_CHANTS'));
if (args.length === 0) {
const Embed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(findMessage('CHANTS_TITLE'))
.setDescription(findMessage('CHANTS_DESCRIPTION'))
.addField(ReplyChantList(createChantList(Character)), '\u200B', true);
return message.reply(Embed);
}
const Chant = getChant({
Character: Character,
chant_name: args[0],
db.findOne({ user: message.author.tag })
.then(doc => {
if (isEmpty(doc)) {
return message.reply(findMessage('NOENTRY'));
}
const Character = doc.character;
if (!Character.hasOwnProperty('chants'))
return message.reply(findMessage('NO_CHANTS'));
if (args.length === 0) {
const Embed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(findMessage('CHANTS_TITLE'))
.setDescription(findMessage('CHANTS_DESCRIPTION'))
.addField(ReplyChantList(createChantList(Character)), '\u200B', true);
return message.reply(Embed);
}
const Chant = getChant({
Character: Character,
chant_name: args[0],
});
if (!Chant) {
return message.reply(findMessage('SPELL_UNKNOWN'));
}
return message.reply(ReplyChant(Chant));
})
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
});
if (!Chant) {
return message.reply(findMessage('SPELL_UNKNOWN'));
}
return message.reply(ReplyChant(Chant));
});
},
};
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,16 +1,16 @@
const globals = require('../globals');
const { roll } = require('@dsabot/Roll');
const { findMessage }= require('@dsabot/findMessage');
const { findMessage } = require('@dsabot/findMessage');
const { Coin } = require('../globals');
module.exports = {
name: 'kopf',
description: 'Wirf eine Münze. Kopf oder Zahl?',
aliases: ['zahl', 'heads', 'tails'],
usage: '',
needs_args: false,
name: 'kopf',
description: 'Wirf eine Münze. Kopf oder Zahl?',
aliases: ['zahl', 'heads', 'tails'],
usage: '',
needs_args: false,
async exec(message, args) {
const coin = roll(1,2,message.author.tag).dice;
message.reply(`${findMessage('HEADS_OR_TAILS')} **${globals.Coin[(coin-1)]}**.`);
},
};
async exec(message) {
const { dice } = roll(1, 2, message.author.tag);
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,85 +1,107 @@
const globals = require('../globals');
const db = globals.db;
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 = {
name: 'parry',
description: 'Würfelt den Paradewert auf eine Nahkampfwaffe.',
aliases: ['parieren','parade'],
usage: '<Waffe>',
needs_args: true,
name: 'parry',
description: 'Würfelt den Paradewert auf eine Nahkampfwaffe.',
aliases: ['parieren', 'parade'],
usage: '<Waffe>',
needs_args: true,
async exec(message, args) {
try {
db.find({
user: message.author.tag,
}, function(err, docs) {
if (docs.length === 0) {
return message.reply(globals.Replies.find(r => r.id === 'NOENTRY').string);
}
else {
async exec(message, args) {
db.find({ user: message.author.tag }).then(docs => {
if (isEmpty(docs)) {
return message.reply(findMessage('NOENTRY'));
}
Random.use(message.author.tag);
Random.use(message.author.tag);
const Player = docs[0].character;
const Weapon = globals.Weapons.find(w => w.id === args[0].toLowerCase());
if(!Weapon) { return message.reply(globals.Replies.find(r => r.id === 'NO_SUCH_WEAPON').string);}
const Player = docs[0].character;
const Weapon = Weapons.find(w => w.id === args[0].toLowerCase());
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);
let CombatTechniqueValue = null;
if (PlayerCombatTechnique) { CombatTechniqueValue = PlayerCombatTechnique.level; }
if(!CombatTechniqueValue) { CombatTechniqueValue = 6; }
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;
if (PlayerCombatTechnique) {
CombatTechniqueValue = PlayerCombatTechnique.level;
}
if (!CombatTechniqueValue) {
CombatTechniqueValue = 6;
}
let ParryValue = Math.ceil(CombatTechniqueValue/2);
CombatTechniqueValue.Leiteigenschaft.forEach( Property => {
let Attribute = globals.Werte.find(a => a.kuerzel === Property.id);
ParryValue += Math.floor((Player.attributes.find(a => a.id === Attribute).level - 8)/3);
});
ParryValue += Weapon.pa_mod;
let ParryValue = Math.ceil(CombatTechniqueValue / 2);
CombatTechniqueValue.Leiteigenschaft.forEach(Property => {
const Attribute = Werte.find(a => a.kuerzel === Property.id);
ParryValue += Math.floor(
(Player.attributes.find(a => a.id === Attribute).level - 8) / 3
);
});
ParryValue += Weapon.pa_mod;
let dice = [];
let Bonus = 0;
if(args[1] && !isNaN(parseInt(args[1]))) { Bonus = parseInt(args[1]); }
let Comparison = Math.floor(ParryValue + Bonus);
let Patzer = false;
let Critical = false;
let Ok = false;
const dice = [];
for (let i = 0; i < 2; i++) {
dice.push(Random.int(1,20));
}
const Bonus = parseInt(args[1], 10) || 0;
// 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; }
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(); }
const Comparison = Math.floor(ParryValue + Bonus);
let Patzer = false;
let Critical = false;
let Ok = false;
for (let i = 0; i < 2; i += 1) {
dice.push(Random.int(1, 20));
}
let Reply = 'Du versuchst, mit ' + globals.Declination[Weapon.article] + ' ' + Weapon.name + ' zu parieren.\n';
Reply += 'Dein Paradewert für ' + CombatTechnique.name + ' ist ' + Math.floor(ParryValue - Weapon.pa_mod) + '. (Waffe: ' + Weapon.pa_mod + ')\n';
Reply += 'Deine 🎲: ` ' + dice.join(', ') + ' `.\n\n';
// 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;
} 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();
}
if(!Ok) {
Reply += globals.Replies.find(reply => reply.id === 'PARRY_FAIL').string;
if(Patzer) { Reply += globals.Replies.find(reply => reply.id === 'PARRY_CRIT_FAIL').string; }
}
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; }
}
let Reply = `Du versuchst, mit ${Weapon.name} zu parieren.\n`;
Reply += `Dein Paradewert für ${CombatTechnique.name} ist ${Math.floor(
ParryValue - Weapon.pa_mod
)}. (Waffe ${Weapon.pa_mod})\n`;
Reply += `Deine 🎲: ${dice.join(', ')}\n\n`;
return message.reply( Reply );
if (!Ok) {
Reply += findMessage('PARRY_FAIL');
if (Patzer) {
Reply += findMessage('PARRY_CRIT_FAIL');
}
} else {
if (Critical) {
Reply += findMessage('PARRY_CRIT_SUCCESS');
}
if (!Critical) {
Reply += findMessage('PARRY_SUCCESS');
}
}
}
});
}
catch (e) {
throw e;
}
},
};
return message.reply(Reply);
});
},
};

View File

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

View File

@ -1,24 +1,28 @@
// eslint-disable-next-line no-unused-vars
const globals = require('../globals');
const { roll } = require('@dsabot/Roll');
const { findMessage }= require('@dsabot/findMessage');
const { findMessage } = require('@dsabot/findMessage');
const { DiceRegex } = require('../globals');
module.exports = {
name: 'roll',
description: 'Lass die Würfel rollen. Benötigt wird die Anzahl sowie die Augenzahl auf den Würfeln.',
aliases: ['r'],
usage: '<Anzahl> w <Augenzahl>',
needs_args: true,
async exec(message, args) {
let params = args.join('').split(globals.DiceRegex);
if ( params.length >= 2 ) {
const Bonus = parseInt(params[2]) || 0;
const numberOfDice = parseInt( params[0] );
const diceValues = parseInt( params[1] );
const result = roll( numberOfDice, diceValues, message.author.tag );
let total = (Bonus ? Bonus + result.sum : result.sum)
message.reply(`${findMessage('ROLL')} ${result.dice.join(', ')} `+
`(Gesamt: ${result.sum}${Bonus ? `+${Bonus}=${total}` : ``})` );
}
},
name: 'roll',
description:
'Lass die Würfel rollen. Benötigt wird die Anzahl sowie die Augenzahl auf den Würfeln.',
aliases: ['r'],
usage: '<Anzahl> w <Augenzahl>',
needs_args: true,
async exec(message, args) {
const params = args.join('').split(DiceRegex);
if (params.length >= 2) {
const Bonus = parseInt(params[2], 10) || 0;
const numberOfDice = parseInt(params[0], 10);
const diceValues = parseInt(params[1], 10);
const result = roll(numberOfDice, diceValues, message.author.tag);
const total = Bonus ? Bonus + result.sum : result.sum;
message.reply(
`${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 db = globals.db;
const { findMessage } = require('@dsabot/findMessage');
const { isEmpty } = require('@dsabot/isEmpty');
const { db } = require('../globals');
module.exports = {
name: 'show',
@ -13,37 +13,28 @@ module.exports = {
// eslint-disable-next-line no-unused-vars
async exec(message, args) {
try {
db.find(
{
user: message.author.tag,
},
function (err, docs) {
if (docs.length === 0) {
return message.reply(findMessage('NOENTRY'));
} else {
const Character = docs[0].character;
let Gender;
if (Character.sex == 'female') {
Gender = '♀️';
} else {
Gender = '♂️';
}
const Reply = new Discord.MessageEmbed();
Reply.setColor('#0099ff');
Reply.setTitle(`${Gender} ${Character.name}`);
Reply.setDescription(
`${Character.age} Jahre, ${Character.race}/${Character.culture}`
);
Reply.addField(Character.professionname, Character.xp.startinglevel);
message.reply(Reply);
}
db.find({ user: message.author.tag })
.then(docs => {
if (isEmpty(docs)) {
return message.reply(findMessage('NOENTRY'));
}
);
} catch (e) {
message.reply(findMessage('ERROR'));
throw e;
}
const Character = docs[0].character;
const Gender = Character.sex === 'female' ? '♀️' : '♂️';
const Reply = new Discord.MessageEmbed();
Reply.setColor('#0099ff');
Reply.setTitle(`${Gender} ${Character.name}`);
Reply.setDescription(
`${Character.age} Jahre, ${Character.race}/${Character.culture}`
);
Reply.addField(Character.professionname, Character.xp.startinglevel);
return message.reply(Reply);
})
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
});
},
};

View File

@ -1,7 +1,8 @@
const globals = require('../globals');
const db = globals.db;
const { findMessage } = require('@dsabot/findMessage');
const { getSkill } = require('@dsabot/getSkill');
const { isEmpty } = require('@dsabot/isEmpty');
const { db } = require('../globals');
module.exports = {
name: 'skill',
description: 'Zeigt dir deinen Fertigkeitswert im jeweiligen Talent.',
@ -10,15 +11,20 @@ module.exports = {
needs_args: true,
async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => {
if (docs.length === 0) {
return message.reply(findMessage('NOENTRY'));
}
const Skill = getSkill({ Character: docs[0].character, args: args });
if (!Skill) {
return message.reply(findMessage('TALENT_UNKNOWN'));
}
return message.reply(`Du hast folgenden Wert in **${Skill.Name}**: ${Skill.Level}`);
});
db.find({ user: message.author.tag })
.then(docs => {
if (isEmpty(docs)) {
return message.reply(findMessage('NOENTRY'));
}
const Skill = getSkill({ Character: docs[0].character, args: args });
if (!Skill) {
return message.reply(findMessage('TALENT_UNKNOWN'));
}
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 { findMessage } = require('@dsabot/findMessage');
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 = {
name: 'spells',
description: 'Zeigt dir deinen Fertigkeitswert im jeweiligen Magietalent.',
@ -12,48 +33,32 @@ module.exports = {
needs_args: false,
async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => {
if (docs.length === 0) {
return message.reply(findMessage('NOENTRY'));
}
const Character = docs[0].character;
if (!Character.hasOwnProperty('spells')) return message.reply(findMessage('NO_SPELLS'));
if (args.length === 0) {
const Embed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(findMessage('SPELLS_TITLE'))
.setDescription(findMessage('SPELLS_DESCRIPTION'))
.addField(ReplySpellList(createSpellList(Character)), '\u200B', true);
return message.reply(Embed);
}
const Spell = getSpell({
Character: Character,
spell_name: args[0],
db.find({ user: message.author.tag })
.then(docs => {
if (docs.length === 0) {
return message.reply(findMessage('NOENTRY'));
}
const Character = docs[0].character;
if (!Character.hasOwnProperty('spells'))
return message.reply(findMessage('NO_SPELLS'));
if (args.length === 0) {
const Embed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(findMessage('SPELLS_TITLE'))
.setDescription(findMessage('SPELLS_DESCRIPTION'))
.addField(ReplySpellList(createSpellList(Character)), '\u200B', true);
return message.reply(Embed);
}
const Spell = getSpell({
Character: Character,
spell_name: args[0],
});
if (!Spell) return message.reply(findMessage('SPELL_UNKNOWN'));
return message.reply(ReplySpell(Spell));
})
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
});
if (!Spell) return message.reply(findMessage('SPELL_UNKNOWN'));
return message.reply(ReplySpell(Spell));
});
},
};
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 db = globals.db;
const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage');
const { getSkill } = require('@dsabot/getSkill');
const { CalculateQuality } = require('@dsabot/CalculateQuality');
const { CompareResults } = require('@dsabot/CompareResults');
const { CreateResultTable } = require('@dsabot/CreateResultTable');
const { isString } = require('@dsabot/isString');
const { db } = require('../globals');
module.exports = {
name: 'talent',
description:
@ -17,69 +18,82 @@ module.exports = {
usage: '<Talent> [<-Erschwernis> / <+Erleichterung>]',
needs_args: true,
async exec(message, args) {
db.find({ user: message.author.tag }, (err, docs) => {
if (docs.length === 0) {
return message.reply(findMessage('NOENTRY'));
}
if (!isNaN(args[0])) {
return message.reply(findMessage('WRONG_ARGUMENTS'));
}
db.find({ user: message.author.tag })
.then(docs => {
if (docs.length === 0) {
return message.reply(findMessage('NOENTRY'));
}
if (!isString(args[0])) {
return message.reply(findMessage('WRONG_ARGUMENTS'));
}
const Skill = getSkill({ Character: docs[0].character, args: args });
if (!Skill) {
return message.reply(findMessage('TALENT_UNKNOWN'));
}
const Skill = getSkill({ Character: docs[0].character, args: args });
if (!Skill) {
return message.reply(findMessage('TALENT_UNKNOWN'));
}
const Attributes = Skill.Attributes;
const DiceThrow = roll(3, 20, message.author.tag).dice;
const Bonus = parseInt(args[1]) || 0;
let { Passed, CriticalHit, Fumbles, PointsUsed, PointsRemaining } = CompareResults(
DiceThrow,
Attributes.map(attr => attr.Level),
Bonus,
Skill.Level
);
const Reply = new Discord.MessageEmbed();
Reply.addFields({
name: `Du würfelst auf das Talent **${Skill.Name}** (Stufe ${Skill.Level} + ${Bonus})`,
value: CreateResultTable({
Attributes: Attributes,
Throws: DiceThrow,
PointsUsed: PointsUsed,
Bonus: Bonus,
}),
inline: false,
const { Attributes } = Skill;
const DiceThrow = roll(3, 20, message.author.tag).dice;
const Bonus = parseInt(args[1], 10) || 0;
const {
Passed,
CriticalHit,
Fumbles,
PointsUsed,
PointsRemaining,
} = CompareResults(
DiceThrow,
Attributes.map(attr => attr.Level),
Bonus,
Skill.Level
);
const Reply = new Discord.MessageEmbed();
Reply.addFields({
name: `Du würfelst auf das Talent **${Skill.Name}** (Stufe ${Skill.Level} + ${Bonus})`,
value: CreateResultTable({
Attributes: Attributes,
Throws: DiceThrow,
PointsUsed: PointsUsed,
Bonus: Bonus,
}),
inline: false,
});
if (Fumbles >= 2) {
Reply.setColor('#900c3f');
Reply.addFields({
name: findMessage('TITLE_CRIT_FAILURE'),
value: findMessage('MSG_CRIT_FAILURE'),
inline: false,
});
} else if (CriticalHit >= 2) {
Reply.setColor('#1E8449');
Reply.addFields({
name: findMessage('TITLE_CRIT_SUCCESS'),
value: findMessage('MSG_CRIT_SUCCESS'),
inline: false,
});
} else if (Passed < 3) {
Reply.addFields({
name: findMessage('TITLE_FAILURE'),
value: `${
Passed === 0 ? 'Keine Probe' : `nur ${Passed}/3 Proben`
} erfolgreich. 😪`,
inline: false,
});
} else {
Reply.addFields({
name: findMessage('TITLE_SUCCESS'),
value: `Dein verbleibender Bonus: ${PointsRemaining}/${
Skill.Level
} (QS${CalculateQuality(PointsRemaining)})`,
inline: false,
});
}
return message.reply(Reply);
})
.catch(err => {
message.reply(findMessage('ERROR'));
throw new Error(err);
});
if (Fumbles >= 2) {
Reply.setColor('#900c3f');
Reply.addFields({
name: findMessage('TITLE_CRIT_FAILURE'),
value: findMessage('MSG_CRIT_FAILURE'),
inline: false,
});
} else if (CriticalHit >= 2) {
Reply.setColor('#1E8449');
Reply.addFields({
name: findMessage('TITLE_CRIT_SUCCESS'),
value: findMessage('MSG_CRIT_SUCCESS'),
inline: false,
});
} else if (Passed < 3) {
Reply.addFields({
name: findMessage('TITLE_FAILURE'),
value: `${Passed === 0 ? 'Keine Probe' : `nur ${Passed}/3 Proben`} erfolgreich. 😪`,
inline: false,
});
} else {
Reply.addFields({
name: findMessage('TITLE_SUCCESS'),
value: `Dein verbleibender Bonus: ${PointsRemaining}/${Skill.Level} (QS${CalculateQuality(
PointsRemaining
)})`,
inline: false,
});
}
message.reply(Reply);
});
},
};

View File

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

View File

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

View File

@ -1,41 +1,38 @@
const globals = require('../globals');
const Discord = require('discord.js');
const { Capitalize } = require('@dsabot/Capitalize');
module.exports = {
name: 'weapons',
description: 'Listet eine Übersicht, welche für einen Angriff genutzt werden können.',
aliases: ['waffen'],
usage: '',
needs_args: false,
async exec(message, args) {
const Embed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Waffenübersicht')
.setDescription('Folgende Waffen können für einen Angriff genutzt werden:');
for (let Technique of GenerateWeaponList()) {
Embed.addField(Technique.Technique_Name, Technique.Weapons.join('\n'), true);
}
message.author.send(
Embed,
);
},
};
const { CombatTechniques } = require('../globals');
const { Weapons } = require('../globals');
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();
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 = {
name: 'weapons',
description: 'Listet eine Übersicht, welche für einen Angriff genutzt werden können.',
aliases: ['waffen'],
usage: '',
needs_args: false,
async exec(message) {
const Embed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Waffenübersicht')
.setDescription('Folgende Waffen können für einen Angriff genutzt werden:');
const WeaponList = GenerateWeaponList();
WeaponList.forEach(Technique => {
Embed.addField(Technique.Technique_Name, Technique.Weapons.join('\n'), true);
});
return message.author.send(Embed);
},
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,7 +1,7 @@
const globals = require('../globals');
const { Replies } = require('../globals');
const findMessage = (value) => {
return globals.Replies.find(r => r.id === value).string;
const findMessage = value => {
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 = {}) => {
let AttributeId;
let AttributeLevel;
let AttributeList = [];
for (let Attribute of Attributes) {
AttributeId = globals.Werte.find(att => att.kuerzel === Attribute).id;
AttributeLevel = Character.attributes.find(att => att.id === AttributeId).level;
AttributeList.push({ Name: Attribute, Level: AttributeLevel });
}
const AttributeList = [];
Attributes.forEach(Attribute => {
const { id } = Werte.find(att => att.kuerzel === Attribute);
const { level } = Character.attributes.find(att => att.id === id);
AttributeList.push({ Name: Attribute, Level: level });
});
return AttributeList;
};
module.exports = { getAttributeLevels };

View File

@ -1,28 +1,24 @@
const { getAttributeLevels } = require('@dsabot/getAttributeLevels');
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;
let chant_entry =
Chants.find(chant => chant.id.toLowerCase() === chant_name.toLowerCase()) ||
Chants.find(chant => chant.name.toLowerCase() === chant_name.toLowerCase());
const chantEntry =
Chants.find(chant => chant.id.toLowerCase() === chantName.toLowerCase()) ||
Chants.find(chant => chant.name.toLowerCase() === chantName.toLowerCase());
if (!chant_entry) {
console.log(`getChant() Did not find entry for ${chant_name}`);
return;
if (!chantEntry) {
console.log(`getChant() Did not find entry for ${chantName}`);
return null;
}
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')) {
Level = Chant.level || 0;
}
let Attributes = getAttributeLevels(chant_entry.attributes, Character);
const Attributes = getAttributeLevels(chantEntry.attributes, Character);
return {
Name: chant_entry.name,
Level: Level,
Attributes: Attributes,
};
return { Name: chantEntry.name, Level: Level, Attributes: Attributes };
};
module.exports = { getChant };

View File

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

View File

@ -1,27 +1,27 @@
const { getAttributeLevels } = require('@dsabot/getAttributeLevels');
const Spells = require('@Lib/Spells.json');
const getSpell = ({ Character: Character = [], spell_name: spell_name = '' } = {}) => {
const spell_entry =
Spells.find(spell => spell.id.toLowerCase() === spell_name.toLowerCase()) ||
Spells.find(spell => spell.name.toLowerCase() === spell_name.toLowerCase());
const getSpell = ({ Character: Character = [], spell_name: spellName = '' } = {}) => {
const spellEntry =
Spells.find(spell => spell.id.toLowerCase() === spellName.toLowerCase()) ||
Spells.find(spell => spell.name.toLowerCase() === spellName.toLowerCase());
if (!spell_entry) {
console.log(`getSpell() did not find entry for ${spell_name}`);
return;
if (!spellEntry) {
console.log(`getSpell() did not find entry for ${spellName}`);
return null;
}
let Level = 0; // This is the minimum attributes value.
if (!Character.hasOwnProperty('spells')) return;
let Spell = Character.spells.find(spell => spell.id === spell_entry.id) || {}; //?+
if (!Character.hasOwnProperty('spells')) return null;
const Spell = Character.spells.find(spell => spell.id === spellEntry.id) || null; //?+
if (Spell && Spell.hasOwnProperty('level')) {
Level = Spell.level || 0;
}
let ModifiedBy = spell_entry.modified_by;
let Attributes = getAttributeLevels(spell_entry.attributes, Character);
const ModifiedBy = spellEntry.modified_by;
const Attributes = getAttributeLevels(spellEntry.attributes, Character);
return {
Name: spell_entry.name,
Name: spellEntry.name,
Level: Level,
Attributes: Attributes,
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 Datastore = require('nedb'),
db = new Datastore({
const Datastore = require('nedb-promises')
const db = Datastore.create({
filename: 'data/dsabot.db',
autoload: false,
});
const MessageEmbed = new Discord.MessageEmbed();
const money = [{
'GD': 'Golddukaten',
'ST': 'Silbertaler',
}];
const DiceRegex = /\s?[DdWw]\s?|(?=\-|\+)/;
const DiceRegex = /\s?[DdWw]\s?|(?=-|\+)/;
const Coin = ['Kopf', 'Zahl'];
const Werte = [
{ id: 'mut', kuerzel: 'MU', name: 'Mut' },
@ -147,7 +144,8 @@ const Replies = [
{ id: 'NO_CHANTS', string: 'Du kennst keine Liturgien.' },
{ id: 'CHANTS_TITLE', string: 'Liturgien'},
{ 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 Articles = ['Der','Die','Das',''];
@ -233,12 +231,4 @@ const 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 };

137
index.js
View File

@ -2,64 +2,13 @@ require('module-alias/register');
require('dotenv').config();
const fs = require('fs');
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 { findMessage } = require('@dsabot/findMessage');
const { db } = require('./globals');
db.load();
const cmdprefix = process.env.CMDPREFIX || '!';
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) {
try {
@ -71,26 +20,60 @@ function validateJSON(body) {
}
async function CreateFromFile(message, data) {
try {
db.find(
{
db.find({
user: message.author.tag,
}).then(docs => {
if (docs.length === 0) {
db.insert({
uid: `${message.author.id}`,
user: message.author.tag,
},
function (err, docs) {
if (docs.length === 0) {
db.insert(
{
user: message.author.tag,
character: data,
},
function (err, docs) {
message.reply(globals.Replies.find(r => r.id === 'SAVED_DATA').string);
}
);
}
}
);
} catch (e) {
throw e;
}
character: data,
}).then(() => {
message.reply(findMessage('SAVED_DATA'));
});
}
});
}
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(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);
});

27834
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,43 +1,47 @@
{
"name": "dsabot",
"version": "1.5.2",
"description": "",
"main": "index.js",
"scripts": {
"lint": "eslint commands/",
"start": "node index.js",
"test": "jest --collectCoverage"
},
"_moduleAliases": {
"@dsabot": "functions",
"@data": "data",
"@Commands": "commands",
"@Lib": "lib"
},
"author": "",
"license": "ISC",
"dependencies": {
"discord.js": "^12.5.3",
"dotenv": "^8.2.0",
"module-alias": "^2.2.2",
"nedb": "^1.8.0",
"node-fetch": "^2.6.1",
"random": "^3.0.6"
},
"devDependencies": {
"@types/jest": "^26.0.23",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.8.0",
"jest": "^26.6.3",
"rewire": "^5.0.0"
},
"jest": {
"collectCoverage": true,
"collectCoverageFrom": [
"**/*.{js,jsx}",
"!**/node_modules/**",
"!**/vendor/**"
],
"coverageDirectory": "coverage"
}
"name": "dsabot",
"version": "1.6.1",
"description": "",
"main": "index.js",
"scripts": {
"lint": "eslint commands/",
"start": "node index.js",
"test": "jest --collectCoverage"
},
"_moduleAliases": {
"@dsabot": "functions",
"@data": "data",
"@Commands": "commands",
"@Lib": "lib"
},
"author": "",
"license": "ISC",
"dependencies": {
"discord.js": "^12.5.3",
"dotenv": "^8.2.0",
"module-alias": "^2.2.2",
"nedb-promises": "^4.1.2",
"node-fetch": "^2.6.1",
"random": "^3.0.6"
},
"devDependencies": {
"@types/jest": "^26.0.23",
"babel-plugin-rewire": "^1.2.0",
"eslint": "^6.8.0",
"eslint-config-airbnb": "^18.2.1",
"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",
"rewire": "^5.0.0"
},
"jest": {
"collectCoverage": true,
"collectCoverageFrom": [
"**/*.{js,jsx}",
"!**/node_modules/**",
"!**/vendor/**"
],
"coverageDirectory": "coverage"
}
}