Skip to content

Commit

Permalink
chore(bot): use logger instead of console log (#478)
Browse files Browse the repository at this point in the history
  • Loading branch information
yadPe authored Mar 29, 2022
1 parent 3d97c59 commit 43a4d73
Show file tree
Hide file tree
Showing 9 changed files with 116 additions and 80 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@
"dependencies": {
"discord-rpc": "^3.2.0",
"electron-is-dev": "^1.1.0",
"electron-log": "^4.3.4",
"electron-log": "^4.4.6",
"electron-updater": "^4.3.8",
"electron-window-state": "^5.0.3",
"fs-extra": "^9.1.0",
Expand Down Expand Up @@ -239,4 +239,4 @@
"react-app"
]
}
}
}
48 changes: 22 additions & 26 deletions src/Bot/BeatconnectApi.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,35 @@
import ElectronLog from 'electron-log';
import config from '../shared/config';

const logger = ElectronLog.scope('bot-beatconnect-api');

const BeatmapStatus = Object.freeze({
'4': 'Loved',
'3': 'Qualified',
'2': 'Approved',
'1': 'Ranked',
'0': 'Pending',
'-1': 'WIP',
'-2': 'Graveyard',
});

class BeatconnectApi {
constructor(key) {
this.key = key;
this.url = 'https://beatconnect.io/api';
this.status = {
'4': 'Loved',
'3': 'Qualified',
'2': 'Approved',
'1': 'Ranked',
'0': 'Pending',
'-1': 'WIP',
'-2': 'Graveyard',
};
this.status = BeatmapStatus;
}

getBeatmapById(beatmapId) {
console.log(beatmapId);
logger.log('getBeatmapById', beatmapId);
return fetch(config.api.getBeatmapById(beatmapId), { mode: 'cors' })
.then(res => res.json())
.catch(err => console.error(err));
.catch(logger.error);
}

searchBeatmap(query, page) {
query = query.join('%20');
console.log('searching ' + query);
searchBeatmap(rawQuery, page) {
logger.log('searching ' + query);
const query = encodeURI(rawQuery);
return fetch(config.api.searchBeatmaps(query, page))
.then(res => res.json())
.then(results => {
Expand All @@ -45,26 +50,17 @@ class BeatconnectApi {
}`
);
})
.catch(err => console.error(err));
.catch(ElectronLog.error);
}
}

const getDlLink = (beatmapInfos, pretty, extra) => {
console.log('getdlLimk', beatmapInfos);
if (beatmapInfos.error) throw new Error(beatmapInfos.error); // Need Test
const { id, artist, title, unique_id } = beatmapInfos;
const status = {
'4': 'Loved',
'3': 'Qualified',
'2': 'Approved',
'1': 'Ranked',
'0': 'Pending',
'-1': 'WIP',
'-2': 'Graveyard',
};

if (extra) {
const { creator, approved, version, creator_id, bpm, max_combo, diff_approach } = extra;
return `[${status[approved] || ''}] [https://beatconnect.io/b/${id}/${unique_id} ${artist || ''} - ${title ||
return `[${BeatmapStatus[approved] || ''}] [https://beatconnect.io/b/${id}/${unique_id} ${artist || ''} - ${title ||
''} [${version || ''}]] by [https://osu.ppy.sh/u/${creator_id} ${creator || 'peppy'}] | BPM ${bpm ||
0} | AR ${diff_approach || 0} ${max_combo ? '| Max combo: ' + max_combo : ''}`;
}
Expand Down
46 changes: 26 additions & 20 deletions src/Bot/Bot.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import ElectronLog from 'electron-log';
import OsuIrc from './OsuIrc';
import OsuApi from './OsuApi';
import MpMatch from './multiplayer/mpMatch';
import store from '../shared/store';
import { updateMatchsList } from './actions';
import { BeatconnectApi, getDlLink } from './BeatconnectApi';

const { BeatconnectApi, getDlLink } = require('./BeatconnectApi');
const botLogger = ElectronLog.scope('Bot');

class Bot {
constructor(configFile) {
Expand Down Expand Up @@ -47,18 +49,18 @@ class Bot {
.then(response => getDlLink(response, true, extra))
.then(link => this.irc.pm(to, link))
.catch(err => {
console.error(err);
botLogger.error('sendMapById failed ', err);
this.irc.pm(to, 'oops ! Cannot get beatmap');
});
}

newMatch(id, matchName, ircRoom, creator, playerList) {
console.log(`New match created : ${id} ${matchName} ${ircRoom} ${creator}`);
botLogger.info(`Creating new match : ${id} ${matchName} ${ircRoom} ${creator}`);
let alreadyExist = false;
this.matchs.forEach(match => {
if (match.id === id) alreadyExist = true;
});
if (alreadyExist) return;
if (alreadyExist) return botLogger.info(`Match with id ${id} already exist! Doing nothing..`);
const newMatch = new MpMatch(
id,
matchName,
Expand All @@ -73,49 +75,53 @@ class Bot {
newMatch.players = playerList;
}
this.matchs.push(newMatch);
//this.web.matchs = this.matchs;
updateMatchsList(this.matchs);
console.log(this.matchs);
botLogger.info('New match created, current matchs : ', this.matchs);
}

endMatch(matchId) {
this.matchs = this.matchs.filter(match => match.id !== matchId);
updateMatchsList(this);
console.log(`Current matchs : ${this.matchs}`);
botLogger.info(`Match ${matchId} ended`);
botLogger.debug('Current matchs :', this.matchs);
}

newBeatmap(beatmapId, matchId) {
botLogger.info(`Beatmap changed ${beatmapId} for match ${matchId}!`);
this.osuApi
.getSetId(beatmapId)
.then(beatmap =>
this.matchs.forEach(match => {
if (match.id === matchId) {
this.beatconnect.getBeatmapById(beatmap.beatmapset_id).then(response => {
console.log('Beatconnect', response);
beatmap = { ...beatmap, ...response };
match.updateBeatmap(beatmap).then(() => updateMatchsList(this.matchs));
console.log('osu', beatmap, this.matchs);
return;
});
this.beatconnect
.getBeatmapById(beatmap.beatmapset_id)
.then(response => {
botLogger.log('Beatconnect', response);
beatmap = { ...beatmap, ...response };
match.updateBeatmap(beatmap).then(() => updateMatchsList(this.matchs));
botLogger.log('osu', beatmap, this.matchs);
return;
})
.catch(botLogger.error);
}
}),
)
.catch(err => console.error(err));
.catch(botLogger.error);
}

np(beatmapId, from) {
this.osuApi
.getSetId(beatmapId)
.then(res => this.sendMapById(res.beatmapset_id, from))
.catch(err => console.error(err));
.catch(botLogger.error);
}

joinMatch(reqMatchId, from) {
this.irc
.joinMatch(reqMatchId)
.then(({ matchId, playerList }) => this.newMatch(matchId, null, `#mp_${matchId}`, null, playerList))
.catch(err => {
console.error(err);
botLogger.error(err);
if (from) this.irc.pm(from, 'Cannot find this room');
store.dispatch({ type: 'ERROR', payload: reqMatchId });
});
Expand Down Expand Up @@ -146,7 +152,7 @@ class Bot {
const player = args[1].split(' ').shift();
match.host = player;
updateMatchsList(this.matchs);
console.log(`Host for ${match.matchName} is now ${player}`);
botLogger.info(`Host for ${match.matchName} is now ${player}`);
} else if (
args[1].includes('Room name: ') ||
args[1].includes('Room name: ') ||
Expand Down Expand Up @@ -195,15 +201,15 @@ class Bot {
.makeMatch(params[0], from)
.then(({ matchId, name, matchRoom, creator }) => this.newMatch(matchId, name, matchRoom, creator))
.catch(err => {
console.error(err);
botLogger.error(err);
this.irc.pm(from, 'Unable to create the match, maybe you already have too many matchs currently open');
});
break;
case this.commandsList[1]: // search
this.beatconnect
.searchBeatmap(params)
.then(result => this.irc.pm(fromMp || from, result))
.catch(err => console.error(err));
.catch(err => botLogger.error(err));
break;
case this.commandsList[4]: // beat
if (!fromMp) {
Expand Down
5 changes: 1 addition & 4 deletions src/Bot/OsuApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,7 @@ class OsuApi {
}

getSetId(beatmapId) {
return this.request('get_beatmaps', [{ param: 'b', value: beatmapId }]).then(res => {
console.log(res[0].beatmapset_id);
return res[0];
});
return this.request('get_beatmaps', [{ param: 'b', value: beatmapId }]).then(res => res[0]);
}
}

Expand Down
43 changes: 28 additions & 15 deletions src/Bot/OsuIrc.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import ElectronLog from 'electron-log';
import { EventEmitter } from 'events';
import { remote } from 'electron';
import irc from 'irc';
import store from '../shared/store';

const irc = require('irc');
const EventEmitter = require('events').EventEmitter;
const logger = ElectronLog.scope('bot-irc-client');

class OsuIrc {
constructor(onMessage, onMpMessage, np, endMatch, config) {
this.onMpMessage = onMpMessage;
Expand Down Expand Up @@ -40,11 +43,20 @@ class OsuIrc {
});
this.onError = err => {
// this.eventEmitter.emit('ircError', err); // wtf
console.error(`IRC Client error: ${err}`);
logger.error('IRC Client error', err);
switch (err.command) {
case 'err_nosuchchannel': {
remote.dialog.showErrorBox('Invalid match Id', `Details:\n${err.args.join('\n')}`);
break;
}
default:
break;
}
logger.error(err);
};
this.client.on('error', this.onError);
this.client.addListener('message', (from, channel, text, rawMsg) => {
console.log(rawMsg);
logger.log(`new message: \n${text}`, rawMsg);
onMessage(from, channel, text, rawMsg);
this.previousMessage = rawMsg;
});
Expand All @@ -59,7 +71,7 @@ class OsuIrc {
this.client.disconnect();
store.dispatch({ type: 'DISCONNECT' });
}
console.error('RECEIVED ERROR FROM IRC SERVER: ', msg.args);
logger.error('RECEIVED ERROR FROM IRC SERVER: ', msg.args);
}
if (msg.command === 'rpl_welcome') {
store.dispatch({ type: 'CONNECTED' });
Expand All @@ -75,7 +87,7 @@ class OsuIrc {
.split(' ')
.filter(player => !(player.startsWith('@') || player.startsWith('+') || player === ''));
const matchId = args[2].split('_').pop();
console.log(playerList, matchId, 'ICI');
logger.log(playerList, matchId, 'ICI');
this.eventEmitter.emit('namreply', { matchId, playerList });
}
if (msg.command === 'PART') {
Expand All @@ -85,10 +97,10 @@ class OsuIrc {
}
}
if (msg.args[1]) {
console.log(msg.args[1]);
logger.log(msg.args[1]);
if (msg.args[1].includes('ACTION is listening to')) {
const beatmapId = /.*?(\d+)/i.exec(msg.args[1])[1];
console.log(beatmapId);
logger.log(beatmapId);
this.np(beatmapId, msg.args[0].includes('mp') ? msg.args[0] : msg.nick);
}
}
Expand All @@ -102,10 +114,10 @@ class OsuIrc {
if (rawCommand === 'MODE' && args[1] === '+v' && args[0].includes('mp'))
this.eventEmitter.emit('newMatchCreated', rawMsg);
if (rawCommand === 'PRIVMSG' && args[1].includes('Created the tournament match')) {
const matchId = this.regExps[0].exec(args[1])[1];
const matchName = args[1].split(' ').pop();
const matchRoom = `#mp_${matchId}`;
//this.eventEmitter.emit('newMatchCreated', { matchId, matchName, matchRoom });
// const matchId = this.regExps[0].exec(args[1])[1];
// const matchName = args[1].split(' ').pop();
// const matchRoom = `#mp_${matchId}`;
// this.eventEmitter.emit('newMatchCreated', { matchId, matchName, matchRoom });
} else if (rawCommand === 'PRIVMSG' && args[0].includes('mp')) {
const matchId = args[0].split('_').pop();
this.onMpMessage(matchId, { rawMsg, from, channel, text });
Expand All @@ -119,7 +131,7 @@ class OsuIrc {
joinMatch(match_Id) {
return new Promise((resolve, reject) => {
const onError = err => {
console.log(err.command);
logger.error(err.command);
if (err.command === 'err_nosuchchannel') {
reject('No such channel');
}
Expand All @@ -140,6 +152,7 @@ class OsuIrc {
// TODO Don't work when called again before previous call is resolved - Need Fix //
makeMatch(name, creator) {
return new Promise((resolve, reject) => {
let timeout = 0;
const onNewMatch = msg => {
const { args } = msg;
clearTimeout(timeout);
Expand All @@ -148,9 +161,9 @@ class OsuIrc {
const matchId = args[0].split('_').pop();
resolve({ matchId, name, matchRoom, creator });
};
const timeout = setTimeout(() => {
timeout = setTimeout(() => {
this.eventEmitter.removeListener('newMatchCreated', onNewMatch);
reject('Timed out');
reject(new Error('Timed out'));
}, 5000);
this.client.say('banchobot', `!mp make ${name}`);
this.eventEmitter.on('newMatchCreated', onNewMatch);
Expand Down
11 changes: 7 additions & 4 deletions src/Bot/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import ElectronLog from 'electron-log';
import Bot from './Bot';
import store from '../shared/store';
import { getOsuApiKey } from '../App/modules/Settings/reducer/selectors';

const logger = ElectronLog.scope('bot');

export default () => {
const state = store.getState();
const { bot } = state;
Expand All @@ -14,15 +17,15 @@ export default () => {
};

const { connected, instance } = bot;

if (!instance.connect) {
console.log('connecting using new Bot');
logger.log('connecting using new Bot');
store.dispatch({ type: 'CONNECT', payload: { status: 'connecting', instance: new Bot(botSettings) } });
} else if (connected) {
console.log('disconnecting');
logger.log('disconnecting');
instance.disconnect();
} else {
console.log('connecting using existing Bot');
logger.log('connecting using existing Bot');
store.dispatch({ type: 'CONNECT', payload: { status: 'connecting' } });
instance.connect();
}
Expand Down
Loading

0 comments on commit 43a4d73

Please sign in to comment.