V0.1.0 - Initial

This is the first release of Group Up.  Expect errors and poor input parsing for time.

Documentation is coming soon™️
This commit is contained in:
Ean Milligan (Bastion) 2021-05-30 17:04:58 -04:00
parent 846818c831
commit d60d1ff829
19 changed files with 2265 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
config.ts
logs

12
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,12 @@
{
"deno.enable": true,
"deno.lint": true,
"deno.unstable": true,
"deno.import_intellisense_origins": {
"https://deno.land": true
},
"spellright.language": [
"en"
],
"spellright.documentTypes": []
}

375
LICENSE Normal file
View File

@ -0,0 +1,375 @@
https://choosealicense.com/licenses/mpl-2.0/
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View File

@ -1,2 +1,5 @@
# GroupUp
Group Up is a Discord bot built for scheduling events in your Guild.
# Invite Link
https://discord.com/api/oauth2/authorize?client_id=847256159123013722&permissions=75776&scope=bot

37
config.example.ts Normal file
View File

@ -0,0 +1,37 @@
export const config = {
"name": "Group Up", // Name of the bot
"version": "0.0.0", // Version of the bot
"token": "the_bot_token", // Discord API Token for this bot
"localtoken": "local_testing_token", // Discord API Token for a secondary OPTIONAL testing bot, THIS MUST BE DIFFERENT FROM "token"
"prefix": "[[", // Prefix for all commands
"db": { // Settings for the MySQL database, this is required for use with the API, if you do not want to set this up, you will need to rip all code relating to the DB out of the bot
"host": "", // IP address for the db, usually localhost
"localhost": "", // IP address for a secondary OPTIONAL local testing DB, usually also is localhost, but depends on your dev environment
"port": 3306, // Port for the db
"username": "", // Username for the account that will access your DB, this account will need "DB Manager" admin rights and "REFERENCES" Global Privalages
"password": "", // Password for the account, user account may need to be authenticated with the "Standard" Authentication Type if this does not work out of the box
"name": "" // Name of the database Schema to use for the bot
},
"logChannel": "the_log_channel", // Discord channel ID where the bot should put startup messages and other error messages needed
"reportChannel": "the_report_channel", // Discord channel ID where reports will be sent when using the built-in report command
"devServer": "the_dev_server", // Discord guild ID where testing of indev features/commands will be handled, used in conjuction with the DEVMODE bool in mod.ts
"owner": "the_bot_owner", // Discord user ID of the bot admin
"botLists": [ // Array of objects containing all bot lists that stats should be posted to
{ // Bot List object, duplicate for each bot list
"name": "Bot List Name", // Name of bot list, not used
"enabled": false, // Should statistics be posted to this list?
"apiUrl": "https://example.com/api/bots/?{bot_id}/stats", // API URL, use ?{bot_id} in place of the bot id so that it can be dynamically replaced
"headers": [ // Array of headers that need to be added to the request
{ // Header Object, duplicate for every header needed
"header": "header_name", // Name of header needed, usually Authorization is needed
"value": "header_value" // Value for the header
}
],
"body": { // Data payload to send to the bot list, will be turned into a string and any ?{} will be replaced with the required value, currently only has ?{server_count}
"param_name": "?{param_value}" // Add more params as needed
}
}
]
};
export default config;

67
db/initialize.ts Normal file
View File

@ -0,0 +1,67 @@
// This file will create all tables for the artificer schema
// DATA WILL BE LOST IF DB ALREADY EXISTS, RUN AT OWN RISK
import {
// MySQL deps
Client
} from "../deps.ts";
import { LOCALMODE } from "../flags.ts";
import config from "../config.ts";
// Log into the MySQL DB
const dbClient = await new Client().connect({
hostname: LOCALMODE ? config.db.localhost : config.db.host,
port: config.db.port,
username: config.db.username,
password: config.db.password,
});
console.log("Attempting to create DB");
await dbClient.execute(`CREATE SCHEMA IF NOT EXISTS ${config.db.name};`);
await dbClient.execute(`USE ${config.db.name}`);
console.log("DB created");
console.log("Attempt to drop all tables");
await dbClient.execute(`DROP PROCEDURE IF EXISTS INC_CNT;`);
await dbClient.execute(`DROP TABLE IF EXISTS command_cnt;`);
await dbClient.execute(`DROP TABLE IF EXISTS guild_prefix;`);
console.log("Tables dropped");
console.log("Attempting to create table command_cnt");
await dbClient.execute(`
CREATE TABLE command_cnt (
command char(20) NOT NULL,
count bigint unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (command),
UNIQUE KEY command_cnt_command_UNIQUE (command)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`);
console.log("Table created");
console.log("Attempt creating increment Stored Procedure");
await dbClient.execute(`
CREATE PROCEDURE INC_CNT(
IN cmd CHAR(20)
)
BEGIN
declare oldcnt bigint unsigned;
set oldcnt = (SELECT count FROM command_cnt WHERE command = cmd);
UPDATE command_cnt SET count = oldcnt + 1 WHERE command = cmd;
END
`);
console.log("Stored Procedure created");
console.log("Attempting to create table guild_prefix");
await dbClient.execute(`
CREATE TABLE guild_prefix (
guildId bigint unsigned NOT NULL,
prefix char(10) NOT NULL,
PRIMARY KEY (guildid),
UNIQUE KEY guild_prefix_guildid_UNIQUE (guildid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`);
console.log("Table created");
await dbClient.close();
console.log("Done!");

30
db/populateDefaults.ts Normal file
View File

@ -0,0 +1,30 @@
// This file will populate the tables with default values
import {
// MySQL deps
Client
} from "../deps.ts";
import { LOCALMODE } from "../flags.ts";
import config from "../config.ts";
// Log into the MySQL DB
const dbClient = await new Client().connect({
hostname: LOCALMODE ? config.db.localhost : config.db.host,
port: config.db.port,
db: config.db.name,
username: config.db.username,
password: config.db.password,
});
console.log("Attempting to insert default commands into command_cnt");
const commands = ["ping", "help", "info", "version", "report", "privacy", "lfg", "prefix"];
for (let i = 0; i < commands.length; i++) {
await dbClient.execute("INSERT INTO command_cnt(command) values(?)", [commands[i]]).catch(e => {
console.log(`Failed to insert into database`, e);
});
}
console.log("Insertion done");
await dbClient.close();
console.log("Done!");

18
deps.ts Normal file
View File

@ -0,0 +1,18 @@
// All external dependancies are to be loaded here to make updating dependancy versions much easier
export {
startBot, editBotStatus, editBotNickname,
Intents, DiscordActivityTypes, DiscordButtonStyles, DiscordInteractionTypes,
sendMessage, sendDirectMessage, sendInteractionResponse, getMessage, deleteMessage,
hasGuildPermissions,
cache, botId, structures
} from "https://deno.land/x/discordeno@11.0.0-rc.5/mod.ts";
export type {
DiscordenoMessage, DiscordenoMember, DiscordenoGuild, CreateMessage, Interaction, ButtonComponent, ActionRow, EmbedField
} from "https://deno.land/x/discordeno@11.0.0-rc.5/mod.ts"; // https://deno.land/x/discordeno@11.0.0-rc.5/mod.ts
export { Client } from "https://deno.land/x/mysql@v2.9.0/mod.ts";
export { LogTypes as LT, initLog, log } from "https://raw.githubusercontent.com/Burn-E99/Log4Deno/V1.1.0/mod.ts";
export { nanoid } from "https://deno.land/x/nanoid@v3.0.0/mod.ts";

