Skip to content

Commit

Permalink
Merge pull request #24 from taranvohra/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
Taran Vohra authored May 14, 2021
2 parents 24e4e13 + dccf45e commit 3ef362f
Show file tree
Hide file tree
Showing 9 changed files with 235 additions and 28 deletions.
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ Shows the `last 10` logs of the mentioned user.

Generates an `invite` for your server with no expiry and unlimited uses. If such an invite already exists, it re-uses that.

#### Pugs
### Pugs

**addgametype, agm** 🐱‍👤<br/>
`Usage -> .addgametype name totalPlayers totalTeams`
Expand Down Expand Up @@ -181,6 +181,21 @@ Generates an image of top 10 puggers for the gametype (sorted by most number of

Outputs a summary of total number of pugs played, individual pug count(s) and a timestamp when the first pug was played

**addautoremove, aar** 😸<br/>
`Usage -> .addautoremove expiry`

Automatically removes the user from all the pugs they have joined after expiry.

_Expiry Parameters_
`m` for minutes or `h` for hours or `d` for days.

For example `.autoremove 30m` will automatically remove the user from all the pugs after `30 minutes`.

**clearautoremove, car** 😸<br/>
`Usage -> .clearautoremove`

Clears your autoremoval request (if any).

**add** 🐱‍👤<br/>
`Usage -> .add @mention#0000 gametype1 gametype2 etc`

Expand Down
16 changes: 16 additions & 0 deletions src/commands/pugs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,22 @@ const pugsCommandList: Command[] = [
isPrivileged: true,
needsRegisteredGuild: true,
},
{
group,
key: 'handleAddAutoRemove',
aliases: ['addautoremove', 'aar'],
type: 'args',
isPrivileged: false,
needsRegisteredGuild: true,
},
{
group,
key: 'handleClearAutoRemove',
aliases: ['clearautoremove', 'car'],
type: 'solo',
isPrivileged: false,
needsRegisteredGuild: true,
},
];

