Skip to content

Commit

Permalink
Handle errors in default commands more properly
Browse files Browse the repository at this point in the history
  • Loading branch information
justinsmid committed Aug 18, 2020
1 parent 7b586a5 commit ba246c9
Show file tree
Hide file tree
Showing 6 changed files with 63 additions and 21 deletions.
5 changes: 3 additions & 2 deletions desktop/public/electron.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ function onAppReady() {
mainWindow = null
});

// mainWindow.webContents.openDevTools();
mainWindow.webContents.openDevTools();

global.mainWindow = mainWindow;

Expand Down Expand Up @@ -196,8 +196,9 @@ class ExpressServer {
console.log(`Handling [${method}] request for endpoint '${endpoint}'...`);

const response = await this.sendRequest(endpoint, {method: method, ...options});
const status = (response && response.httpStatus) || 200;

res.json(response);
res.status(status).send(response);
};

sendRequest(endpoint, options) {
Expand Down
2 changes: 1 addition & 1 deletion desktop/src/components/navBar/NavigationBar.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default ({currentPath}) => {
<Link
key={route.title}
id={route.title}
to={route.path}
to={route.linkPath}
onClick={toggleShowMenu}
className={`menu-item ${matchesCurrentPath ? 'current' : ''}`}
>
Expand Down
3 changes: 1 addition & 2 deletions desktop/src/pages/twitch/TwitchBot.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export default class TwitchBot {
const {commands} = this.pageRef.state;

if (!(commandName in commands)) {
this.client.say(ircChannel, `@${msgSenderData['display-name']}, the command '${commandName}' is unknown.`);
console.error(`[Twitch bot]: Command '${commandName}' unknown.`);
return false;
}
Expand All @@ -108,8 +109,6 @@ export default class TwitchBot {
}

onMessageHandler(target, msgSenderData, msg, self) {
console.log(msgSenderData);
console.log(this.pageRef);
if (self) return; // Ignore messages from the bot

let msgSegments = msg.split(' ');
Expand Down
9 changes: 5 additions & 4 deletions desktop/src/pages/twitch/TwitchPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ const DEFAULT_TRUSTED_USERS = [

let authWindow;

export const fetchTwitchApi = (url, options) => {
export const fetchTwitchApi = (url, accessToken, options) => {
accessToken = (accessToken || JSON.parse(getGlobal('twitchAuthStorage').getItem('accessToken')));

return fetch(url, {
...options,
headers: {
'Client-ID': TWITCH_APP_CLIENT_ID,
'Authorization': `Bearer ${JSON.parse(getGlobal('twitchAuthStorage').getItem('accessToken')).access_token}`
'Authorization': `Bearer ${accessToken.access_token}`
}
});
};
Expand Down Expand Up @@ -110,8 +112,7 @@ export default class TwitchPage extends Component {
}

updateTwitchUserFromToken(accessToken) {
console.log(`Updating twitch user from token`, accessToken);
fetchTwitchApi(`https://api.twitch.tv/helix/users/`)
fetchTwitchApi(`https://api.twitch.tv/helix/users/`, accessToken)
.then(jsonResponse)
.then(async res => {
const twitchUserData = res.data[0];
Expand Down
62 changes: 51 additions & 11 deletions desktop/src/pages/twitch/defaultCommands.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const parseStringifiedCommands = commandsStr => {

// eslint-disable-next-line
// return JSON.parse(commandsStr, (key, val) => key === 'execute' ? eval(val) : val);

const commands = JSON.parse(commandsStr);

// TODO: Store commands[execute]. This is a workaround and only works for default commands.
Expand Down Expand Up @@ -61,7 +61,7 @@ export const argumentFormatExplanation = format => {
return `Named - Arguments should be prefixed with '<name>=' and can be given in any order. ${ending}`;
default: throw new Error(`Argument format '${format}' not explained`);
}
}
};

// TODO: Perform checks for command args more properly, and for all commands that take args
export const defaultCommands = {
Expand Down Expand Up @@ -93,10 +93,17 @@ export const defaultCommands = {
format: '!lcu trust <username>',
requiredRole: RequiredRole.TRUSTED_PLUS,
execute: (args, twitchBot, msgSenderData, ircChannel) => {
if (args.length === 0) {
console.error(`Argument 'username' not provided for command 'trust'`);
twitchBot.client.say(ircChannel, `@${msgSenderData['display-name']}, please provide a username for command 'trust'`);
return;
}

const username = args[0];

if (!twitchBot.pageRef.state.trustedUsers.some(trustedUser => equalsIgnoreCase(trustedUser, username))) {
console.log(`[Twitch bot]: Trusting user '${username}'...`);
twitchBot.client.say(ircChannel, `@${msgSenderData['display-name']}, '${username}' is now trusted.`);

return twitchBot.pageRef.addTrustedUser(username);
} else {
Expand All @@ -112,10 +119,24 @@ export const defaultCommands = {
argumentData: null,
format: '!lcu accept-queue',
requiredRole: RequiredRole.MODS_PLUS,
execute: () => {
execute: (args, twitchBot, msgSenderData, ircChannel) => {
console.log('[Twitch bot]: Accepting queue...');
const url = `${getGlobal('serverUrl')}/request?endpoint=/lol-matchmaking/v1/ready-check/accept`;
return fetch(url, {method: 'POST'});
return fetch(url, {method: 'POST'})
.then(res => {
switch (res.status) {
case 404:
console.error('Attempted to accept queue, but no active queue was found.');
twitchBot.client.say(ircChannel, `@${msgSenderData['display-name']}, no active queue found to accept.`);
return res;
case 500:
console.error('Attempted to accept queue, but the current queue has not popped yet.');
twitchBot.client.say(ircChannel, `@${msgSenderData['display-name']}, the current queue has not popped yet.`);
return res;
case 200:
default: return res;
}
});
}
},
'decline-queue': {
Expand All @@ -125,10 +146,24 @@ export const defaultCommands = {
argumentData: null,
format: '!lcu decline-queue',
requiredRole: RequiredRole.MODS_PLUS,
execute: () => {
execute: (args, twitchBot, msgSenderData, ircChannel) => {
console.log('[Twitch bot]: Declining queue...');
const url = `${getGlobal('serverUrl')}/request?endpoint=/lol-matchmaking/v1/ready-check/decline`;
return fetch(url, {method: 'POST'});
return fetch(url, {method: 'POST'})
.then(res => {
switch (res.status) {
case 404:
console.error('Attempted to decline queue, but no active queue was found.');
twitchBot.client.say(ircChannel, `@${msgSenderData['display-name']}, no active queue found to decline.`);
return res.json();
case 500:
console.error('Attempted to decline queue, but the current queue has not popped yet.');
twitchBot.client.say(ircChannel, `@${msgSenderData['display-name']}, the current queue has not popped yet.`);
return res.json();
case 200:
default: return res;
}
});
}
},
'hover-champ': {
Expand All @@ -147,7 +182,7 @@ export const defaultCommands = {
},
format: '!lcu hover-champ <champion>',
requiredRole: RequiredRole.SUBSCRIBERS_PLUS,
execute: args => pickChamp(args, false)
execute: (args, twitchBot, msgSenderData, ircChannel) => pickChamp(args, false, 'hover-champ', twitchBot, msgSenderData, ircChannel)
},
'lock-champ': {
name: 'Lock in champion',
Expand All @@ -165,7 +200,7 @@ export const defaultCommands = {
},
format: '!lcu lock-champ <champion>',
requiredRole: RequiredRole.TRUSTED_PLUS,
execute: args => pickChamp(args, true)
execute: (args, twitchBot, msgSenderData, ircChannel) => pickChamp(args, true, 'lock-champ', twitchBot, msgSenderData, ircChannel)
},
'request': {
name: 'Send custom request',
Expand Down Expand Up @@ -271,12 +306,13 @@ const getChampionId = async ({arg, summonerId}) => {
};

// TODO: handle multiple champs that include given name, champion not being available
const pickChamp = async (args, lockIn = false) => {
const pickChamp = async (args, lockIn = false, command, twitchBot, msgSenderData, ircChannel) => {
console.clear();
console.log('[Twitch bot]: Picking champion...');

if (args.length === 0 || args.length > 1) {
console.error(`1 argument expected for pickChamp: championId or championName but instead got ${args.length}`, args);
if (args.length === 0) {
console.error(`Argument 'champion' not provided for command '${command}'`);
twitchBot.client.say(ircChannel, `@${msgSenderData['display-name']}, please provide a champion for command '${command}'`);
return;
}

Expand All @@ -287,20 +323,24 @@ const pickChamp = async (args, lockIn = false) => {
const championId = await getChampionId({arg: args[0], summonerId: mySummonerId});
if (!championId) {
console.error(`Could not find a champion matching ${args[0]}`);
twitchBot.client.say(ircChannel, `@${msgSenderData['display-name']}, could not find a champion matching '${args[0]}'`);
return;
}
console.log('Got championId', championId);

const champSelectSession = await fetch(`${getGlobal('serverUrl')}/request?endpoint=/lol-champ-select/v1/session`)
.then(async res => {
console.log('champ select session res before .json()', res);
res = await res.json();
console.log('champ select session res after .json()', res);
console.log(res, res.httpStatus === 404);
const returnValue = res.httpStatus === 404 ? null : res;
console.log('returnValue', returnValue);
return returnValue;
});
if (!champSelectSession) {
console.error(`No active champion select found`);
twitchBot.client.say(ircChannel, `@${msgSenderData['display-name']}, no active champion select found.`);
return;
}

Expand Down
3 changes: 2 additions & 1 deletion desktop/src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import TwitchPage from "./pages/twitch/TwitchPage";

export default [
{
path: '/twitch',
path: ['/', '/twitch'],
linkPath: '/twitch',
title: 'Twitch integration',
component: TwitchPage
}
Expand Down

0 comments on commit ba246c9

Please sign in to comment.