6
flags.ts Normal file
View File

@ -0,0 +1,6 @@
// DEVMODE is to prevent users from accessing parts of the bot that are currently broken
export const DEVMODE = false;
// DEBUG is used to toggle the cmdPrompt
export const DEBUG = false;
// LOCALMODE is used to run a differnt bot token for local testing
export const LOCALMODE = false;

831
mod.ts Normal file
View File

@ -0,0 +1,831 @@
import {
// Discordeno deps
startBot, editBotStatus, editBotNickname,
Intents, DiscordActivityTypes, DiscordButtonStyles, DiscordInteractionTypes,
sendMessage, sendInteractionResponse, deleteMessage, getMessage,
hasGuildPermissions,
cache, botId, structures,
DiscordenoMessage, DiscordenoGuild, Interaction, ButtonComponent, ActionRow,
// MySQL Driver deps
Client,
// Log4Deno deps
LT, initLog, log
} from "./deps.ts";
import { BuildingLFG, ActiveLFG, GuildPrefixes, ButtonData } from "./src/mod.d.ts";
import intervals from "./src/intervals.ts";
import { LFGActivities } from "./src/games.ts";
import { JoinLeaveType } from "./src/lfgHandlers.d.ts";
import { handleLFGStep, handleMemberJoin, handleMemberLeave } from "./src/lfgHandlers.ts";
import { constantCmds, editBtns } from "./src/constantCmds.ts";
import { DEBUG, LOCALMODE } from "./flags.ts";
import config from "./config.ts";
// Initialize DB client
const dbClient = await new Client().connect({
hostname: LOCALMODE ? config.db.localhost : config.db.host,
port: config.db.port,
db: config.db.name,
username: config.db.username,
password: config.db.password
});
// Initialize logging client with folder to use for logs, needs --allow-write set on Deno startup
initLog("logs", DEBUG);
log(LT.INFO, `${config.name} Starting up . . .`)
// Handle idling out the active builders
const activeBuilders: Array<BuildingLFG> = [];
setInterval(() => {
intervals.buildingTimeout(activeBuilders);
}, 1000);
const activeLFGPosts: Array<ActiveLFG> = JSON.parse(localStorage.getItem("activeLFGPosts") || "[]", (_key, value) => {
if (typeof value === "string" && /^\d+n$/.test(value)) {
return BigInt(value.substr(0, value.length - 1));
}
return value;
});
log(LT.INFO, `Loaded ${activeLFGPosts.length} activeLFGPosts`);
setInterval(() => {
intervals.lfgNotifier(activeLFGPosts);
}, 60000);
const guildPrefixes: Map<bigint, string> = new Map();
const getGuildPrefixes = await dbClient.query("SELECT * FROM guild_prefix");
getGuildPrefixes.forEach((g: GuildPrefixes) => {
guildPrefixes.set(g.guildId, g.prefix);
});
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Start up the Discord Bot
startBot({
token: LOCALMODE ? config.localtoken : config.token,
intents: [Intents.GuildMessages, Intents.DirectMessages, Intents.Guilds],
eventHandlers: {
ready: () => {
log(LT.INFO, `${config.name} Logged in!`);
editBotStatus({
activities: [{
name: "Booting up . . .",
type: DiscordActivityTypes.Game,
createdAt: new Date().getTime()
}],
status: "online"
});
// Interval to rotate the status text every 30 seconds to show off more commands
setInterval(() => {
log(LT.LOG, "Changing bot status");
try {
// Wrapped in try-catch due to hard crash possible
editBotStatus({
activities: [{
name: intervals.getRandomStatus(),
type: DiscordActivityTypes.Game,
createdAt: new Date().getTime()
}],
status: "online"
});
} catch (e) {
log(LT.ERROR, `Failed to update status: ${JSON.stringify(e)}`);
}
}, 30000);
// Interval to update bot list stats every 24 hours
LOCALMODE ? log(LT.INFO, "updateListStatistics not running") : setInterval(() => {
log(LT.LOG, "Updating all bot lists statistics");
intervals.updateListStatistics(botId, cache.guilds.size);
}, 86400000);
// setTimeout added to make sure the startup message does not error out
setTimeout(() => {
LOCALMODE && editBotNickname(config.devServer, `LOCAL - ${config.name}`);
LOCALMODE ? log(LT.INFO, "updateListStatistics not running") : intervals.updateListStatistics(botId, cache.guilds.size);
editBotStatus({
activities: [{
name: "Booting Complete",
type: DiscordActivityTypes.Game,
createdAt: new Date().getTime()
}],
status: "online"
});
sendMessage(config.logChannel, `${config.name} has started, running version ${config.version}.`).catch(e => {
log(LT.ERROR, `Failed to send message: ${JSON.stringify(e)}`);
});
}, 1000);
},
guildCreate: (guild: DiscordenoGuild) => {
log(LT.LOG, `Handling joining guild ${JSON.stringify(guild)}`);
sendMessage(config.logChannel, `New guild joined: ${guild.name} (id: ${guild.id}). This guild has ${guild.memberCount} members!`).catch(e => {
log(LT.ERROR, `Failed to send message: ${JSON.stringify(e)}`);
});
},
guildDelete: (guild: DiscordenoGuild) => {
log(LT.LOG, `Handling leaving guild ${JSON.stringify(guild)}`);
sendMessage(config.logChannel, `I have been removed from: ${guild.name} (id: ${guild.id}).`).catch(e => {
log(LT.ERROR, `Failed to send message: ${JSON.stringify(e)}`);
});
},
debug: (dmsg, data) => log(LT.LOG, `Debug Message | ${JSON.stringify(dmsg)} | ${JSON.stringify(data)}`, false),
messageCreate: async (message: DiscordenoMessage) => {
// Ignore all other bots
if (message.isBot) return;
const prefix = guildPrefixes.get(message.guildId) || config.prefix;
// Handle messages not starting with the prefix
if (message.content.indexOf(prefix) !== 0) {
// Mentions
if (message.mentionedUserIds[0] === botId && message.content.trim().startsWith(`<@!${botId}>`)) {
// Light telemetry to see how many times a command is being run
await dbClient.execute(`CALL INC_CNT("prefix");`).catch(e => {
log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`);
});
if (message.content.trim() === `<@!${botId}>`) {
message.send({
embed: {
title: `Hello ${message.member?.username}, and thanks for using Group Up!`,
fields: [
{
name: `My prefix in this guild is: \`${prefix}\``,
value: "Mention me with a new prefix to change it."
}
]
}
});
}
else if (hasGuildPermissions(message.guildId, message.authorId, ["ADMINISTRATOR"])) {
const newPrefix = message.content.replace(`<@!${botId}>`, "").trim();
if (newPrefix.length <= 10) {
let success = true;
if (guildPrefixes.has(message.guildId)) {
// Execute the DB update
await dbClient.execute("UPDATE guild_prefix SET prefix = ? WHERE guildId = ?", [newPrefix, message.guildId]).catch(e => {
log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`);
success = false;
});
} else {
// Execute the DB insertion
await dbClient.execute("INSERT INTO guild_prefix(guildId,prefix) values(?,?)", [message.guildId, newPrefix]).catch(e => {
log(LT.ERROR, `Failed to insert into database: ${JSON.stringify(e)}`);
success = false;
});
}
if (success) {
guildPrefixes.set(message.guildId, newPrefix);
message.send({
embed: {
fields: [
{
name: `My prefix in this guild is now: \`${newPrefix}\``,
value: "Mention me with a new prefix to change it."
}
]
}
});
} else {
message.send({
embed: {
fields: [
{
name: "Something went wrong!",
value: `My prefix is still \`${prefix}\`. Please try again, and if the problem persists, please report this to the developers using \`${prefix}report\`.`
}
]
}
});
}
} else {
message.send({
embed: {
fields: [
{
name: "Prefix too long, please set a prefix less than 10 characters long.",
value: "Mention me with a new prefix to change it."
}
]
}
});
}
}
return;
}
// Other
const activeIdx = activeBuilders.findIndex(x => (message.channelId === x.channelId && message.authorId === x.userId));
if (activeIdx > -1) {
activeBuilders[activeIdx].lastTouch = new Date();
activeBuilders[activeIdx] = await handleLFGStep(activeBuilders[activeIdx], message.content);
if (activeBuilders[activeIdx].step === "done") {
if (message.member) {
const memberJoined = handleMemberJoin(activeBuilders[activeIdx].lfgMsg.embeds[0].fields || [], message.member, false);
const newTimestamp = new Date(parseInt(memberJoined.embed[1].value.split("#")[1]));
const newLfgUid = ALPHABET[Math.floor(Math.random()*26)] + ALPHABET[Math.floor(Math.random()*26)];
const tempMembers = memberJoined.embed[4].name.split(":")[1].split("/");
const currentMembers = parseInt(tempMembers[0]);
const maxMembers = parseInt(tempMembers[1]);
if (activeBuilders[activeIdx].editing) {
if (currentMembers > maxMembers) {
const currentPeople = memberJoined.embed[4].value.split("\n");
const newAlts = currentPeople.splice(maxMembers);
memberJoined.embed[4].value = currentPeople.join("\n") || "None";
memberJoined.embed[5].value = `${newAlts.join("\n")}\n${memberJoined.embed[5].value === "None" ? "" : memberJoined.embed[5].value}`;
memberJoined.embed[4].name = `Members Joined: ${maxMembers}/${maxMembers}`;
}
}
await activeBuilders[activeIdx].lfgMsg.edit({
content: "",
embed: {
fields: memberJoined.embed,
footer: {
text: `Created by: ${message.member.username} | ${newLfgUid}`,
},
timestamp: newTimestamp.toISOString()
},
components: [
{
type: 1,
components: [
{
type: 2,
label: "Join",
customId: "active@join_group",
style: DiscordButtonStyles.Success,
disabled: currentMembers >= maxMembers
},
{
type: 2,
label: "Leave",
customId: "active@leave_group",
style: DiscordButtonStyles.Danger
},
{
type: 2,
label: "Join as Alternate",
customId: "active@alternate_group",
style: DiscordButtonStyles.Primary
}
]
}
]
});
activeLFGPosts.push({
messageId: activeBuilders[activeIdx].lfgMsg.id,
channelId: activeBuilders[activeIdx].lfgMsg.channelId,
ownerId: message.authorId,
lfgUid: newLfgUid,
lfgTime: newTimestamp.getTime(),
notified: false,
locked: false
});
localStorage.setItem("activeLFGPosts", JSON.stringify(activeLFGPosts, (_key, value) =>
typeof value === "bigint" ? value.toString() + "n" : value
));
}
await activeBuilders[activeIdx].questionMsg.delete()
activeBuilders.splice(activeIdx, 1);
}
await message.delete();
}
return;
}
log(LT.LOG, `Handling message ${JSON.stringify(message)}`);
// Split into standard command + args format
const args = message.content.slice(prefix.length).trim().split(/[ \n]+/g);
const command = args.shift()?.toLowerCase();
// All commands below here
// ping
// Its a ping test, what else do you want.
if (command === "ping") {
// Light telemetry to see how many times a command is being run
dbClient.execute(`CALL INC_CNT("ping");`).catch(e => {
log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`);
});
// Calculates ping between sending a message and editing it, giving a nice round-trip latency.
try {
const m = await message.send({
embed: {
title: "Ping?"
}
});
m.edit({
embed: {
title: `Pong! Latency is ${m.timestamp - message.timestamp}ms.`
}
});
} catch (e) {
log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`);
}
}
// lfg
// Handles all LFG commands, creating, editing, deleting
else if (command === "lfg") {
// Light telemetry to see how many times a command is being run
dbClient.execute(`CALL INC_CNT("lfg");`).catch(e => {
log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`);
});
const subcmd = args[0] || "help";
const lfgUid = (args[1] || "").toUpperCase();
// Learn how the LFG command works
if (subcmd === "help" || subcmd === "h" || subcmd === "?") {
message.send(constantCmds.lfgHelp).catch(e => {
log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`);
});
}
// Create a new LFG
else if (subcmd === "create" || subcmd === "c") {
const lfgMsg = await message.send(`Creating new LFG post for <@${message.authorId}>. Please reply with the requested information and watch as your LFG post gets created!`);
const gameButtons: Array<ButtonComponent> = Object.keys(LFGActivities).map(game => {
return {
type: 2,
label: game,
customId: `building@set_game#${game}`,
style: DiscordButtonStyles.Primary
};
});
const buttonComps: Array<ActionRow> = [];
const temp: Array<ActionRow["components"]> = [];
gameButtons.forEach((btn, idx) => {
if (!temp[Math.floor(idx/5)]) {
temp[Math.floor(idx/5)] = [btn];
} else {
temp[Math.floor(idx/5)].push(btn);
}
});
temp.forEach(btns => {
if (btns.length && btns.length <= 5) {
buttonComps.push({
type: 1,
components: btns
});
}
});
const question = await message.send({
content: "Please select a game from the list below. If your game is not listed, please type it out:",
components: buttonComps
});
activeBuilders.push({
userId: message.authorId,
channelId: message.channelId,
step: "set_game",
lfgMsg: lfgMsg,
questionMsg: question,
lastTouch: new Date(),
maxIdle: 60,
editing: false
});
message.delete();
}
// Delete an existing LFG
else if (subcmd === "delete" || subcmd === "d") {
// User provided a Uid, use it
if (lfgUid) {
const matches = activeLFGPosts.filter(lfg => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId && lfgUid === lfg.lfgUid));
// Found one, delete
if (matches.length) {
await deleteMessage(matches[0].channelId, matches[0].messageId, "User requested LFG to be deleted.");
const lfgIdx = activeLFGPosts.findIndex(lfg => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId && lfgUid === lfg.lfgUid));
activeLFGPosts.splice(lfgIdx, 1);
localStorage.setItem("activeLFGPosts", JSON.stringify(activeLFGPosts, (_key, value) =>
typeof value === "bigint" ? value.toString() + "n" : value
));
const m = await message.send(constantCmds.lfgDelete3);
setTimeout(() => {
m.delete();
message.delete();
}, 5000);
}
// Did not find one
else {
const m = await message.send(constantCmds.lfgDelete1);
setTimeout(() => {
m.delete();
message.delete();
}, 5000);
}
}
// User did not provide a Uid, find it automatically
else {
const matches = activeLFGPosts.filter(lfg => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId));
// Found one, delete
if (matches.length === 1) {
await deleteMessage(matches[0].channelId, matches[0].messageId, "User requested LFG to be deleted.");
const lfgIdx = activeLFGPosts.findIndex(lfg => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId));
activeLFGPosts.splice(lfgIdx, 1);
localStorage.setItem("activeLFGPosts", JSON.stringify(activeLFGPosts, (_key, value) =>
typeof value === "bigint" ? value.toString() + "n" : value
));
const m = await message.send(constantCmds.lfgDelete3);
setTimeout(() => {
m.delete();
message.delete();
}, 5000);
}
// Found multiple, notify user
else if (matches.length) {
const deleteMsg = constantCmds.lfgDelete2;
const deepCloningFailedSoThisIsTheSolution = constantCmds.lfgDelete2.embed.fields[0].value;
matches.forEach(mt => {
deleteMsg.embed.fields[0].value += `[${mt.lfgUid}](https://discord.com/channels/${message.guildId}/${mt.channelId}/${mt.messageId})\n`
});
deleteMsg.embed.fields[0].value += "\nThis message will self descruct in 30 seconds."
const m = await message.send(deleteMsg);
constantCmds.lfgDelete2.embed.fields[0].value = deepCloningFailedSoThisIsTheSolution;
setTimeout(() => {
m.delete();
message.delete();
}, 30000);
}
// Found none, notify user you cannot delete other's lfgs
else {
const m = await message.send(constantCmds.lfgDelete1);
setTimeout(() => {
m.delete();
message.delete();
}, 5000);
}
}
}
// Edit an existing LFG
else if (subcmd === "edit" || subcmd === "e") {
// User provided a Uid, use it
if (lfgUid) {
const matches = activeLFGPosts.filter(lfg => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId && lfgUid === lfg.lfgUid));
// Found one, edit
if (matches.length) {
const lfgMessage = await (await getMessage(matches[0].channelId, matches[0].messageId)).edit({
content: `Editing new LFG post for <@${matches[0].ownerId}>. Please reply with the requested information and watch as your LFG post gets edited!`
});
const question = await message.send({
content: "Please select an item to edit from the buttons below:",
components: [{
type: 1,
components: editBtns
}]
});
activeBuilders.push({
userId: matches[0].ownerId,
channelId: matches[0].channelId,
step: "edit_btn",
lfgMsg: lfgMessage,
questionMsg: question,
lastTouch: new Date(),
maxIdle: 60,
editing: true
});
message.delete();
}
// Did not find one
else {
const m = await message.send(constantCmds.lfgEdit1);
setTimeout(() => {
m.delete();
message.delete();
}, 5000);
}
}
// User did not provide a Uid, find it automatically
else {
const matches = activeLFGPosts.filter(lfg => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId));
// Found one, edit
if (matches.length === 1) {
const lfgMessage = await (await getMessage(matches[0].channelId, matches[0].messageId)).edit({
content: `Editing new LFG post for <@${matches[0].ownerId}>. Please reply with the requested information and watch as your LFG post gets edited!`
});
const question = await message.send({
content: "Please select an item to edit from the buttons below:",
components: [{
type: 1,
components: editBtns
}]
});
activeBuilders.push({
userId: matches[0].ownerId,
channelId: matches[0].channelId,
step: "edit_btn",
lfgMsg: lfgMessage,
questionMsg: question,
lastTouch: new Date(),
maxIdle: 60,
editing: true
});
message.delete();
}
// Found multiple, notify user
else if (matches.length) {
const deleteMsg = constantCmds.lfgEdit2;
const deepCloningFailedSoThisIsTheSolution = constantCmds.lfgEdit2.embed.fields[0].value;
matches.forEach(mt => {
deleteMsg.embed.fields[0].value += `[${mt.lfgUid}](https://discord.com/channels/${message.guildId}/${mt.channelId}/${mt.messageId})\n`
});
deleteMsg.embed.fields[0].value += "\nThis message will self descruct in 30 seconds."
const m = await message.send(deleteMsg);
constantCmds.lfgEdit2.embed.fields[0].value = deepCloningFailedSoThisIsTheSolution;
setTimeout(() => {
m.delete();
message.delete();
}, 30000);
}
// Found none, notify user you cannot edit other's lfgs
else {
const m = await message.send(constantCmds.lfgEdit1);
setTimeout(() => {
m.delete();
message.delete();
}, 5000);
}
}
}
}
// report or r (command that failed)
// Manually report something that screwed up
else if (command === "report" || command === "r") {
// Light telemetry to see how many times a command is being run
dbClient.execute(`CALL INC_CNT("report");`).catch(e => {
log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`);
});
sendMessage(config.reportChannel, ("USER REPORT:\n" + args.join(" "))).catch(e => {
log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`);
});
message.send(constantCmds.report).catch(e => {
log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`);
});
}
// version or v
// Returns version of the bot
else if (command === "version" || command === "v") {
// Light telemetry to see how many times a command is being run
dbClient.execute(`CALL INC_CNT("version");`).catch(e => {
log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`);
});
message.send(constantCmds.version).catch(e => {
log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`);
});
}
// info or i
// Info command, prints short desc on bot and some links
else if (command === "info" || command === "i") {
// Light telemetry to see how many times a command is being run
dbClient.execute(`CALL INC_CNT("info");`).catch(e => {
log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`);
});
message.send(constantCmds.info).catch(e => {
log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`);
});
}
// help or h or ?
// Help command, prints available commands
else if (command === "help" || command === "h" || command === "?") {
// Light telemetry to see how many times a command is being run
dbClient.execute(`CALL INC_CNT("help");`).catch(e => {
log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`);
});
message.send(constantCmds.help).catch(e => {
log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`);
});
}
},
interactionCreate: async (interact: Interaction) => {
if (interact.type === DiscordInteractionTypes.MessageComponent) {
if (interact.message && interact.data && (interact.data as ButtonData).customId && interact.member) {
sendInteractionResponse(BigInt(interact.id), interact.token, {
type: 6
});
const [handler, stepInfo] = (interact.data as ButtonData).customId.split("@");
const [action, value] = stepInfo.split("#");
switch (handler) {
case "building": {
await activeBuilders.some(async (x, i) => {
if (x.channelId === BigInt(interact.channelId) && interact.member && x.userId === BigInt(interact.member.user.id)) {
x.lastTouch = new Date();
x = await handleLFGStep(x, value);
if (x.step === "done") {
const member = await structures.createDiscordenoMember(interact.member, BigInt(interact.guildId));
const currentLFG = (x.lfgMsg.embeds[0].fields || []);
const newTimestamp = new Date(parseInt(currentLFG[1].value.split("#")[1]));
const newLfgUid = ALPHABET[Math.floor(Math.random()*26)] + ALPHABET[Math.floor(Math.random()*26)];
const tempMembers = currentLFG[4].name.split(":")[1].split("/");
const currentMembers = parseInt(tempMembers[0]);
const maxMembers = parseInt(tempMembers[1]);
const buttonRow: ActionRow = x.lfgMsg.components[0] as ActionRow;
(buttonRow.components[0] as ButtonComponent).disabled = currentMembers >= maxMembers;
if (currentMembers > maxMembers) {
const currentPeople = currentLFG[4].value.split("\n");
const newAlts = currentPeople.splice(maxMembers - 1);
currentLFG[4].value = currentPeople.join("\n");
currentLFG[5].value = `${newAlts.join("\n")}\n${currentLFG[5].value}`;
currentLFG[4].name = `Members Joined: ${maxMembers}/${maxMembers}`;
}
await x.lfgMsg.edit({
content: "",
embed: {
fields: currentLFG,
footer: {
text: `Created by: ${member.username} | ${newLfgUid}`,
},
timestamp: newTimestamp.toISOString()
},
components: [buttonRow]
});
const activeIdx = activeLFGPosts.findIndex(lfg => (lfg.channelId === x.channelId && lfg.messageId === x.lfgMsg.id && lfg.ownerId === x.userId));
activeLFGPosts[activeIdx].lfgTime = newTimestamp.getTime();
activeLFGPosts[activeIdx].lfgUid = newLfgUid;
await activeBuilders[i].questionMsg.delete()
activeBuilders.splice(i, 1);
} else {
activeBuilders[i] = x;
}
return true;
}
});
break;
}
case "active": {
const member = await structures.createDiscordenoMember(interact.member, BigInt(interact.guildId));
const message = await structures.createDiscordenoMessage(interact.message);
const embeds = message.embeds[0].fields || [];
let results: JoinLeaveType = {
embed: [],
success: false,
full: true
};
switch (action) {
case "join_group":
results = handleMemberJoin(embeds, member, false);
break;
case "leave_group":
results = handleMemberLeave(embeds, member);
break;
case "alternate_group":
results = handleMemberJoin(embeds, member, true);
break;
}
if (results.success) {
const buttonRow: ActionRow = message.components[0] as ActionRow;
(buttonRow.components[0] as ButtonComponent).disabled = results.full;
await message.edit({
embed: {
fields: results.embed,
footer: message.embeds[0].footer,
timestamp: message.embeds[0].timestamp
},
components: [buttonRow]
});
}
break;
}
case "editing": {
await activeBuilders.some(async (x, i) => {
if (x.editing && x.channelId === BigInt(interact.channelId) && interact.member && x.userId === BigInt(interact.member.user.id)) {
x.step = action;
x.lastTouch = new Date();
let nextQuestion = "";
const nextComponents: Array<ActionRow> = [];
switch (action) {
case "set_game": {
nextQuestion = "Please select a game from the list below. If your game is not listed, please type it out:";
const gameButtons: Array<ButtonComponent> = Object.keys(LFGActivities).map(game => {
return {
type: 2,
label: game,
customId: `building@set_game#${game}`,
style: DiscordButtonStyles.Primary
};
});
const temp: Array<ActionRow["components"]> = [];
gameButtons.forEach((btn, idx) => {
if (!temp[Math.floor(idx/5)]) {
temp[Math.floor(idx/5)] = [btn];
} else {
temp[Math.floor(idx/5)].push(btn);
}
});
temp.forEach(btns => {
if (btns.length && btns.length <= 5) {
nextComponents.push({
type: 1,
components: btns
});
}
});
break;
}
case "set_time": {
nextQuestion = "Please enter the time of the activity:";
break;
}
case "set_desc": {
nextQuestion = "Please enter a description for the activity. Enter `none` to skip:";
break;
}
default:
break;
}
x.questionMsg = await x.questionMsg.edit({
content: nextQuestion,
components: nextComponents
});
activeBuilders[i] = x;
return true;
}
});
break;
}
default:
break;
}
}
}
}
}
});