export default pugsCommandList;
4 changes: 3 additions & 1 deletion src/formatting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export const formatJoinStatus = (statuses: Array<JoinStatus>) => {

export const formatLeaveStatus = (
statuses: Array<LeaveStatus>,
reason?: 'offline' | 'left'
reason?: 'offline' | 'left' | 'autoremove'
) => {
const { left, nf, nj, username } = statuses.reduce(
(acc, { name, result, pug, user }) => {
Expand Down Expand Up @@ -122,6 +122,8 @@ export const formatLeaveStatus = (
reasonMsg = `because the user went offline ${emojis.residentsleeper}${emojis.pupcurn}`;
else if (reason === 'left')
reasonMsg = 'because the user left this discord server';
else if (reason === 'autoremove')
reasonMsg = 'because the user had autoremoval added';
else reasonMsg = '';

return `${left.length > 0 ? `${username} left ${left} ${reasonMsg}` : ``}${
Expand Down
1 change: 1 addition & 0 deletions src/handlers/generalHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export const handleRegisterServer: Handler = async (message, _) => {
guildId: guild.id,
cooldowns: {},
ignoredCommandGroup: [],
autoremovals: {},
})
);
store.dispatch(initBlocks({ guildId: guild.id, list: [] }));
Expand Down
137 changes: 124 additions & 13 deletions src/handlers/pugHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ import {
emojis,
getRandomInt,
sanitizeName,
calculateBlockExpiry,
calculateExpiry,
isDuelPug,
getRandomPickIndex,
teamEmojiTypes,
getPlayerIndexFromPlayerList,
} from '~/utils';
import {
addGuildGameType,
Expand Down Expand Up @@ -41,6 +42,8 @@ import store, {
disableCoinFlip,
updateTeamEmojis,
updatePickingOrder,
addAutoRemoval,
clearAutoRemoval,
} from '~/store';
import {
formatPugFilledDM,
Expand Down Expand Up @@ -456,6 +459,9 @@ export const handleJoinGameTypes: Handler = async (
`Remove pug ${toBroadcast.name} at guild ${guild.id} from store`
);
store.dispatch(removePug({ guildId: guild.id, name: toBroadcast.name }));
store.dispatch(
clearAutoRemoval({ guildId: guild.id, userId: author.id })
);
}
}

Expand Down Expand Up @@ -555,7 +561,13 @@ export const handleLeaveGameTypes: Handler = async (

const leaveMessage = formatLeaveStatus(
allLeaveStatuses,
content === 'zzz' ? 'offline' : content === 'left' ? 'left' : undefined
content === 'zzz'
? 'offline'
: content === 'left'
? 'left'
: content === 'arr'
? 'autoremove'
: undefined
);

if (!returnMsg) {
Expand Down Expand Up @@ -646,9 +658,11 @@ export const handleLeaveAllGameTypes: Handler = async (message) => {

const cache = store.getState();
const pugs = cache.pugs[guild.id];
if (!pugs) return;
const misc = cache.misc[guild.id];
if (!pugs || !misc) return;

const { list } = pugs;
const { autoremovals } = misc;

const listToLeave = list
.filter((pug) => pug.players.find((p) => p.id === author.id))
Expand All @@ -661,6 +675,9 @@ export const handleLeaveAllGameTypes: Handler = async (message) => {
return;
}

if (autoremovals[author.id])
store.dispatch(clearAutoRemoval({ guildId: guild.id, userId: author.id }));

handleLeaveGameTypes(message, listToLeave);
log.info(`Exiting handleLeaveAllGameTypes`);
};
Expand Down Expand Up @@ -716,7 +733,11 @@ export const handlePickPlayer: Handler = async (
mentionedUser
) => {
log.info(`Entering handlePickPlayer`);
const { guild, author } = message;
const {
guild,
author,
mentions: { users },
} = message;
if (!guild) return;

const cache = store.getState();
Expand Down Expand Up @@ -757,11 +778,15 @@ export const handlePickPlayer: Handler = async (
let lastPickedPlayerIndex: number | null;

const canPickTwice = pickingOrder[turn + 1] === team; // next turn is same team pick
const mentionedUsers = users.array();

// +1 because few lines down we're going to subtract -1 so we still gucci 😎
const firstMentionedUser = mentionedUsers[0];
const playerIndex =
index === 'random'
? getRandomPickIndex(forPug.players) + 1
: firstMentionedUser
? getPlayerIndexFromPlayerList(forPug.players, firstMentionedUser) + 1
: parseInt(index);
if (!playerIndex) return;

Expand All @@ -786,9 +811,12 @@ export const handlePickPlayer: Handler = async (
/**
* Situation when captain picks two in a row
*/
const secondMentionedUser = mentionedUsers[1];
const playerIndex2 =
index2 === 'random'
? getRandomPickIndex(forPug.players) + 1
: secondMentionedUser
? getPlayerIndexFromPlayerList(forPug.players, secondMentionedUser) + 1
: parseInt(index2);

if (canPickTwice && playerIndex2) {
Expand Down Expand Up @@ -816,11 +844,9 @@ export const handlePickPlayer: Handler = async (
}
}

const pickedPlayers = [
pick1,
pick2,
lastPickedPlayerIndex,
].filter((i): i is number => Number.isInteger(i));
const pickedPlayers = [pick1, pick2, lastPickedPlayerIndex].filter(
(i): i is number => Number.isInteger(i)
);
message.channel.send(formatPickPlayerStatus(forPug, pickedPlayers) ?? '');

if (!forPug.isInPickingMode) {
Expand Down Expand Up @@ -1068,13 +1094,13 @@ export const handlePromoteAvailablePugs: Handler = async (message, args) => {

export const handleDecidePromoteOrPick: Handler = async (message, args) => {
log.info(`Entering handleDecidePromoteOrPick`);
const { guild, cmd } = message;
const { guild, cmd, mentions } = message;
if (!guild || !cmd) return;

// just p or promote
if (!args[0]) handlePromoteAvailablePugs(message, args);
else {
// p 4 or p siege5
// p 4 or p siege5 or p @mention
const cache = store.getState();
const pugs = cache.pugs[guild.id];
if (!pugs) return;
Expand All @@ -1085,7 +1111,11 @@ export const handleDecidePromoteOrPick: Handler = async (message, args) => {
);

if (isArgGameType) handlePromoteAvailablePugs(message, args);
else if (!isNaN(parseInt(args[0])) || args[0] === 'random')
else if (
mentions.users.size !== 0 ||
!isNaN(parseInt(args[0])) ||
args[0] === 'random'
)
handlePickPlayer(message, args);
else handlePromoteAvailablePugs(message, args);
}
Expand Down Expand Up @@ -1282,6 +1312,8 @@ export const handleAdminPickPlayer: Handler = async (message, args) => {
}

mentionedUser.username = sanitizeName(mentionedUser.username);
// because if picks are also mentions then the mentioned user should atleast be removed for no confusion
message.mentions.users.delete(mentionedUser.id);
handlePickPlayer(message, args.slice(1), mentionedUser);
log.info(`Exiting handleAdminPickPlayer`);
};
Expand Down Expand Up @@ -1370,7 +1402,7 @@ export const handleAdminBlockPlayer: Handler = async (message, args) => {
const blockLength = parseInt(blockLengthString);
if (blockLength <= 0) return;

const expiry = calculateBlockExpiry(
const expiry = calculateExpiry(
blockPeriodString as 'm' | 'h' | 'd',
blockLength
);
Expand Down Expand Up @@ -1695,3 +1727,82 @@ export const handleAdminEnforceCustomPickingOrder: Handler = async (

log.info(`Exiting handleAdminEnforceCustomPickingOrder`);
};

export const handleAddAutoRemove: Handler = async (message, args) => {
log.info(`Entering handleAddAutoRemove`);
const { guild, author } = message;
if (!guild) return;

const cache = store.getState();
const misc = cache.misc[guild.id];
const pugs = cache.pugs[guild.id];
if (!misc || !pugs) return;

const userId = author.id;
const { list } = pugs;

const userHasJoinedAtleastOnePug = list.some((pug) =>
pug.players.find((p) => p.id === userId)
);

if (!userHasJoinedAtleastOnePug) {
log.debug(`User ${userId} has not joined any pug, so no autoremoval`);
message.channel.send(
`You need to join atleast one pug to be able to use this command`
);
return;
}

const [timeframe = ''] = args;
const [autoRemoveLengthString] = timeframe.match(/[0-9]+/g) ?? [];
const [autoRemovePeriodString] = timeframe.match(/[m|h|d]/g) ?? [];

if (!autoRemoveLengthString || !autoRemovePeriodString) {
message.channel.send(`No duration was provided`);
return;
}

const autoRemoveLength = parseInt(autoRemoveLengthString);
if (autoRemoveLength <= 0) return;

const expiry = calculateExpiry(
autoRemovePeriodString as 'm' | 'h' | 'd',
autoRemoveLength
);

store.dispatch(addAutoRemoval({ guildId: guild.id, userId, expiry }));
log.info(`Autoremoval added for user ${userId} at ${expiry.toUTCString()}`);

message.channel.send(
`<@${userId}>, you will be autoremoved from every pug at **${expiry.toUTCString()}**`
);

log.info(`Exiting handleAddAutoRemove`);
};

export const handleClearAutoRemove: Handler = async (message, _) => {
log.info(`Entering handleClearAutoRemove`);
const { guild, author } = message;
if (!guild) return;

const cache = store.getState();
const misc = cache.misc[guild.id];
if (!misc) return;

const userId = author.id;
const { autoremovals } = misc;

const userHasAutoRemoval = autoremovals[userId];
if (!userHasAutoRemoval) {
log.debug(`User ${userId} has no autoremoval`);
message.channel.send(`You have no autoremoval added`);
return;
}

store.dispatch(clearAutoRemoval({ guildId: guild.id, userId }));
log.info(`Autoremoval cleared for user ${userId}`);

message.channel.send(`<@${userId}>, you will not be autoremoved anymore`);

log.info(`Exiting handleClearAutoRemove`);
};
Loading

0 comments on commit 3ef362f

Please sign in to comment.