Skip to content
This repository has been archived by the owner on Feb 1, 2024. It is now read-only.

Playerdata #41

Merged
merged 3 commits into from
Dec 28, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
55 changes: 55 additions & 0 deletions src/commands/recordrole.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import xlg from '../xlogger';
import { sendError } from "../utils/messages";
import checkAccess from '../utils/checkaccess';
import { CommandClient, ExtMessage } from '../typings';
import { TextChannel } from 'discord.js';
import { stringToRole } from "../utils/parsers";

module.exports = {
name: "recordrole",
aliases: ["rr"],
usage: "<#role | none>",
args: true,
specialArgs: 1,
description: "set the role given to record breakers",
async execute(client: CommandClient, message: ExtMessage, args: string[]) {
try {
// check for perms
if (!(await checkAccess(message))) return;
if (!message.guild) return;

const a = args.join(" ");
if (a === "none") {
await client.database?.setRecordRole(message.guild.id, "");// set the recordrole to "" to mean "none" (resetting)
message.channel.send({
embed: {
color: process.env.NAVY_COLOR,
description: `The Fail Role has been reset.`
}
});
return;
}

const target = stringToRole(message.guild, a);// getting role from args
if (!target || typeof target === "string") {
if (!(message.channel instanceof TextChannel)) return false;
sendError(message.channel, "A valid role is required", true);
return false;
}

await client.database?.setRecordRole(message.guild.id, target.id);// set the id of the recordrole for the guild in the db
message.channel.send({
embed: {
color: process.env.NAVY_COLOR,
description: `The Record Role has been set to ${target}.\nPeople deemed new record breakers will receive this role, it will be removed from old record breakers.`
}
});
return;
} catch (error) {
xlg.error(error);
if (!(message.channel instanceof TextChannel)) return;
sendError(message.channel);
return false;
}
}
}
59 changes: 30 additions & 29 deletions src/typings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,39 +39,40 @@ export interface ExtMessage extends Discord.Message {
guesses?: number;
}