172
src/constantCmds.ts Normal file
View File

@ -0,0 +1,172 @@
import {
DiscordButtonStyles, ActionRow
} from "../deps.ts";
import config from "../config.ts";
export const constantCmds = {
help: {
embed: {
title: `${config.name} Help`,
fields: [
{
name: "All commands must have the bot's prefix before them.",
value: `Default is \`${config.prefix}\`, send <@847256159123013722> to change it.`
},
{
name: "LFG Commands",
value: `
\`lfg help\` - More detailed help for the LFG commands
\`lfg create\` - Create a new LFG post
\`lfg edit\` - Edit an existing LFG post
\`lfg delete\` - Delete an existing LFG post
`
},
{
name: "Utility Commands",
value: `
\`info\` - Information about the bot
\`ping\` - Pings the bot to check its connection
\`report [TEXT]\` - Report an issue to the developer
\`version\` - Prints the bot's current version
`
}
]
}
},
lfgHelp: {
embed: {
title: `${config.name} LFG Help`,
fields: [
{
name: "All commands must have the bot's prefix before them.",
value: `Default is \`${config.prefix}\`, send <@847256159123013722> to change it.`
},
{
name: "lfg create",
value: `
\`lfg create\`, alternatively \`lfg c\`, will walk you through creating a new LFG post. Simply follow the prompts and the bot will walk you through building a new LFG.
Make sure you run this command in the channel you wish the LFG post to be created in.
`,
inline: true
},
{
name: "lfg edit",
value: `
\`lfg edit [id?]\`, alternatively \`lfg e [id?]\`, will walk you through editing an existing LFG. Like \`lfg create\`, the bot will walk you through editing it.
Simply run \`lfg edit\` in the channel where the LFG post lives.
If you only have one LFG in this channel, the editing process will begin.
If you have more than one LFG in this channel, the bot will ask you to specify the LFG post using a two character id.
`,
inline: true
},
{
name: "lfg delete",
value: `
\`lfg delete [id?]\`, alternatively \`lfg d [id?]\`, will delete an existing LFG. You only can delete LFG posts that you own.
Simply run \`lfg delete\` in the channel where the LFG post lives.
If you only have one LFG in this channel, the LFG will be deleted.
If you have more than one LFG in this channel, the bot will ask you to specify the LFG post using a two character id.
`,
inline: true
}
]
}
},
info: {
embed: {
fields: [
{
name: "Group Up, the LFG bot",
value: `Group Up is developed by Ean AKA Burn_E99.
Want to check out my source code? Check it out [here](https://github.com/Burn-E99/GroupUp).
Need help with this bot? Join my support server [here](https://discord.gg/peHASXMZYv).`
}
]
}
},
version: {
embed: {
title: `My current version is ${config.version}`
}
},
report: {
embed: {
fields: [
{
name: "Failed command has been reported to my developer.",
value: "For more in depth support, and information about planned maintenance, please join the support server [here](https://discord.gg/peHASXMZYv)."
}
]
}
},
lfgDelete1: {
embed: {
fields: [
{
name: "Could not find any LFGs to delete.",
value: "Make sure you are the owner of the LFG and are running this command in the same channel as the LFG"
}
]
}
},
lfgDelete2: {
embed: {
fields: [
{
name: `Multiple LFGs found, please run this command again with the two character ID of the LFG you wish to delete.\n\nExample: \`${config.prefix}lfg delete XX\``,
value: "Click on the two character IDs below to view the LFG:\n"
}
]
}
},
lfgDelete3: {
embed: {
title: "LFG deleted."
}
},
lfgEdit1: {
embed: {
fields: [
{
name: "Could not find any LFGs to edit.",
value: "Make sure you are the owner of the LFG and are running this command in the same channel as the LFG"
}
]
}
},
lfgEdit2: {
embed: {
fields: [
{
name: `Multiple LFGs found, please run this command again with the two character ID of the LFG you wish to edit.\n\nExample: \`${config.prefix}lfg edit XX\``,
value: "Click on the two character IDs below to view the LFG:\n"
}
]
}
}
};
export const editBtns: ActionRow["components"] = [
{
type: 2,
label: "Change Game/Activity",
customId: `editing@set_game`,
style: DiscordButtonStyles.Primary
},
{
type: 2,
label: "Change Time",
customId: `editing@set_time`,
style: DiscordButtonStyles.Primary
},
{
type: 2,
label: "Change Description",
customId: `editing@set_desc`,
style: DiscordButtonStyles.Primary
}
];

