Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Codeycoin leaderboard #263

Merged
merged 8 commits into from
Aug 7, 2022
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions src/commandDetails/coin/leaderboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { container, SapphireClient } from '@sapphire/framework';
import { MessageEmbed } from 'discord.js';
import {
CodeyCommandDetails,
CodeyCommandResponseType,
getUserIdFromMessage,
SapphireMessageExecuteType,
SapphireMessageResponse
} from '../../codeyCommand';
import {
getCurrentCoinLeaderboard,
getCoinBalanceByUserId,
UserCoinEntry,
getUserIdCurrentCoinPosition
} from '../../components/coin';
import { EMBED_COLOUR } from '../../utils/embeds';

const getCurrentCoinLeaderboardEmbed = async (
client: SapphireClient<boolean>,
leaderboard: UserCoinEntry[],
currentUserId: string,
limit = 10
marko-polo-cheno marked this conversation as resolved.
Show resolved Hide resolved
mcpenguin marked this conversation as resolved.
Show resolved Hide resolved
): Promise<MessageEmbed> => {
// Initialise user's coin balance if they have not already
const userBalance = await getCoinBalanceByUserId(currentUserId);
const currentPosition = await getUserIdCurrentCoinPosition(currentUserId);

let currentLeaderboardText = '';
for (let i = 0; i < limit; i++) {
if (leaderboard.length <= i) break;
const userCoinEntry = leaderboard[i];
const user = await client.users.fetch(userCoinEntry.user_id);
const userTag = user?.tag ?? '<unknown>';
const userCoinEntryText = `${i + 1}. ${userTag} - ${userCoinEntry.balance} 🪙\n`;
currentLeaderboardText += userCoinEntryText;
}
const currentLeaderboardEmbed = new MessageEmbed()
.setColor(EMBED_COLOUR)
.setTitle('CodeyCoin Leaderboard')
.setDescription(currentLeaderboardText);

currentLeaderboardEmbed.addFields({
name: 'Your Position',
value: `You are currently **#${currentPosition}** in the leaderboard with ${userBalance} 🪙.`
});

return currentLeaderboardEmbed;
};

const coinCurrentLeaderboardExecuteCommand: SapphireMessageExecuteType = async (
client,
messageFromUser,
_args
): Promise<SapphireMessageResponse> => {
const userId = getUserIdFromMessage(messageFromUser);
const leaderboard = await getCurrentCoinLeaderboard();
return getCurrentCoinLeaderboardEmbed(client, leaderboard, userId);
};

export const coinCurrentLeaderboardCommandDetails: CodeyCommandDetails = {
name: 'leaderboard',
aliases: ['lb'],
description: 'Get the current coin leaderboard.',
detailedDescription: `**Examples:**
\`${container.botPrefix}coin lb\`
\`${container.botPrefix}coin leaderboard\``,

isCommandResponseEphemeral: false,
messageWhenExecutingCommand: 'Getting the current coin leaderboard...',
executeCommand: coinCurrentLeaderboardExecuteCommand,
codeyCommandResponseType: CodeyCommandResponseType.EMBED,

options: [],
subcommandDetails: {}
};
4 changes: 3 additions & 1 deletion src/commands/coin/coin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { coinBalanceCommandDetails } from '../../commandDetails/coin/balance';
import { coinCheckCommandDetails } from '../../commandDetails/coin/check';
import { coinInfoCommandDetails } from '../../commandDetails/coin/info';
import { coinUpdateCommandDetails } from '../../commandDetails/coin/update';
import { coinCurrentLeaderboardCommandDetails } from '../../commandDetails/coin/leaderboard';

const coinCommandDetails: CodeyCommandDetails = {
name: 'coin',
Expand All @@ -28,7 +29,8 @@ const coinCommandDetails: CodeyCommandDetails = {
balance: coinBalanceCommandDetails,
check: coinCheckCommandDetails,
info: coinInfoCommandDetails,
update: coinUpdateCommandDetails
update: coinUpdateCommandDetails,
leaderboard: coinCurrentLeaderboardCommandDetails
},
defaultSubcommandDetails: coinBalanceCommandDetails
};
Expand Down
36 changes: 36 additions & 0 deletions src/components/coin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ export const coinBonusMap = new Map<BonusType, Bonus>([
]
]);

export interface UserCoinEntry {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't ctrl f on phone but can u just lmk where this is used XD

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the leaderboard :))

user_id: string;
balance: number;
}

export interface UserCoinBonus {
id: string;
user_id: string;
Expand Down Expand Up @@ -135,6 +140,37 @@ export const changeDbCoinBalanceByUserId = async (
await createCoinLedgerEntry(userId, oldBalance, newBalance, event, reason, adminId);
};

/*
Get the leaderboard for the current coin amounts.
*/
export const getCurrentCoinLeaderboard = async (limit = 10): Promise<UserCoinEntry[]> => {
const db = await openDB();
const res = await db.all(
`
SELECT user_id, balance
FROM user_coin
ORDER BY balance DESC
mcpenguin marked this conversation as resolved.
Show resolved Hide resolved
LIMIT ${limit}
mcpenguin marked this conversation as resolved.
Show resolved Hide resolved
`
);
return res;
};

/*
Get the position for a user id's balance
*/
export const getUserIdCurrentCoinPosition = async (userId: string): Promise<number> => {
const db = await openDB();
const res = await db.get(
`
SELECT COUNT(user_id) AS count
FROM user_coin
WHERE balance >= (SELECT balance FROM user_coin WHERE user_id = '${userId}')
mcpenguin marked this conversation as resolved.
Show resolved Hide resolved
mcpenguin marked this conversation as resolved.
Show resolved Hide resolved
`
);
return _.get(res, 'count', 0);
};

/*
Adds an entry to the Codey coin ledger due to a change in a user's coin balance.
reason is only applicable for admin commands and is optional.
Expand Down