export interface guildObject {
guildID?: string;
count?: number;
increment?: number;
countChannel?: string;
commandChannel?: string;
failRole?: string;
lastUpdatedID?: string;
lastMessageID?: string;
chatAllowed?: boolean;
leaderboardEligible?: 0 | 1;
numberOfCounts?: number;
totalCount?: number;
recordNumber?: number;
numberOfErrors?: number;
pogNumStat?: number;
export interface guildObject {// the information object assigned to every active guild
guildID?: string;// identifying snowflake
count?: number;// current count (the last number in the counting channel)
increment?: number;// what the count should be increasing by
countChannel?: string;// identifying snowflake of the channel the count takes place in
commandChannel?: string;// identifying snowflake of the only channel commands can be executed in, if enabled
failRole?: string;// identifying snowflake of the role given to players when they fail the count
lastUpdatedID?: string;// identifying snowflake of the last user to count
lastMessageID?: string;// identifying snowflake of the message containing the last count
chatAllowed?: boolean;// setting for whether non-numeric messages should be allowed in the counting channel
leaderboardEligible?: 0 | 1;// status of whether the guild is stil eligible to appear on the leaderboard
numberOfCounts?: number;// the total number of counts committed in the guild
totalCount?: number;// numberOfCounts * increment (the current increment is added to this figure every count)
recordNumber?: number;// the highest number reached in the guild
numberOfErrors?: number;// the total number of counting errors made in the guild
pogNumStat?: number;// the number of times the number 69 was reached
players?: Array<GuildPlayer>;// individual player data for the guild, not global info
saves?: number;// the number of saves the guild currently has (max 3)
lastSaved?: Date;// the timestamp of the last time a save was used on the count
deletedMessageReminder?: boolean;// whether or not the message warning that the previous count was deleted was already sent for the turn
courtesyChances?: 0 | 1 | 2;// the number of chances remaining for the players to guess the number if the situation arises
autoMute?: boolean;// whether the auto-mute on fail feature is enabled, IN BETA
recordRole?: string;// for the achievement role handed out when the record is broken
recordHolder?: string;// identifying snowflake of the user who made the last highest count, MAY SWITCH TO ARRAY OF USERS
//paused?: boolean;
players?: Array<GuildPlayer>;
saves?: number;
lastSaved?: Date;
//checkMarks?: boolean;
deletedMessageReminder?: boolean;
courtesyChances?: 0 | 1 | 2;
//foulMessage?: boolean;
//redemptionChances?: 0 | 1 | 2;
autoMute?: boolean;
//checkMarks?: boolean;
}

export interface GuildPlayer {
id: string;
errors: number;
totalCounts: number;
highestNumber: number;
export interface GuildPlayer {// used for player data in a guildObject
id: string;// the identifying snowflake
errors: number;// the number of errors in total made by the player
totalCounts: number;// the total number of counts made by the player
highestNumber: number;// the highest number the player reached
//mutedUntil?: Date;
}

Expand Down
46 changes: 39 additions & 7 deletions src/utils/counthandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,34 @@ export = async (client: CommandClient, message: ExtMessage): Promise<boolean> =>
const incre = increment.increment || 1;
//if (parseInt(message.content, 10) !== parseInt((rmsgs.array())[1].content, 10) + 1) {
if (parseInt(message.content, 10) !== cc + incre) {
if (!await handleFoul(client, message, "wrong number")) xlg.log("failed to handle foul: number");
if (!await handleFoul(client, message, "wrong number", parseInt(message.content, 10) - (cc + incre))) xlg.log("failed to handle foul: number");
return true;
}


// record role handling
const recordRoleID = await client.database?.getRecordRole(message.guild?.id || "");
if (recordRoleID && recordRoleID.length > 0) {// will check if a role needs to be given to the user who failed the count
const s = await client.database.getStats(message.guild.id);
if (s && s.recordNumber) {
if (cc + incre > s.recordNumber) {
const recordRole = message.guild?.roles.cache.get(recordRoleID);
if (recordRole) {
message.member?.roles.add(recordRole).catch(xlg.error);
const rhid = await client.database.getRecordHolder(message.guild.id);
if (rhid && rhid !== message.author.id) {
const rh = message.guild.members.cache.get(rhid);
if (rh/* && rh.roles.cache.has(recordRoleID)*/) {
rh.roles.remove(recordRole);
}
}
await client.database.setRecordHolder(message.guild.id, message.author.id);
} else {
await client.database?.setRecordRole(message.guild?.id || "", "");
}
}
}
}

await client.database?.setLastUpdater(message.guild.id, message.author.id);// mark the sender as the last counter
await client.database?.updateCount(message.guild.id, cc + incre, message.id);
await client.database?.setDelReminderShown(message.guild.id, false);// resets the status to no for whether the reminder for being delete-tricked had been sent
Expand All @@ -62,7 +86,7 @@ export = async (client: CommandClient, message: ExtMessage): Promise<boolean> =>
}
}