43
src/games.ts Normal file
View File

@ -0,0 +1,43 @@
export const LFGActivities = {
"Destiny 2": {
"Raids": {
"Vault of Glass": 6,
"Deep Stone Crypt": 6,
"Garden of Salvation": 6,
"Last Wish": 6
},
"Dungeons": {
"Prophecy": 3,
"Pit of Heresy": 3,
"Shattered Throne": 3
},
"Crucible": {
"Iron Banner": 6,
"Quickplay": 6,
"Competitive": 3,
"Trials of Osiris": 3,
"Private Match": 12
},
"Gambit": {
"Classic": 4,
"Private Match": 8
},
"Exotic Missions": {
"Presage": 3,
"Harbinger": 3
},
"Nightfall": 3,
"Miscellaneous": {
"Override": 6,
"Expunge": 3,
"Battlegrounds": 3,
"Wrathborn Hunt": 3,
"Empire Hunt": 3,
"Nightmare Hunt": 3
}
},
"Among Us": {
"Vanilla": 10,
"Modded": 10
}
};

146
src/intervals.ts Normal file
View File

@ -0,0 +1,146 @@
import {
// Discordeno deps
cache,
sendMessage, getMessage, deleteMessage, sendDirectMessage,
// Log4Deno deps
LT, log
} from "../deps.ts";
import { BuildingLFG, ActiveLFG } from "./mod.d.ts";
import config from "../config.ts";
// getRandomStatus() returns status as string
// Gets a new random status for the bot
const getRandomStatus = (): string => {
let status = "";
switch (Math.floor((Math.random() * 5) + 1)) {
case 1:
status = `${config.prefix}help for commands`;
break;
case 2:
status = `Running V${config.version}`;
break;
case 3:
status = `${config.prefix}info to learn more`;
break;
case 4:
status = "Mention me to check my prefix!";
break;
default:
status = `Running LFGs in ${cache.guilds.size} servers`;
break;
}
return status;
};
// updateListStatistics(bot ID, current guild count) returns nothing
// Sends the current server count to all bot list sites we are listed on
const updateListStatistics = (botID: BigInt, serverCount: number): void => {
config.botLists.forEach(async e => {
if (e.enabled) {
log(LT.LOG, `Updating statistics for ${JSON.stringify(e)}`)
const tempHeaders = new Headers();
tempHeaders.append(e.headers[0].header, e.headers[0].value);
tempHeaders.append("Content-Type", "application/json");
// ?{} is a template used in config, just need to replace it with the real value
const response = await fetch(e.apiUrl.replace("?{bot_id}", botID.toString()), {
"method": 'POST',
"headers": tempHeaders,
"body": JSON.stringify(e.body).replace('"?{server_count}"', serverCount.toString()) // ?{server_count} needs the "" removed from around it aswell to make sure its sent as a number
});
log(LT.INFO, `Posted server count to ${e.name}. Results: ${JSON.stringify(response)}`);
}
});
};
const buildingTimeout = async (activeBuilders: Array<BuildingLFG>): Promise<void> => {
const currentTime = new Date().getTime();
for (let i = 0; i < activeBuilders.length; i++) {
if (activeBuilders[i].lastTouch.getTime() + (activeBuilders[i].maxIdle * 1000) < currentTime) {
activeBuilders[i].questionMsg.delete();
if (activeBuilders[i].editing) {
activeBuilders[i].lfgMsg.edit({
content: ""
});
} else {
activeBuilders[i].lfgMsg.delete();
}
const m = await sendMessage(activeBuilders[i].channelId, `<@${activeBuilders[i].userId}>, your LFG ${activeBuilders[i].editing ? "editing" : "creation"} has timed out. Please try again.`);
activeBuilders.splice(i, 1);
setTimeout(() => {
m.delete();
}, 30000);
i--;
}
}
}
const lfgNotifier = async (activeLFGPosts: Array<ActiveLFG>): Promise<void> => {
log(LT.INFO, "Checking for LFG posts to notify/delete/lock")
const tenMin = 10 * 60 * 1000;
const now = new Date().getTime();
for (let i = 0; i < activeLFGPosts.length; i++) {
// Send notifications
if (!activeLFGPosts[i].notified && activeLFGPosts[i].lfgTime < (now + tenMin)) {
log(LT.INFO, `Notifying LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid}`);
const message = await getMessage(activeLFGPosts[i].channelId, activeLFGPosts[i].messageId);
const lfg = message.embeds[0].fields || [];
const lfgActivity = `${lfg[0].name.substr(0, lfg[0].name.length - 1)} - ${lfg[0].value}`;
const guildName = message.guild?.name || "unknown";
const members = lfg[4].value;
let editMsg = "";
await members.split("\n").forEach(async m => {
const [name, tmpId] = m.split(" - <@");
const userId = BigInt(tmpId.substr(0, tmpId.length - 1));
editMsg += `<@${userId}>, `;
await sendDirectMessage(userId, {
embed: {
title: `Hello ${name}! You ${lfgActivity} in ${guildName} starts in less than 10 minutes.`,
fields: [{
name: "Please start grouping up with the other members of this activity:",
value: members
}]
}
});
});
editMsg += `your ${lfgActivity} starts in less than 10 minutes.`;
await message.edit({
content: editMsg
});
activeLFGPosts[i].notified = true;
}
// Lock LFG from editing/Joining/Leaving
if (!activeLFGPosts[i].locked && activeLFGPosts[i].lfgTime < now) {
log(LT.INFO, `Locking LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid}`);
const message = await getMessage(activeLFGPosts[i].channelId, activeLFGPosts[i].messageId);
await message.edit({
components: []
});
activeLFGPosts[i].locked = true;
}
// Delete old LFG post
if (activeLFGPosts[i].lfgTime < (now - tenMin)) {
log(LT.INFO, `Deleting LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid}`);
await deleteMessage(activeLFGPosts[i].channelId, activeLFGPosts[i].messageId, "LFG post expired").catch(e => {
log(LT.WARN, `Failed to delete LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid} | ${JSON.stringify(e)}`);
});
activeLFGPosts.splice(i, 1);
i--;
}
}
localStorage.setItem("activeLFGPosts", JSON.stringify(activeLFGPosts, (_key, value) =>
typeof value === "bigint" ? value.toString() + "n" : value
));
}
export default { getRandomStatus, updateListStatistics, buildingTimeout, lfgNotifier };

