Refactoring (#29)

* refactor Attack command

* add test to Attack functions

* changed README.md

* install dev dependency rewire

* stop autoloading due to ci errors
This commit is contained in:
2021-04-30 23:14:27 +02:00
committed by GitHub
parent edcfba3d7b
commit f22df0dec1
7 changed files with 1859 additions and 171 deletions

View File

@ -1,7 +1,7 @@
[![CodeQL](https://github.com/TobenderZephyr/dsabot/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/TobenderZephyr/dsabot/actions/workflows/codeql-analysis.yml)
# DSA Discord Bot
![GitHub package.json version](https://img.shields.io/github/package-json/v/TobenderZephyr/dsabot?style=flat-square) ![node-current](https://img.shields.io/node/v/discord.js?style=flat-square) ![GitHub last commit](https://img.shields.io/github/last-commit/TobenderZephyr/dsabot?style=flat-square) ![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/TobenderZephyr/dsabot-docker/Build%20Image%20on%20Push/main?label=docker%20image&style=flat-square) ![Docker Pulls](https://img.shields.io/docker/pulls/tobenderzephyr/dsabot) [![CodeQL](https://github.com/TobenderZephyr/dsabot/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/TobenderZephyr/dsabot/actions/workflows/codeql-analysis.yml)
This Project is a fork of LucaSchwan/dsa-bot.
It is a Discord.js Bot written in JavaScript to support playing the German Pen & Paper RPG "Das Schwarze Auge" (The Dark Eye). The Bot has a built-in Database based on Endb and can handle character sheets from [The Dark Aid](https://www.ulisses-ebooks.de/product/212543/The-Dark-Aid-alpha).

View File

@ -0,0 +1,145 @@
require('module-alias/register');
const rewire = require('rewire');
const rewireUtils = rewire('@Commands/Attack');
const getWeapon = rewireUtils.__get__('getWeapon');
const getAttributeLevel = rewireUtils.__get__('getAttributeLevel');
const getCombatTechniqueLevel = rewireUtils.__get__('getCombatTechniqueLevel');
const isMeleeWeapon = rewireUtils.__get__('isMeleeWeapon');
const getAttribute = rewireUtils.__get__('getAttribute');
const CompareAttackResult = rewireUtils.__get__('CompareAttackResult');
const getCombatTechnique = rewireUtils.__get__('getCombatTechnique');
it('should be undefined without value', () => {
expect(getCombatTechnique({})).toBeUndefined();
});
it('should return defined object', () => {
expect(getCombatTechnique({ combattechnique: 'dolche' })).toEqual(
expect.objectContaining({
id: expect.any(String),
name: expect.any(String),
Leiteigenschaft: expect.anything(),
})
);
});
test('getAttribute should return Object', () => {
const obj = { id: 'mut', kuerzel: 'MU', name: 'Mut' };
expect(getAttribute('KK')).toEqual(
expect.objectContaining({
id: expect.any(String),
kuerzel: expect.any(String),
name: expect.any(String),
})
);
expect(getAttribute('MU')).toEqual(obj);
});
test('CompareAttackResults', () => {
expect(CompareAttackResult()).toEqual(
expect.objectContaining({
Ok: expect.any(Boolean),
Patzer: expect.any(Boolean),
CriticalHit: expect.any(Boolean),
DoubleDamage: expect.any(Boolean),
Dice: expect.anything(),
})
);
});
it('should return object with fumble', () => {
const obj = {
Ok: false,
Patzer: true,
CriticalHit: false,
DoubleDamage: false,
Dice: [20, 14],
};
expect(CompareAttackResult([20, 14], 8)).toEqual(obj);
});
it('should return object with crit', () => {
const obj = {
Ok: true,
Patzer: false,
CriticalHit: true,
DoubleDamage: false,
Dice: [1, 14],
};
expect(CompareAttackResult([1, 14], 8)).toEqual(obj);
});
it('should return object with double damage', () => {
const obj = {
Ok: true,
Patzer: false,
CriticalHit: true,
DoubleDamage: true,
Dice: [1, 4],
};
expect(CompareAttackResult([1, 4], 8)).toEqual(obj);
});
it('should return object without passing', () => {
const obj = {
Ok: false,
Patzer: false,
CriticalHit: false,
DoubleDamage: false,
Dice: [10],
};
expect(CompareAttackResult([10, 14], 8)).toEqual(obj);
});
it('returns a number ', () => {
expect(getAttributeLevel({ attributes: [{ id: 'mut', level: 8 }] }, 'mut')).toBe(8);
});
it('returnsa defined object ', () => {
const Player = { combattechniques: [{ id: 'dolche', level: 9 }] };
const CombatTechnique = { name: 'Dolche', id: 'dolche', Leiteigenschaft: ['GE'] };
expect(getCombatTechniqueLevel(Player, CombatTechnique)).toEqual(
expect.objectContaining({
id: expect.any(String),
name: expect.any(String),
level: expect.any(Number),
Leiteigenschaft: expect.any(Array),
})
);
});
it('returns a defined object ', () => {
expect(getWeapon('waqqif')).toEqual(
expect.objectContaining({
id: expect.any(String),
name: expect.any(String),
dice: expect.any(Number),
diemodificator: expect.any(Number),
at_mod: expect.any(Number),
pa_mod: expect.any(Number),
article: expect.any(Number),
DmgThreshold: expect.any(Number),
combattechnique: expect.any(String),
})
);
});
it('returns true ', () => {
expect(isMeleeWeapon({ id: 'waqqif' })).toBeTruthy();
});
it('returns false ', () => {
expect(isMeleeWeapon({ id: 'bogen' })).toBeFalsy();
});
// main function
/*
it('should abort with a message', () => {
const message = {
reply: function (e) {
throw new Error(e);
},
};
const err = 'error';
const handleAttack = rewireUtils.__get__('handleAttack');
expect(handleAttack(err)).toThrowError();
//expect(handleAttack(null, [])).toThrowError();
});
*/

View File

@ -1,124 +1,149 @@
require('module-alias/register');
const globals = require('../globals');
const db = globals.db;
const Random = require('random');
//const { roll } = require('@dsabot/Roll');
const { findMessage }= require('@dsabot/findMessage');
const { roll } = require('@dsabot/Roll');
const { findMessage } = require('@dsabot/findMessage');
module.exports = {
name: 'attack',
description: 'Würfelt den Attackewert auf eine Nahkampfwaffe.',
aliases: ['angriff','attacke'],
usage: '<Waffe>',
needs_args: true,
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,
}, function(err, docs) {
if (docs.length === 0) {
return message.reply(findMessage('NOENTRY'));
}
else {
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); }
// Determining Both Attack and Ranged Attack Values.
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; }
let Attribute;
let AttackValue = CombatTechniqueValue;
if (globals.MeleeWeapons.find(MeleeWeapon => MeleeWeapon.id === Weapon.id)) {
// For melee combat, MU is used for determining the Attack Value. Also, any weapon-based attack modifiers apply.
Attribute = Player.attributes.find(a => a.id === 'mut').level;
AttackValue += Weapon.at_mod;
}
else {
// For ranged combat, FF is used for determining Attack Value
Attribute = Player.attributes.find(a => a.id === 'fingerfertigkeit').level;
}
AttackValue += Math.floor((Attribute - 8)/3);
let dice = [];
let Bonus = 0;
if(args[1] && !isNaN(parseInt(args[1]))) { Bonus = parseInt(args[1]); }
let Comparison = Math.floor(AttackValue + Bonus);
let CriticalHit = false;
let Patzer = false;
let Ok = false;
let DoubleDamage = false;
for (let i = 0; i < 2; i++) {
dice.push(Random.int(1,20));
}
// If there is a cleaner way to do these checks, I'm all into it.
if((dice[0] == 1) && dice[1] <= Comparison) { CriticalHit = true; DoubleDamage = true; Ok = true; }
else if((dice[0] == 1) && dice[1] > Comparison) { CriticalHit = true; Ok = true; }
else if((dice[0] == 20) && dice[1] > Comparison) { Patzer = true; }
else if(dice[0] <= Comparison && !CriticalHit) { Ok = true; dice.pop(); }
else if(dice[0] > Comparison ) { dice.pop(); }
let Reply = 'Du greifst mit ' + globals.Declination[Weapon.article] + ' ' + Weapon.name + ' an.\n';
Reply += 'Dein Angriffswert für ' + CombatTechnique.name + ' ist ' + Math.floor(((Attribute - 8)/3) + CombatTechniqueValue) + '. (KtW: ' + CombatTechniqueValue + ')\n';
Reply += 'Deine 🎲: ` ' + dice.join(', ') + ' `.\n\n';
if(!Ok) {
Reply += globals.Replies.find(reply => reply.id === 'COMBAT_FAIL').string;
if(Patzer) { Reply += globals.Replies.find(reply => reply.id === 'COMBAT_CRIT_FAIL').string; }
}
else {
if(CriticalHit) { Reply += globals.Replies.find(reply => reply.id === 'COMBAT_CRIT_SUCCESS').string; }
if(DoubleDamage) { Reply += globals.Replies.find(reply => reply.id === 'COMBAT_DOUBLEDAMAGE').string; }
if(!CriticalHit) { Reply += globals.Replies.find(reply => reply.id === 'COMBAT_SUCCESS').string; }
// adding 1 to damage for every point above weapon's "Leiteigenschaft"
// applies only to Melee Weapons.
let AttackBonus = 0;
if (globals.MeleeWeapons.find(MeleeWeapon => MeleeWeapon.id === Weapon.id))
{
if(Weapon.DmgThreshold) {
CombatTechnique.Leiteigenschaft.forEach(LEKuerzel => {
let Leiteigenschaft = globals.Werte.find(attribute => attribute.kuerzel === LEKuerzel);
let DmgThreshold = Weapon.DmgThreshold;
let AttributeValue = Player.attributes.find(attribute => attribute.id === Leiteigenschaft.id).level;
if(DmgThreshold<AttributeValue) {
AttackBonus += Math.floor(AttributeValue - DmgThreshold);
}
});
}
}
const DieModificator = Weapon.diemodificator;
let Damage = DieModificator + AttackBonus;
let DamageDice = [];
for (let i = 0; i < Weapon.dice; i++) {
DamageDice.push(Random.int(1,6));
}
DamageDice.forEach(result => {
Damage += result;
});
if(DoubleDamage) { Damage *= 2; }
Reply += '\n\nHier aufklappen, wenn der Gegner nicht parieren/Ausweichen konnte:\n';
Reply += '||' + globals.Articles[Weapon.article] + ' ' + Weapon.name + ' (' + Weapon.dice + 'W6+' + Weapon.diemodificator +') erzielt ` ' + Damage + ' ` Schaden.';
Reply += '\nDeine 🎲: ` ' + DamageDice.join(',') + ' `.||\n';
}
return message.reply( Reply );
}
});
}
catch (e) {
throw e;
}
},
async exec(message, args) {
try {
db.find({ user: message.author.tag }, (err, docs) => handleAttack(err, docs, message));
} catch (e) {
throw e;
}
},
};
function handleAttack(err, docs, message) {
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.`;
Reply += '\nDeine 🎲: ` ' + DamageDice.join(',') + ' `.||\n';
}
return message.reply(Reply);
}
function getCombatTechnique(Weapon) {
if (Weapon)
return globals.CombatTechniques.find(technique => technique.id === Weapon.combattechnique);
}
function getAttribute(abbr) {
return globals.Werte.find(attribute => attribute.kuerzel === abbr);
}
function CompareAttackResult(dice = [8, 8], Comparison = 6) {
let ok = false,
crit = false,
dd = false,
fumble = false;
dice.forEach((val, index) => {
if (index === 0) {
ok = val <= Comparison ? true : false;
crit = val === 1 ? true : false;
fumble = val === 20 ? true : false;
if ((ok && !crit) || (!ok && !fumble)) {
dice.pop();
}
}
if (index === 1) {
dd = crit && val < Comparison ? true : false;
fumble = !crit && val > Comparison ? true : false;
}
});
return {
Ok: ok,
Patzer: fumble,
CriticalHit: crit,
DoubleDamage: dd,
Dice: dice,
};
}
function getAttributeLevel(Player = {}, Attribute = '') {
return Player.attributes.find(a => a.id === Attribute).level;
}
function getCombatTechniqueLevel(Player = {}, CombatTechnique = {}) {
if (Player && CombatTechnique) {
const p = Player.combattechniques.find(technique => technique.id === CombatTechnique.id);
return {
id: CombatTechnique.id,
name: CombatTechnique.name,
level: p ? p.level : 6,
Leiteigenschaft: CombatTechnique.Leiteigenschaft,
};
}
}
function getWeapon(Weapon = '') {
if (Weapon)
return globals.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;
}

View File

@ -2,7 +2,7 @@ const Discord = require('discord.js');
const Datastore = require('nedb'),
db = new Datastore({
filename: 'data/dsabot.db',
autoload: true,
autoload: false,
});
const MessageEmbed = new Discord.MessageEmbed();
const money = [{

127
index.js
View File

@ -4,6 +4,7 @@ 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 client = new Discord.Client();
@ -11,75 +12,85 @@ client.commands = new Discord.Collection();
client.on('message', commandHandler);
client.login(process.env.BOT_TOKEN);
client.once('ready', () => {
console.log('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);
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);
}
}
//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 {
const data = body.json();
return data;
} catch (e) {
return null;
}
try {
const data = body.json();
return data;
} catch (e) {
return null;
}
}
async function CreateFromFile(message, data) {
try {
db.find({
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;
}
try {
db.find(
{
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;
}
}

1504
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -26,10 +26,15 @@
},
"devDependencies": {
"@types/jest": "^26.0.23",
"jest": "^26.6.3"
"jest": "^26.6.3",
"rewire": "^5.0.0"
},
"jest": {
"collectCoverage": true,
"collectCoverageFrom": ["**/*.{js,jsx}", "!**/node_modules/**", "!**/vendor/**"]
"collectCoverageFrom": [
"**/*.{js,jsx}",
"!**/node_modules/**",
"!**/vendor/**"
]
}
}