async function handleFoul(client: CommandClient, message: ExtMessage, reason?: string): Promise<boolean> {
async function handleFoul(client: CommandClient, message: ExtMessage, reason?: string, offBy?: number): Promise<boolean> {
if (!client || !message) return false;
if (!reason) reason = "Foul";

Expand Down Expand Up @@ -139,10 +163,11 @@ async function handleFoul(client: CommandClient, message: ExtMessage, reason?: s
await client.database?.updateCount(message.guild?.id || "", 0);// reset the count
await client.database?.incrementErrorCount(message.guild?.id || "");// adds to the total count of errors for the guild
await client.database?.setDelReminderShown(message.guild?.id || "", false);// resets the status to no for whether the reminder for being delete-tricked had been sent
await client.database?.incrementGuildPlayerStats(message.guild?.id || "", message.author.id, true);
if (message.guesses !== 2) {
await client.database?.setCourtesyChances(message.guild?.id || "", 2);// resets the chances given for the players to guess the number if they get it wrong under circums.
}
await client.database?.incrementGuildPlayerStats(message.guild?.id || "", message.author.id, true);

// fail role handling
const failroleid = await client.database?.getFailRole(message.guild?.id || "");
if (failroleid && failroleid.length > 0) {// will check if a role needs to be given to the user who failed the count
Expand All @@ -154,7 +179,7 @@ async function handleFoul(client: CommandClient, message: ExtMessage, reason?: s
}
}
// auto mute handling
await handleMute(client, message);
await handleMute(client, message, offBy);

const increment = await client.database?.getIncrement(message.guild?.id);
if (!increment) return false;
Expand All @@ -172,14 +197,21 @@ async function handleFoul(client: CommandClient, message: ExtMessage, reason?: s
return true;
}

async function handleMute(client: CommandClient, message: ExtMessage): Promise<void> {
async function handleMute(client: CommandClient, message: ExtMessage, offBy?: number): Promise<void> {
if (!message.guild || message.channel.type !== "text" || !message.member) return;
const ams = await client.database?.getAutoMuteSetting(message.guild?.id);
if (!ams) return;

message.channel.updateOverwrite(message.member, {
"SEND_MESSAGES": false
}, `muting ${message.author.tag} for failing the count`);
const aimDate = moment(new Date()).add(parseInt(process.env.DEF_MUTE_LENGTH || "10"), "m").toDate();

let muteLength = parseInt(process.env.DEF_MUTE_LENGTH || "10");
if (offBy && Math.abs(offBy) > 5) {
muteLength = (Math.abs(offBy) + 5) * 2;
}
const aimDate = moment(new Date()).add(muteLength, "m").toDate();

client.database?.setMemberMute(message.guild?.id, message.author.id, aimDate)
}

Expand Down
56 changes: 54 additions & 2 deletions src/utils/dbm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,9 @@ export class Database {
pogNumStat: 0,
players: [],
courtesyChances: 2,
autoMute: false
autoMute: false,
recordRole: "",
recordHolder: ""
}
private userDefaults: PlayerData = {
userID: "",
Expand Down Expand Up @@ -295,6 +297,28 @@ export class Database {
if (!result || !result.autoMute) return false;
return true;
}

async getRecordRole(guildID: string | undefined): Promise<string | false> {
if (!guildID || !this.db) return false;
await this.maybeSetDefaults(guildID);
const GuildData = this.db.collection("GuildData");
const result = await GuildData.findOne({ "guildID": guildID }) || this.guildDefaults;
if (result.recordRole) {
return result.recordRole;
}
return "";
}

async getRecordHolder(guildID: string | undefined): Promise<string | false> {
if (!guildID || !this.db) return false;
await this.maybeSetDefaults(guildID);
const GuildData = this.db.collection("GuildData");
const result = await GuildData.findOne({ "guildID": guildID }) || this.guildDefaults;
if (result.recordHolder) {
return result.recordHolder;
}
return "";
}

/*┏━━━━━━━━━┓
┃ SETTERS ┃
Expand Down Expand Up @@ -571,6 +595,32 @@ export class Database {
});
}

async setRecordRole(guildID: string, role: string): Promise<void> {
if (!this.db) return;
await this.maybeSetDefaults(guildID);
const GuildData = this.db.collection("GuildData");
await GuildData.updateOne({
"guildID": guildID,
}, {
$set: { "recordRole": role }
}, {
upsert: true
});
}

async setRecordHolder(guildID: string, id: string): Promise<void> {
if (!this.db) return;
await this.maybeSetDefaults(guildID);
const GuildData = this.db.collection("GuildData");
await GuildData.updateOne({
"guildID": guildID,
}, {
$set: { "recordHolder": id }
}, {
upsert: true
});
}

/*┏━━━━━━━━━━┓
┃ DEFAULTS ┃
┗━━━━━━━━━━┛*/
Expand Down Expand Up @@ -598,7 +648,9 @@ export class Database {
lastMessageID: "",
totalCount: 0,
failRole: "",
autoMute: false
autoMute: false,
recordRole: "",
recordHolder: ""
}
const guild = await GuildData.findOne({ "guildID": guildID }) || guildDefaults;
if (isNaN(guild.count)) guild.count = 0;
Expand Down