9
src/lfgHandlers.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
import {
EmbedField
} from "../deps.ts";
export type JoinLeaveType = {
embed: EmbedField[],
success: boolean,
full: boolean
}

401
src/lfgHandlers.ts Normal file
View File

@ -0,0 +1,401 @@
import {
ActionRow, ButtonComponent, DiscordButtonStyles, EmbedField, DiscordenoMember
} from "../deps.ts";
import { JoinLeaveType } from "./lfgHandlers.d.ts";
import { BuildingLFG } from "./mod.d.ts";
import { LFGActivities } from "./games.ts";
import { determineTZ } from "./timeUtils.ts"
export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise<BuildingLFG> => {
const currentLFG = (wipLFG.lfgMsg.embeds[0] || { fields: undefined }).fields || [
{
name: ". . .",
value: ". . .",
inline: true
},
{
name: "Start Time:",
value: ". . .",
inline: true
},
{
name: "Add to Calendar:",
value: "Coming Soon:tm:",
inline: true
},
{
name: "Description:",
value: ". . .",
inline: false
},
{
name: `Members Joined: 0/?`,
value: "None",
inline: true
},
{
name: "Alternates:",
value: "None",
inline: true
}
];
let nextQuestion = "";
const nextComponents: Array<ActionRow> = [];
let editFlag = true;
switch (wipLFG.step) {
case "set_game": {
currentLFG[0].name = input;
if (Object.prototype.hasOwnProperty.call(LFGActivities, input)) {
nextQuestion = "Please select an Activity from the list below. Depending on the game selected, these may be categories you can use to drill down to a specific activity.\n\nIf your activity is not listed, please type it out:";
let tempObj = {};
Object.entries(LFGActivities).some(e => {
if (e[0] === input) {
tempObj = e[1];
return true;
}
});
const activityButtons: Array<ButtonComponent> = Object.keys(tempObj).map(activity => {
return {
type: 2,
label: activity,
customId: `building@set_activity#${activity}`,
style: DiscordButtonStyles.Primary
};
});
const temp: Array<ActionRow["components"]> = [];
activityButtons.forEach((btn, idx) => {
if (!temp[Math.floor(idx/5)]) {
temp[Math.floor(idx/5)] = [btn];
} else {
temp[Math.floor(idx/5)].push(btn);
}
});
temp.forEach(btns => {
if (btns.length && btns.length <= 5) {
nextComponents.push({
type: 1,
components: btns
});
}
});
} else {
nextQuestion = "Please type the activity name out:";
}
wipLFG.step = "set_activity";
break;
}
case "set_activity": {
const game = currentLFG[0].name;
let tempObj;
Object.entries(LFGActivities).some(e => {
if (e[0] === game) {
Object.entries(e[1]).some(f => {
if (f[0] === input) {
tempObj = f[1];
return true;
}
});
return true;
}
});
currentLFG[0].name = `${game}:`;
currentLFG[0].value = input;
if (typeof tempObj === "number") {
// Activity
currentLFG[4].name = `Members Joined: ${currentLFG[4].value === "None" ? 0 : currentLFG[4].value.split("\n").length}/${tempObj}`;
nextQuestion = wipLFG.editing ? "Finalizing, please wait. . ." : "Please enter the time of the activity:";
wipLFG.step = wipLFG.editing ? "done" : "set_time";
} else if (!tempObj) {
// Custom
nextQuestion = "Please enter the max number of members for this activity:";
wipLFG.step = "set_player_cnt";
} else {
// Category
nextQuestion = "Please select an Activity from the list below.\n\nIf your activity is not listed, please type it out:";
currentLFG[0].name = game;
const activityButtons: Array<ButtonComponent> = Object.keys(tempObj).map(activity => {
return {
type: 2,
label: activity,
customId: `building@set_activity_from_category#${activity}`,
style: DiscordButtonStyles.Primary
};
});
const temp: Array<ActionRow["components"]> = [];
activityButtons.forEach((btn, idx) => {
if (!temp[Math.floor(idx/5)]) {
temp[Math.floor(idx/5)] = [btn];
} else {
temp[Math.floor(idx/5)].push(btn);
}
});
temp.forEach(btns => {
if (btns.length && btns.length <= 5) {
nextComponents.push({
type: 1,
components: btns
});
}
});
wipLFG.step = "set_activity_from_category";
}
break;
}
case "set_activity_from_category": {
const game = currentLFG[0].name;
const category = currentLFG[0].value;
let tempObj;
Object.entries(LFGActivities).some(e => {
if (e[0] === game) {
Object.entries(e[1]).some(f => {
if (f[0] === category) {
Object.entries(f[1]).some(g => {
if (g[0] === input) {
tempObj = g[1];
return true;
}
});
return true;
}
});
return true;
}
});
currentLFG[0].name = `${game}:`;
currentLFG[0].value = input;
if (tempObj) {
currentLFG[4].name = `Members Joined: ${currentLFG[4].value === "None" ? 0 : currentLFG[4].value.split("\n").length}/${tempObj}`;
nextQuestion = wipLFG.editing ? "Finalizing, please wait. . ." : "Please enter the time of the activity:";
wipLFG.step = wipLFG.editing ? "done" : "set_time";
} else {
nextQuestion = "Please enter the max number of members for this activity:";
wipLFG.step = "set_player_cnt";
}
break;
}
case "set_player_cnt": {
if (parseInt(input)) {
currentLFG[4].name = `Members Joined: ${currentLFG[4].value === "None" ? 0 : currentLFG[4].value.split("\n").length}/${parseInt(input)}`;
nextQuestion = wipLFG.editing ? "Finalizing, please wait. . ." : "Please enter the time of the activity:";
wipLFG.step = wipLFG.editing ? "done" : "set_time";
} else {
editFlag = false;
nextQuestion = `Input max members "${input}" is invalid, please make sure you are only entering a number.\n\nPlease enter the max number of members for this activity:`
}
break;
}
case "set_time": {
const today = new Date();
let lfgDate = `${today.getMonth() + 1}/${today.getDate()}`,
lfgTime = "",
lfgTZ = "",
lfgPeriod = "";
input.split(" ").forEach(c => {
if (c.includes("/")) {
lfgDate = c;
} else if (c.includes(":") || parseInt(c).toString() === c) {
lfgTime = c;
} else if (c.toLowerCase() === "am" || c.toLowerCase() === "pm") {
lfgPeriod = c.toLowerCase();
} else if (c.toLowerCase().includes("am") || c.toLowerCase().includes("pm")) {
lfgTime = c.substr(0, c.length - 2);
lfgPeriod = c.toLowerCase().includes("am") ? "am" : "pm";
} else {
lfgTZ = determineTZ(c);
}
});
if (!lfgTZ) {
lfgTZ = determineTZ("ET");
}
if (!lfgTime.includes(":")) {
lfgTime += ":00";
}
if (!lfgPeriod) {
lfgPeriod = parseInt(lfgTime.split(":")[0]) >= 12 ? "pm" : "am";
}
lfgPeriod = lfgPeriod.toUpperCase();
lfgTZ = lfgTZ.toUpperCase();
lfgDate = `${lfgDate.split("/")[0]}/${lfgDate.split("/")[1]}/${today.getFullYear()}`;
const lfgDateTime = new Date(`${lfgTime} ${lfgPeriod} ${lfgTZ} ${lfgDate}`);
lfgDate = `${lfgDate.split("/")[0]}/${lfgDate.split("/")[1]}`;
const lfgDateStr = `[${lfgTime} ${lfgPeriod} ${lfgTZ} ${lfgDate}](https://groupup.eanm.dev/tz#${lfgDateTime.getTime()})`;
currentLFG[1].name = "Start Time (Click for Conversion):";
currentLFG[1].value = lfgDateStr;
if (isNaN(lfgDateTime.getTime())) {
nextQuestion = `Input time "${input}" is invalid, please make sure you have the timezone set correctly.\n\nPlease enter the time of the activity:`;
editFlag = false;
} else {
nextQuestion = wipLFG.editing ? "Finalizing, please wait. . ." : "Please enter a description for the activity. Enter `none` to skip:";
wipLFG.step = wipLFG.editing ? "done" : "set_desc";
}
break;
}
case "set_desc":{
if (input === "none") {
input = currentLFG[0].value;
}
currentLFG[3].value = input;
nextQuestion = "Finalizing, please wait. . .";
wipLFG.step = "done";
break;
}
default:
break;
}
if (editFlag) {
wipLFG.lfgMsg = await wipLFG.lfgMsg.edit({
embed: {
fields: currentLFG
}
});
}
wipLFG.questionMsg = await wipLFG.questionMsg.edit({
content: nextQuestion,
components: nextComponents
});
return wipLFG;
};
export const handleMemberJoin = (lfg: EmbedField[], member: DiscordenoMember, alternate: boolean): JoinLeaveType => {
let success = false;
const userStr = `${member.username} - <@${member.id}>`;
const tempMembers = lfg[4].name.split(":")[1].split("/");
let currentMembers = parseInt(tempMembers[0]);
const maxMembers = parseInt(tempMembers[1]);
if (alternate && !lfg[5].value.includes(member.id.toString())) {
if (lfg[4].value.includes(member.id.toString())) {
const tempArr = lfg[4].value.split("\n");
const memberIdx = tempArr.findIndex(m => m.includes(member.id.toString()));
tempArr.splice(memberIdx, 1)
lfg[4].value = tempArr.join("\n") || "None";
if (currentMembers) {
currentMembers--;
}
lfg[4].name = `Members Joined: ${currentMembers}/${maxMembers}`;
}
if (lfg[5].value === "None") {
lfg[5].value = userStr;
} else {
lfg[5].value += `\n${userStr}`;
}
success = true;
} else if (!alternate &&currentMembers < maxMembers && !lfg[4].value.includes(member.id.toString())) {
if (lfg[5].value.includes(member.id.toString())) {
const tempArr = lfg[5].value.split("\n");
const memberIdx = tempArr.findIndex(m => m.includes(member.id.toString()));
tempArr.splice(memberIdx, 1)
lfg[5].value = tempArr.join("\n") || "None";
}
if (lfg[4].value === "None") {
lfg[4].value = userStr;
} else {
lfg[4].value += `\n${userStr}`;
}
currentMembers++;
lfg[4].name = `Members Joined: ${currentMembers}/${maxMembers}`;
success = true;
}
return {
embed: lfg,
success: success,
full: currentMembers === maxMembers
};
};
export const handleMemberLeave = (lfg: EmbedField[], member: DiscordenoMember): JoinLeaveType => {
let success = false;
const memberId = member.id.toString();
const tempMembers = lfg[4].name.split(":")[1].split("/");
let currentMembers = parseInt(tempMembers[0]);
const maxMembers = parseInt(tempMembers[1]);
if (lfg[4].value.includes(memberId)) {
const tempArr = lfg[4].value.split("\n");
const memberIdx = tempArr.findIndex(m => m.includes(memberId));
tempArr.splice(memberIdx, 1);
lfg[4].value = tempArr.join("\n") || "None";
if (currentMembers) {
currentMembers--;
}
lfg[4].name = `Members Joined: ${currentMembers}/${maxMembers}`;
success = true;
}
if (lfg[5].value.includes(memberId)) {
const tempArr = lfg[5].value.split("\n");
const memberIdx = tempArr.findIndex(m => m.includes(memberId));
tempArr.splice(memberIdx, 1);
lfg[5].value = tempArr.join("\n") || "None";
success = true;
}
return {
embed: lfg,
success: success,
full: currentMembers === maxMembers
};
};

37
src/mod.d.ts vendored Normal file
View File

@ -0,0 +1,37 @@
import {
DiscordenoMessage
} from "../deps.ts";
export type BuildingLFG = {
userId: bigint,
channelId: bigint,
step: string,
lfgMsg: DiscordenoMessage,
questionMsg: DiscordenoMessage,
lastTouch: Date,
maxIdle: number,
editing: boolean
}
export type ActiveLFG = {
messageId: bigint,
channelId: bigint,
ownerId: bigint,
lfgUid: string,
lfgTime: number,
notified: boolean,
locked: boolean
}
export type GuildPrefixes = {
guildId: bigint,
prefix: string
}
// TEMP
export interface ButtonData {
/** with the value you defined for this component */
customId: string;
/** The type of this component */
componentType: 2;
}

16
src/timeUtils.ts Normal file
View File

@ -0,0 +1,16 @@
export const determineTZ = (tz: string): string => {
tz = tz.toUpperCase();
if (tz === "ET" || tz === "CT" || tz === "MT" || tz === "PT") {
const today = new Date();
const jan = new Date(today.getFullYear(), 0, 1);
const jul = new Date(today.getFullYear(), 6, 1);
if (today.getTimezoneOffset() < Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset())) {
tz = `${tz.substr(0, 1)}DT`;
} else {
tz = `${tz.substr(0, 1)}ST`;
}
}
return tz;
};

1
start.command Normal file
View File

@ -0,0 +1 @@
deno run --allow-write=./logs --location=https://groupup.local --allow-net .\mod.ts

View File

@ -0,0 +1,59 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<meta name="HandheldFriendly" content="true"/>
<meta name="author" content="Ean Milligan (ean@milligan.dev)">
<meta name="designer" content="Ean Milligan (ean@milligan.dev)">
<meta name="publisher" content="Ean Milligan (ean@milligan.dev)">
<title>Group Up Time Checker</title>
<meta name="description" content="The Artificer Discord Bot is a advanced dice rolling bot utilizing the Roll20 format. The Artificer is fast and reliable and free to use.">
<meta name="keywords" content="The Artificer, Discord bot, dice roller, dice rolling, roll, rolling, dice, roller, bot, artificer">
<meta name="robots" content="index, follow">
<meta name="revisit-after" content="7 days">
<meta name="distribution" content="web">
<meta name="robots" content="noodp, noydir">
<meta name="distribution" content="web">
<meta name="web_author" content="Ean Milligan (ean@milligan.dev)">
<link rel="shortcut icon" href="./favicon.ico">
<style>
body {
font-family: sans-serif;
font-size: 5rem;
height: 100vh;
padding: 0;
margin: 0;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
color: #dcddde;
background-color: #2f3136;
}
</style>
</head>
<body>
<div id="message">
I don't know why you are here, the URL should have a timestamp in it.
</div>
<script>
if (window.location.hash) {
console.log(window.location.hash)
var groupDate = new Date(parseInt(window.location.hash.substr(1)));
document.getElementById("message").innerText = "Your event is happening at:\n\n" + groupDate.toLocaleString();
}
</script>
</body>
</html>