Add initial implementation and configuration files for Discord bot and dashboard

This commit is contained in:
2026-01-28 05:51:44 +00:00
parent 053db5e32b
commit 66ffe17aed
114 changed files with 775203 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
const fs = require('fs');
const path = require('path');
const { Client, GatewayIntentBits } = require('discord.js');
const { discordToken } = require('@config'); // Using alias for config
const environment = process.env.NODE_ENV || 'development';
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
const serverDataFilePath = path.join(
__dirname,
`discord/store/${environment}-serverData.json`
);
let serverData = {};
if (fs.existsSync(serverDataFilePath)) {
serverData = JSON.parse(fs.readFileSync(serverDataFilePath, 'utf8'));
} else {
fs.writeFileSync(serverDataFilePath, JSON.stringify({}, null, 2), 'utf8');
console.warn(
`Warning: File not found at ${serverDataFilePath}. Using empty server data.`
);
}
// Load event handlers
const eventFiles = fs
.readdirSync('./src/discord/events')
.filter(file => file.endsWith('.js') && !file.endsWith('.spec.js'));
for (const file of eventFiles) {
const event = require(`./discord/events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, serverData));
} else {
client.on(event.name, (...args) => event.execute(...args, serverData));
}
}
client.login(discordToken);

View File

@@ -0,0 +1,18 @@
const environment = process.env.NODE_ENV || 'development';
const config = {
development: {
discordToken: process.env.DISCORD_TOKEN,
discordClientId: process.env.DISCORD_CLIENT_ID,
challongeApiKey: process.env.CHALLONGE_API_KEY,
redisUrl: process.env.REDIS_URL
},
production: {
discordToken: process.env.DISCORD_TOKEN,
discordClientId: process.env.DISCORD_CLIENT_ID,
challongeApiKey: process.env.CHALLONGE_API_KEY,
redisUrl: process.env.REDIS_URL
}
};
module.exports = config[environment];

View File

@@ -0,0 +1,5 @@
{
"discordToken": "MTI4NTQzMDg4NDI5NTUxMjE1Nw.GzGRez.gxPqBeVAovAg5DaMBpCT9Vt54qQKCtx3f5gDGw",
"discordClientId": "1285430884295512157",
"challongeApiKey": "DOV8yWmlIFdKYIisc7WtcNlVsXlXmfAsqtcn6k5d"
}

View File

@@ -0,0 +1,26 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*storybook.log

View File

@@ -0,0 +1,20 @@
/** @type { import('@storybook/vue3-vite').StorybookConfig } */
const config = {
"stories": [
"../src/**/*.mdx",
"../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"
],
"addons": [
"@storybook/addon-essentials",
"@storybook/addon-onboarding",
"@chromatic-com/storybook",
"@storybook/experimental-addon-test"
],
"framework": {
"name": "@storybook/vue3-vite",
"options": {}
}
};
export default config;

View File

@@ -0,0 +1,13 @@
/** @type { import('@storybook/vue3').Preview } */
const preview = {
parameters: {
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
},
};
export default preview;

View File

@@ -0,0 +1,9 @@
import { beforeAll } from 'vitest';
import { setProjectAnnotations } from '@storybook/vue3';
import * as projectAnnotations from './preview';
// This is an important step to apply the right configuration when testing your stories.
// More info at: https://storybook.js.org/docs/api/portable-stories/portable-stories-vitest#setprojectannotations
const project = setProjectAnnotations([projectAnnotations]);
beforeAll(project.beforeAll);

View File

@@ -0,0 +1,3 @@
{
"recommendations": ["Vue.volar"]
}

View File

@@ -0,0 +1,20 @@
# Use the official Node.js image as the base image
FROM node:22-slim
# Set the working directory inside the container
WORKDIR /app
# Copy package.json and package-lock.json to the working directory
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy the rest of the application code to the working directory
COPY . .
# Expose the port for the dashboard
EXPOSE 8000
# Start the dashboard
CMD ["npm", "run", "dev"]

View File

@@ -0,0 +1,5 @@
# Vue 3 + Vite
This template should help get you started developing with Vue 3 in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about IDE Support for Vue in the [Vue Docs Scaling up Guide](https://vuejs.org/guide/scaling-up/tooling.html#ide-support).

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,35 @@
{
"name": "package.json",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --port 8000",
"build": "vite build",
"preview": "vite preview",
"storybook": "storybook dev -p 8080",
"dev:all": "concurrently \"npm run dev\" \"npm run storybook\" \"open http://localhost:8000\" \"open http://localhost:8080\"",
"build-storybook": "storybook build"
},
"dependencies": {
"concurrently": "^9.1.2",
"vue": "^3.5.13"
},
"devDependencies": {
"@chromatic-com/storybook": "^3.2.6",
"@storybook/addon-essentials": "^8.6.12",
"@storybook/addon-onboarding": "^8.6.12",
"@storybook/blocks": "^8.6.12",
"@storybook/experimental-addon-test": "^8.6.12",
"@storybook/test": "^8.6.12",
"@storybook/vue3": "^8.6.12",
"@storybook/vue3-vite": "^8.6.12",
"@vitejs/plugin-vue": "^5.2.1",
"@vitest/browser": "^3.1.1",
"@vitest/coverage-v8": "^3.1.1",
"playwright": "^1.51.1",
"storybook": "^8.6.12",
"vite": "^6.2.0",
"vitest": "^3.1.1"
}
}

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,30 @@
<script setup>
import HelloWorld from './components/HelloWorld.vue'
</script>
<template>
<div>
<a href="https://vite.dev" target="_blank">
<img src="/vite.svg" class="logo" alt="Vite logo" />
</a>
<a href="https://vuejs.org/" target="_blank">
<img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
</a>
</div>
<HelloWorld msg="Vite + Vue" />
</template>
<style scoped>
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
filter: drop-shadow(0 0 2em #42b883aa);
}
</style>

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

After

Width:  |  Height:  |  Size: 496 B

View File

@@ -0,0 +1,43 @@
<script setup>
import { ref } from 'vue'
defineProps({
msg: String,
})
const count = ref(0)
</script>
<template>
<h1>{{ msg }}</h1>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<p>
Edit
<code>components/HelloWorld.vue</code> to test HMR
</p>
</div>
<p>
Check out
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
>create-vue</a
>, the official Vue + Vite starter
</p>
<p>
Learn more about IDE Support for Vue in the
<a
href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
target="_blank"
>Vue Docs Scaling up Guide</a
>.
</p>
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>

View File

@@ -0,0 +1,5 @@
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
createApp(App).mount('#app')

View File

@@ -0,0 +1,44 @@
import { fn } from '@storybook/test';
import MyButton from './Button.vue';
// More on how to set up stories at: https://storybook.js.org/docs/writing-stories
export default {
title: 'Example/Button',
component: MyButton,
tags: ['autodocs'],
argTypes: {
size: { control: { type: 'select' }, options: ['small', 'medium', 'large'] },
backgroundColor: { control: 'color' },
},
// Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args
args: { onClick: fn() },
};
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Primary = {
args: {
primary: true,
label: 'Button',
},
};
export const Secondary = {
args: {
label: 'Button',
},
};
export const Large = {
args: {
size: 'large',
label: 'Button',
},
};
export const Small = {
args: {
size: 'small',
label: 'Button',
},
};

View File

@@ -0,0 +1,52 @@
<template>
<button type="button" :class="classes" @click="onClick" :style="style">{{ label }}</button>
</template>
<script>
import './button.css';
import { reactive, computed } from 'vue';
export default {
name: 'my-button',
props: {
label: {
type: String,
required: true,
},
primary: {
type: Boolean,
default: false,
},
size: {
type: String,
validator: function (value) {
return ['small', 'medium', 'large'].indexOf(value) !== -1;
},
},
backgroundColor: {
type: String,
},
},
emits: ['click'],
setup(props, { emit }) {
props = reactive(props);
return {
classes: computed(() => ({
'storybook-button': true,
'storybook-button--primary': props.primary,
'storybook-button--secondary': !props.primary,
[`storybook-button--${props.size || 'medium'}`]: true,
})),
style: computed(() => ({
backgroundColor: props.backgroundColor,
})),
onClick() {
emit('click');
},
};
},
};
</script>

View File

@@ -0,0 +1,364 @@
import { Meta } from "@storybook/blocks";
import Github from "./assets/github.svg";
import Discord from "./assets/discord.svg";
import Youtube from "./assets/youtube.svg";
import Tutorials from "./assets/tutorials.svg";
import Styling from "./assets/styling.png";
import Context from "./assets/context.png";
import Assets from "./assets/assets.png";
import Docs from "./assets/docs.png";
import Share from "./assets/share.png";
import FigmaPlugin from "./assets/figma-plugin.png";
import Testing from "./assets/testing.png";
import Accessibility from "./assets/accessibility.png";
import Theming from "./assets/theming.png";
import AddonLibrary from "./assets/addon-library.png";
export const RightArrow = () => <svg
viewBox="0 0 14 14"
width="8px"
height="14px"
style={{
marginLeft: '4px',
display: 'inline-block',
shapeRendering: 'inherit',
verticalAlign: 'middle',
fill: 'currentColor',
'path fill': 'currentColor'
}}
>
<path d="m11.1 7.35-5.5 5.5a.5.5 0 0 1-.7-.7L10.04 7 4.9 1.85a.5.5 0 1 1 .7-.7l5.5 5.5c.2.2.2.5 0 .7Z" />
</svg>
<Meta title="Configure your project" />
<div className="sb-container">
<div className='sb-section-title'>
# Configure your project
Because Storybook works separately from your app, you'll need to configure it for your specific stack and setup. Below, explore guides for configuring Storybook with popular frameworks and tools. If you get stuck, learn how you can ask for help from our community.
</div>
<div className="sb-section">
<div className="sb-section-item">
<img
src={Styling}
alt="A wall of logos representing different styling technologies"
/>
<h4 className="sb-section-item-heading">Add styling and CSS</h4>
<p className="sb-section-item-paragraph">Like with web applications, there are many ways to include CSS within Storybook. Learn more about setting up styling within Storybook.</p>
<a
href="https://storybook.js.org/docs/configure/styling-and-css/?renderer=vue"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-section-item">
<img
src={Context}
alt="An abstraction representing the composition of data for a component"
/>
<h4 className="sb-section-item-heading">Provide context and mocking</h4>
<p className="sb-section-item-paragraph">Often when a story doesn't render, it's because your component is expecting a specific environment or context (like a theme provider) to be available.</p>
<a
href="https://storybook.js.org/docs/writing-stories/decorators/?renderer=vue#context-for-mocking"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-section-item">
<img src={Assets} alt="A representation of typography and image assets" />
<div>
<h4 className="sb-section-item-heading">Load assets and resources</h4>
<p className="sb-section-item-paragraph">To link static files (like fonts) to your projects and stories, use the
`staticDirs` configuration option to specify folders to load when
starting Storybook.</p>
<a
href="https://storybook.js.org/docs/configure/images-and-assets/?renderer=vue"
target="_blank"
>Learn more<RightArrow /></a>
</div>
</div>
</div>
</div>
<div className="sb-container">
<div className='sb-section-title'>
# Do more with Storybook
Now that you know the basics, let's explore other parts of Storybook that will improve your experience. This list is just to get you started. You can customise Storybook in many ways to fit your needs.
</div>
<div className="sb-section">
<div className="sb-features-grid">
<div className="sb-grid-item">
<img src={Docs} alt="A screenshot showing the autodocs tag being set, pointing a docs page being generated" />
<h4 className="sb-section-item-heading">Autodocs</h4>
<p className="sb-section-item-paragraph">Auto-generate living,
interactive reference documentation from your components and stories.</p>
<a
href="https://storybook.js.org/docs/writing-docs/autodocs/?renderer=vue"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<img src={Share} alt="A browser window showing a Storybook being published to a chromatic.com URL" />
<h4 className="sb-section-item-heading">Publish to Chromatic</h4>
<p className="sb-section-item-paragraph">Publish your Storybook to review and collaborate with your entire team.</p>
<a
href="https://storybook.js.org/docs/sharing/publish-storybook/?renderer=vue#publish-storybook-with-chromatic"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<img src={FigmaPlugin} alt="Windows showing the Storybook plugin in Figma" />
<h4 className="sb-section-item-heading">Figma Plugin</h4>
<p className="sb-section-item-paragraph">Embed your stories into Figma to cross-reference the design and live
implementation in one place.</p>
<a
href="https://storybook.js.org/docs/sharing/design-integrations/?renderer=vue#embed-storybook-in-figma-with-the-plugin"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<img src={Testing} alt="Screenshot of tests passing and failing" />
<h4 className="sb-section-item-heading">Testing</h4>
<p className="sb-section-item-paragraph">Use stories to test a component in all its variations, no matter how
complex.</p>
<a
href="https://storybook.js.org/docs/writing-tests/?renderer=vue"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<img src={Accessibility} alt="Screenshot of accessibility tests passing and failing" />
<h4 className="sb-section-item-heading">Accessibility</h4>
<p className="sb-section-item-paragraph">Automatically test your components for a11y issues as you develop.</p>
<a
href="https://storybook.js.org/docs/writing-tests/accessibility-testing/?renderer=vue"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<img src={Theming} alt="Screenshot of Storybook in light and dark mode" />
<h4 className="sb-section-item-heading">Theming</h4>
<p className="sb-section-item-paragraph">Theme Storybook's UI to personalize it to your project.</p>
<a
href="https://storybook.js.org/docs/configure/theming/?renderer=vue"
target="_blank"
>Learn more<RightArrow /></a>
</div>
</div>
</div>
</div>
<div className='sb-addon'>
<div className='sb-addon-text'>
<h4>Addons</h4>
<p className="sb-section-item-paragraph">Integrate your tools with Storybook to connect workflows.</p>
<a
href="https://storybook.js.org/addons/"
target="_blank"
>Discover all addons<RightArrow /></a>
</div>
<div className='sb-addon-img'>
<img src={AddonLibrary} alt="Integrate your tools with Storybook to connect workflows." />
</div>
</div>
<div className="sb-section sb-socials">
<div className="sb-section-item">
<img src={Github} alt="Github logo" className="sb-explore-image"/>
Join our contributors building the future of UI development.
<a
href="https://github.com/storybookjs/storybook"
target="_blank"
>Star on GitHub<RightArrow /></a>
</div>
<div className="sb-section-item">
<img src={Discord} alt="Discord logo" className="sb-explore-image"/>
<div>
Get support and chat with frontend developers.
<a
href="https://discord.gg/storybook"
target="_blank"
>Join Discord server<RightArrow /></a>
</div>
</div>
<div className="sb-section-item">
<img src={Youtube} alt="Youtube logo" className="sb-explore-image"/>
<div>
Watch tutorials, feature previews and interviews.
<a
href="https://www.youtube.com/@chromaticui"
target="_blank"
>Watch on YouTube<RightArrow /></a>
</div>
</div>
<div className="sb-section-item">
<img src={Tutorials} alt="A book" className="sb-explore-image"/>
<p>Follow guided walkthroughs on for key workflows.</p>
<a
href="https://storybook.js.org/tutorials/"
target="_blank"
>Discover tutorials<RightArrow /></a>
</div>
</div>
<style>
{`
.sb-container {
margin-bottom: 48px;
}
.sb-section {
width: 100%;
display: flex;
flex-direction: row;
gap: 20px;
}
img {
object-fit: cover;
}
.sb-section-title {
margin-bottom: 32px;
}
.sb-section a:not(h1 a, h2 a, h3 a) {
font-size: 14px;
}
.sb-section-item, .sb-grid-item {
flex: 1;
display: flex;
flex-direction: column;
}
.sb-section-item-heading {
padding-top: 20px !important;
padding-bottom: 5px !important;
margin: 0 !important;
}
.sb-section-item-paragraph {
margin: 0;
padding-bottom: 10px;
}
.sb-chevron {
margin-left: 5px;
}
.sb-features-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 32px 20px;
}
.sb-socials {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
.sb-socials p {
margin-bottom: 10px;
}
.sb-explore-image {
max-height: 32px;
align-self: flex-start;
}
.sb-addon {
width: 100%;
display: flex;
align-items: center;
position: relative;
background-color: #EEF3F8;
border-radius: 5px;
border: 1px solid rgba(0, 0, 0, 0.05);
background: #EEF3F8;
height: 180px;
margin-bottom: 48px;
overflow: hidden;
}
.sb-addon-text {
padding-left: 48px;
max-width: 240px;
}
.sb-addon-text h4 {
padding-top: 0px;
}
.sb-addon-img {
position: absolute;
left: 345px;
top: 0;
height: 100%;
width: 200%;
overflow: hidden;
}
.sb-addon-img img {
width: 650px;
transform: rotate(-15deg);
margin-left: 40px;
margin-top: -72px;
box-shadow: 0 0 1px rgba(255, 255, 255, 0);
backface-visibility: hidden;
}
@media screen and (max-width: 800px) {
.sb-addon-img {
left: 300px;
}
}
@media screen and (max-width: 600px) {
.sb-section {
flex-direction: column;
}
.sb-features-grid {
grid-template-columns: repeat(1, 1fr);
}
.sb-socials {
grid-template-columns: repeat(2, 1fr);
}
.sb-addon {
height: 280px;
align-items: flex-start;
padding-top: 32px;
overflow: hidden;
}
.sb-addon-text {
padding-left: 24px;
}
.sb-addon-img {
right: 0;
left: 0;
top: 130px;
bottom: 0;
overflow: hidden;
height: auto;
width: 124%;
}
.sb-addon-img img {
width: 1200px;
transform: rotate(-12deg);
margin-left: 0;
margin-top: 48px;
margin-bottom: -40px;
margin-left: -24px;
}
}
`}
</style>

View File

@@ -0,0 +1,48 @@
import { fn } from '@storybook/test';
import MyHeader from './Header.vue';
export default {
title: 'Example/Header',
component: MyHeader,
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
render: (args) => ({
// Components used in your story `template` are defined in the `components` object
components: {
MyHeader,
},
// The story's `args` need to be mapped into the template through the `setup()` method
setup() {
// Story args can be spread into the returned object
return {
...args,
};
},
// Then, the spread values can be accessed directly in the template
template: '<my-header :user="user" />',
}),
parameters: {
// More on how to position stories at: https://storybook.js.org/docs/configure/story-layout
layout: 'fullscreen',
},
args: {
onLogin: fn(),
onLogout: fn(),
onCreateAccount: fn(),
},
};
export const LoggedIn = {
args: {
user: {
name: 'Jane Doe',
},
},
};
export const LoggedOut = {
args: {
user: null,
},
};

View File

@@ -0,0 +1,59 @@
<template>
<header>
<div class="storybook-header">
<div>
<svg width="32" height="32" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd">
<path
d="M10 0h12a10 10 0 0110 10v12a10 10 0 01-10 10H10A10 10 0 010 22V10A10 10 0 0110 0z"
fill="#FFF"
/>
<path
d="M5.3 10.6l10.4 6v11.1l-10.4-6v-11zm11.4-6.2l9.7 5.5-9.7 5.6V4.4z"
fill="#555AB9"
/>
<path
d="M27.2 10.6v11.2l-10.5 6V16.5l10.5-6zM15.7 4.4v11L6 10l9.7-5.5z"
fill="#91BAF8"
/>
</g>
</svg>
<h1>Acme</h1>
</div>
<div>
<span class="welcome" v-if="user"
>Welcome, <b>{{ user.name }}</b
>!</span
>
<my-button size="small" @click="$emit('logout')" label="Log out" v-if="user" />
<my-button size="small" @click="$emit('login')" label="Log in" v-if="!user" />
<my-button
primary
size="small"
@click="$emit('createAccount')"
label="Sign up"
v-if="!user"
/>
</div>
</div>
</header>
</template>
<script>
import './header.css';
import MyButton from './Button.vue';
export default {
name: 'my-header',
components: { MyButton },
props: {
user: {
type: Object,
},
},
emits: ['login', 'logout', 'createAccount'],
};
</script>

View File

@@ -0,0 +1,34 @@
import { expect, userEvent, within } from '@storybook/test';
import MyPage from './Page.vue';
export default {
title: 'Example/Page',
component: MyPage,
parameters: {
// More on how to position stories at: https://storybook.js.org/docs/configure/story-layout
layout: 'fullscreen',
},
};
export const LoggedOut = {};
// More on component testing: https://storybook.js.org/docs/writing-tests/component-testing
export const LoggedIn = {
render: () => ({
components: {
MyPage,
},
template: '<my-page />',
}),
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const loginButton = canvas.getByRole('button', { name: /Log in/i });
await expect(loginButton).toBeInTheDocument();
await userEvent.click(loginButton);
await expect(loginButton).not.toBeInTheDocument();
const logoutButton = canvas.getByRole('button', { name: /Log out/i });
await expect(logoutButton).toBeInTheDocument();
},
};

View File

@@ -0,0 +1,83 @@
<template>
<article>
<my-header :user="user" @login="onLogin" @logout="onLogout" @createAccount="onCreateAccount" />
<section class="storybook-page">
<h2>Pages in Storybook</h2>
<p>
We recommend building UIs with a
<a href="https://componentdriven.org" target="_blank" rel="noopener noreferrer">
<strong>component-driven</strong>
</a>
process starting with atomic components and ending with pages.
</p>
<p>
Render pages with mock data. This makes it easy to build and review page states without
needing to navigate to them in your app. Here are some handy patterns for managing page data
in Storybook:
</p>
<ul>
<li>
Use a higher-level connected component. Storybook helps you compose such data from the
"args" of child component stories
</li>
<li>
Assemble data in the page component from your services. You can mock these services out
using Storybook.
</li>
</ul>
<p>
Get a guided tutorial on component-driven development at
<a href="https://storybook.js.org/tutorials/" target="_blank" rel="noopener noreferrer"
>Storybook tutorials</a
>
. Read more in the
<a href="https://storybook.js.org/docs" target="_blank" rel="noopener noreferrer">docs</a>
.
</p>
<div class="tip-wrapper">
<span class="tip">Tip</span>
Adjust the width of the canvas with the
<svg width="10" height="10" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd">
<path
d="M1.5 5.2h4.8c.3 0 .5.2.5.4v5.1c-.1.2-.3.3-.4.3H1.4a.5.5 0 01-.5-.4V5.7c0-.3.2-.5.5-.5zm0-2.1h6.9c.3 0 .5.2.5.4v7a.5.5 0 01-1 0V4H1.5a.5.5 0 010-1zm0-2.1h9c.3 0 .5.2.5.4v9.1a.5.5 0 01-1 0V2H1.5a.5.5 0 010-1zm4.3 5.2H2V10h3.8V6.2z"
id="a"
fill="#999"
/>
</g>
</svg>
Viewports addon in the toolbar
</div>
</section>
</article>
</template>
<script>
import './page.css';
import MyHeader from './Header.vue';
export default {
name: 'my-page',
components: { MyHeader },
data() {
return {
user: null,
};
},
methods: {
onLogin() {
this.user = { name: 'Jane Doe' };
},
onLogout() {
this.user = null;
},
onCreateAccount() {
this.user = { name: 'Jane Doe' };
},
},
};
</script>

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="none" viewBox="0 0 48 48"><title>Accessibility</title><circle cx="24.334" cy="24" r="24" fill="#A849FF" fill-opacity=".3"/><path fill="#A470D5" fill-rule="evenodd" d="M27.8609 11.585C27.8609 9.59506 26.2497 7.99023 24.2519 7.99023C22.254 7.99023 20.6429 9.65925 20.6429 11.585C20.6429 13.575 22.254 15.1799 24.2519 15.1799C26.2497 15.1799 27.8609 13.575 27.8609 11.585ZM21.8922 22.6473C21.8467 23.9096 21.7901 25.4788 21.5897 26.2771C20.9853 29.0462 17.7348 36.3314 17.3325 37.2275C17.1891 37.4923 17.1077 37.7955 17.1077 38.1178C17.1077 39.1519 17.946 39.9902 18.9802 39.9902C19.6587 39.9902 20.253 39.6293 20.5814 39.0889L20.6429 38.9874L24.2841 31.22C24.2841 31.22 27.5529 37.9214 27.9238 38.6591C28.2948 39.3967 28.8709 39.9902 29.7168 39.9902C30.751 39.9902 31.5893 39.1519 31.5893 38.1178C31.5893 37.7951 31.3639 37.2265 31.3639 37.2265C30.9581 36.3258 27.698 29.0452 27.0938 26.2771C26.8975 25.4948 26.847 23.9722 26.8056 22.7236C26.7927 22.333 26.7806 21.9693 26.7653 21.6634C26.7008 21.214 27.0231 20.8289 27.4097 20.7005L35.3366 18.3253C36.3033 18.0685 36.8834 16.9773 36.6256 16.0144C36.3678 15.0515 35.2722 14.4737 34.3055 14.7305C34.3055 14.7305 26.8619 17.1057 24.2841 17.1057C21.7062 17.1057 14.456 14.7947 14.456 14.7947C13.4893 14.5379 12.3937 14.9873 12.0715 15.9502C11.7493 16.9131 12.3293 18.0044 13.3604 18.3253L21.2873 20.7005C21.674 20.8289 21.9318 21.214 21.9318 21.6634C21.9174 21.9493 21.9053 22.2857 21.8922 22.6473Z" clip-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 456 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 829 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="33" height="32" fill="none" viewBox="0 0 33 32"><g clip-path="url(#clip0_10031_177575)"><mask id="mask0_10031_177575" style="mask-type:luminance" width="33" height="25" x="0" y="4" maskUnits="userSpaceOnUse"><path fill="#fff" d="M32.5034 4.00195H0.503906V28.7758H32.5034V4.00195Z"/></mask><g mask="url(#mask0_10031_177575)"><path fill="#5865F2" d="M27.5928 6.20817C25.5533 5.27289 23.3662 4.58382 21.0794 4.18916C21.0378 4.18154 20.9962 4.20057 20.9747 4.23864C20.6935 4.73863 20.3819 5.3909 20.1637 5.90358C17.7042 5.53558 15.2573 5.53558 12.8481 5.90358C12.6299 5.37951 12.307 4.73863 12.0245 4.23864C12.003 4.20184 11.9614 4.18281 11.9198 4.18916C9.63431 4.58255 7.44721 5.27163 5.40641 6.20817C5.38874 6.21578 5.3736 6.22848 5.36355 6.24497C1.21508 12.439 0.078646 18.4809 0.636144 24.4478C0.638667 24.477 0.655064 24.5049 0.677768 24.5227C3.41481 26.5315 6.06609 27.7511 8.66815 28.5594C8.70979 28.5721 8.75392 28.5569 8.78042 28.5226C9.39594 27.6826 9.94461 26.7968 10.4151 25.8653C10.4428 25.8107 10.4163 25.746 10.3596 25.7244C9.48927 25.3945 8.66058 24.9922 7.86343 24.5354C7.80038 24.4986 7.79533 24.4084 7.85333 24.3653C8.02108 24.2397 8.18888 24.109 8.34906 23.977C8.37804 23.9529 8.41842 23.9478 8.45249 23.963C13.6894 26.3526 19.359 26.3526 24.5341 23.963C24.5682 23.9465 24.6086 23.9516 24.6388 23.9757C24.799 24.1077 24.9668 24.2397 25.1358 24.3653C25.1938 24.4084 25.19 24.4986 25.127 24.5354C24.3298 25.0011 23.5011 25.3945 22.6296 25.7232C22.5728 25.7447 22.5476 25.8107 22.5754 25.8653C23.0559 26.7955 23.6046 27.6812 24.2087 28.5213C24.234 28.5569 24.2794 28.5721 24.321 28.5594C26.9357 27.7511 29.5869 26.5315 32.324 24.5227C32.348 24.5049 32.3631 24.4783 32.3656 24.4491C33.0328 17.5506 31.2481 11.5584 27.6344 6.24623C27.6256 6.22848 27.6105 6.21578 27.5928 6.20817ZM11.1971 20.8146C9.62043 20.8146 8.32129 19.3679 8.32129 17.5913C8.32129 15.8146 9.59523 14.368 11.1971 14.368C12.8115 14.368 14.0981 15.8273 14.0729 17.5913C14.0729 19.3679 12.7989 20.8146 11.1971 20.8146ZM21.8299 20.8146C20.2533 20.8146 18.9541 19.3679 18.9541 17.5913C18.9541 15.8146 20.228 14.368 21.8299 14.368C23.4444 14.368 24.7309 15.8273 24.7057 17.5913C24.7057 19.3679 23.4444 20.8146 21.8299 20.8146Z"/></g></g><defs><clipPath id="clip0_10031_177575"><rect width="32" height="32" fill="#fff" transform="translate(0.5)"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="none" viewBox="0 0 32 32"><path fill="#161614" d="M16.0001 0C7.16466 0 0 7.17472 0 16.0256C0 23.1061 4.58452 29.1131 10.9419 31.2322C11.7415 31.3805 12.0351 30.8845 12.0351 30.4613C12.0351 30.0791 12.0202 28.8167 12.0133 27.4776C7.56209 28.447 6.62283 25.5868 6.62283 25.5868C5.89499 23.7345 4.8463 23.2419 4.8463 23.2419C3.39461 22.2473 4.95573 22.2678 4.95573 22.2678C6.56242 22.3808 7.40842 23.9192 7.40842 23.9192C8.83547 26.3691 11.1514 25.6609 12.0645 25.2514C12.2081 24.2156 12.6227 23.5087 13.0803 23.1085C9.52648 22.7032 5.7906 21.3291 5.7906 15.1886C5.7906 13.4389 6.41563 12.0094 7.43916 10.8871C7.27303 10.4834 6.72537 8.85349 7.59415 6.64609C7.59415 6.64609 8.93774 6.21539 11.9953 8.28877C13.2716 7.9337 14.6404 7.75563 16.0001 7.74953C17.3599 7.75563 18.7297 7.9337 20.0084 8.28877C23.0623 6.21539 24.404 6.64609 24.404 6.64609C25.2749 8.85349 24.727 10.4834 24.5608 10.8871C25.5868 12.0094 26.2075 13.4389 26.2075 15.1886C26.2075 21.3437 22.4645 22.699 18.9017 23.0957C19.4756 23.593 19.9869 24.5683 19.9869 26.0634C19.9869 28.2077 19.9684 29.9334 19.9684 30.4613C19.9684 30.8877 20.2564 31.3874 21.0674 31.2301C27.4213 29.1086 32 23.1037 32 16.0256C32 7.17472 24.8364 0 16.0001 0ZM5.99257 22.8288C5.95733 22.9084 5.83227 22.9322 5.71834 22.8776C5.60229 22.8253 5.53711 22.7168 5.57474 22.6369C5.60918 22.5549 5.7345 22.5321 5.85029 22.587C5.9666 22.6393 6.03284 22.7489 5.99257 22.8288ZM6.7796 23.5321C6.70329 23.603 6.55412 23.5701 6.45291 23.4581C6.34825 23.3464 6.32864 23.197 6.40601 23.125C6.4847 23.0542 6.62937 23.0874 6.73429 23.1991C6.83895 23.3121 6.85935 23.4605 6.7796 23.5321ZM7.31953 24.4321C7.2215 24.5003 7.0612 24.4363 6.96211 24.2938C6.86407 24.1513 6.86407 23.9804 6.96422 23.9119C7.06358 23.8435 7.2215 23.905 7.32191 24.0465C7.41968 24.1914 7.41968 24.3623 7.31953 24.4321ZM8.23267 25.4743C8.14497 25.5712 7.95818 25.5452 7.82146 25.413C7.68156 25.2838 7.64261 25.1004 7.73058 25.0035C7.81934 24.9064 8.00719 24.9337 8.14497 25.0648C8.28381 25.1938 8.3262 25.3785 8.23267 25.4743ZM9.41281 25.8262C9.37413 25.9517 9.19423 26.0088 9.013 25.9554C8.83203 25.9005 8.7136 25.7535 8.75016 25.6266C8.78778 25.5003 8.96848 25.4408 9.15104 25.4979C9.33174 25.5526 9.45044 25.6985 9.41281 25.8262ZM10.7559 25.9754C10.7604 26.1076 10.6067 26.2172 10.4165 26.2196C10.2252 26.2238 10.0704 26.1169 10.0683 25.9868C10.0683 25.8534 10.2185 25.7448 10.4098 25.7416C10.6001 25.7379 10.7559 25.8441 10.7559 25.9754ZM12.0753 25.9248C12.0981 26.0537 11.9658 26.1862 11.7769 26.2215C11.5912 26.2554 11.4192 26.1758 11.3957 26.0479C11.3726 25.9157 11.5072 25.7833 11.6927 25.7491C11.8819 25.7162 12.0512 25.7937 12.0753 25.9248Z"/></svg>

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="33" height="32" fill="none" viewBox="0 0 33 32"><g clip-path="url(#clip0_10031_177597)"><path fill="#B7F0EF" fill-rule="evenodd" d="M17 7.87059C17 6.48214 17.9812 5.28722 19.3431 5.01709L29.5249 2.99755C31.3238 2.64076 33 4.01717 33 5.85105V22.1344C33 23.5229 32.0188 24.7178 30.6569 24.9879L20.4751 27.0074C18.6762 27.3642 17 25.9878 17 24.1539L17 7.87059Z" clip-rule="evenodd" opacity=".7"/><path fill="#87E6E5" fill-rule="evenodd" d="M1 5.85245C1 4.01857 2.67623 2.64215 4.47507 2.99895L14.6569 5.01848C16.0188 5.28861 17 6.48354 17 7.87198V24.1553C17 25.9892 15.3238 27.3656 13.5249 27.0088L3.34311 24.9893C1.98119 24.7192 1 23.5242 1 22.1358V5.85245Z" clip-rule="evenodd"/><path fill="#61C1FD" fill-rule="evenodd" d="M15.543 5.71289C15.543 5.71289 16.8157 5.96289 17.4002 6.57653C17.9847 7.19016 18.4521 9.03107 18.4521 9.03107C18.4521 9.03107 18.4521 25.1106 18.4521 26.9629C18.4521 28.8152 19.3775 31.4174 19.3775 31.4174L17.4002 28.8947L16.2575 31.4174C16.2575 31.4174 15.543 29.0765 15.543 27.122C15.543 25.1674 15.543 5.71289 15.543 5.71289Z" clip-rule="evenodd"/></g><defs><clipPath id="clip0_10031_177597"><rect width="32" height="32" fill="#fff" transform="translate(0.5)"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="none" viewBox="0 0 32 32"><path fill="#ED1D24" d="M31.3313 8.44657C30.9633 7.08998 29.8791 6.02172 28.5022 5.65916C26.0067 5.00026 16 5.00026 16 5.00026C16 5.00026 5.99333 5.00026 3.4978 5.65916C2.12102 6.02172 1.03665 7.08998 0.668678 8.44657C0 10.9053 0 16.0353 0 16.0353C0 16.0353 0 21.1652 0.668678 23.6242C1.03665 24.9806 2.12102 26.0489 3.4978 26.4116C5.99333 27.0703 16 27.0703 16 27.0703C16 27.0703 26.0067 27.0703 28.5022 26.4116C29.8791 26.0489 30.9633 24.9806 31.3313 23.6242C32 21.1652 32 16.0353 32 16.0353C32 16.0353 32 10.9053 31.3313 8.44657Z"/><path fill="#fff" d="M12.7266 20.6934L21.0902 16.036L12.7266 11.3781V20.6934Z"/></svg>

After

Width:  |  Height:  |  Size: 716 B

View File

@@ -0,0 +1,30 @@
.storybook-button {
display: inline-block;
cursor: pointer;
border: 0;
border-radius: 3em;
font-weight: 700;
line-height: 1;
font-family: 'Nunito Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.storybook-button--primary {
background-color: #555ab9;
color: white;
}
.storybook-button--secondary {
box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 0px 1px inset;
background-color: transparent;
color: #333;
}
.storybook-button--small {
padding: 10px 16px;
font-size: 12px;
}
.storybook-button--medium {
padding: 11px 20px;
font-size: 14px;
}
.storybook-button--large {
padding: 12px 24px;
font-size: 16px;
}

View File

@@ -0,0 +1,32 @@
.storybook-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
padding: 15px 20px;
font-family: 'Nunito Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.storybook-header svg {
display: inline-block;
vertical-align: top;
}
.storybook-header h1 {
display: inline-block;
vertical-align: top;
margin: 6px 0 6px 10px;
font-weight: 700;
font-size: 20px;
line-height: 1;
}
.storybook-header button + button {
margin-left: 10px;
}
.storybook-header .welcome {
margin-right: 10px;
color: #333;
font-size: 14px;
}

View File

@@ -0,0 +1,68 @@
.storybook-page {
margin: 0 auto;
padding: 48px 20px;
max-width: 600px;
color: #333;
font-size: 14px;
line-height: 24px;
font-family: 'Nunito Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.storybook-page h2 {
display: inline-block;
vertical-align: top;
margin: 0 0 4px;
font-weight: 700;
font-size: 32px;
line-height: 1;
}
.storybook-page p {
margin: 1em 0;
}
.storybook-page a {
color: inherit;
}
.storybook-page ul {
margin: 1em 0;
padding-left: 30px;
}
.storybook-page li {
margin-bottom: 8px;
}
.storybook-page .tip {
display: inline-block;
vertical-align: top;
margin-right: 10px;
border-radius: 1em;
background: #e7fdd8;
padding: 4px 12px;
color: #357a14;
font-weight: 700;
font-size: 11px;
line-height: 12px;
}
.storybook-page .tip-wrapper {
margin-top: 40px;
margin-bottom: 40px;
font-size: 13px;
line-height: 20px;
}
.storybook-page .tip-wrapper svg {
display: inline-block;
vertical-align: top;
margin-top: 3px;
margin-right: 4px;
width: 12px;
height: 12px;
}
.storybook-page .tip-wrapper svg path {
fill: #1ea7fd;
}

View File

@@ -0,0 +1,79 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
.card {
padding: 2em;
}
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
})

View File

@@ -0,0 +1,34 @@
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineWorkspace } from 'vitest/config';
import { storybookTest } from '@storybook/experimental-addon-test/vitest-plugin';
const dirname =
typeof __dirname !== 'undefined'
? __dirname
: path.dirname(fileURLToPath(import.meta.url));
// More info at: https://storybook.js.org/docs/writing-tests/test-addon
export default defineWorkspace([
'vite.config.js',
{
extends: 'vite.config.js',
plugins: [
// The plugin will run tests for the stories defined in your Storybook config
// See options at: https://storybook.js.org/docs/writing-tests/test-addon#storybooktest
storybookTest({ configDir: path.join(dirname, '.storybook') })
],
test: {
name: 'storybook',
browser: {
enabled: true,
headless: true,
name: 'chromium',
provider: 'playwright'
},
setupFiles: ['.storybook/vitest.setup.js']
}
}
]);

View File

@@ -0,0 +1,172 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const {
listTournaments,
getMatches,
getParticipants
} = require('@api/challonge.js'); // Import Challonge API
const {
ActionRowBuilder,
StringSelectMenuBuilder,
EmbedBuilder
} = require('discord.js');
const axios = require('axios');
module.exports = {
data: new SlashCommandBuilder()
.setName('list-matches')
.setDescription('List matches of a given tournament'),
async execute(interaction) {
try {
await interaction.deferReply();
// Fetch the list of tournaments from Challonge API
const tournamentsResponse = await listTournaments();
const tournaments = tournamentsResponse;
if (tournaments.length === 0) {
return interaction.editReply('No tournaments found.');
}
// Create a dropdown menu with tournament names
const options = tournaments.map(tournament => ({
label: tournament.tournament.name,
value: tournament.tournament.id.toString()
}));
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('select-tournament')
.setPlaceholder('Select a tournament')
.addOptions(options)
);
await interaction.editReply({
content: 'Select a tournament to list matches:',
components: [row]
});
// Create a collector to handle the dropdown selection
const filter = i =>
i.customId === 'select-tournament' && i.user.id === interaction.user.id;
const collector = interaction.channel.createMessageComponentCollector({
filter,
time: 60_000
});
collector.on('collect', async i => {
const selectedTournamentId = i.values[0];
await i.deferReply({ ephemeral: false });
// Fetch matches for the selected tournament
const [participantsResponse, matchesResponse] = await Promise.all([
getParticipants(selectedTournamentId).catch(error => {
console.error('Error fetching participants:', error);
i.reply({
content: 'Failed to fetch participants. Please try again later.',
ephemeral: false
});
}),
getMatches(selectedTournamentId).catch(error => {
console.error('Error fetching matches:', error);
i.reply({
content: 'Failed to fetch matches. Please try again later.',
ephemeral: false
});
})
]);
const matches = matchesResponse;
const participants = participantsResponse;
const participantsById = participants.reduce((acc, participant) => {
acc[participant.participant.group_player_ids[0]] =
participant.participant;
return acc;
}, {});
if (matches.length === 0) {
await i.update({
content: 'No matches found for the selected tournament.',
components: []
});
return;
}
// Group matches by match.group_id
const matchesByIdentifier = matches.reduce((acc, match) => {
if (match.match.player1_id !== null) {
const groupId = match.match.group_id;
if (!acc[groupId]) {
acc[groupId] = [];
}
acc[groupId].push(match);
}
return acc;
}, {});
// Create an embed for each unique match.identifier
const embeds = Object.keys(matchesByIdentifier).map(identifier => {
const matchesForIdentifier = matchesByIdentifier[identifier];
const players = [];
const embed = new EmbedBuilder()
.setTitle(`Matches for Group: ${identifier}`)
.setDescription(
matchesForIdentifier
.map(match => {
if (match.match.player1_id !== null) {
players.push(
participantsById?.[match.match.player1_id]?.name ||
'undefined'
);
}
if (match.match.player2_id !== null) {
players.push(
participantsById?.[match.match.player2_id]?.name ||
'undefined'
);
}
return `Match ID: ${match.match.id}\nPlayer 1: ${participantsById?.[match.match.player1_id]?.name || 'undefined'}\nPlayer 2: ${participantsById?.[match.match.player2_id]?.name || 'undefined'}\nRound: ${match.match.round}\nState: ${match.match.state}`;
})
.join('\n\n')
)
.setColor(0x00ae86);
if (players.length > 0) {
embed.addFields({
name: 'Players in this group',
value: players.join(', ')
});
}
return embed;
});
// Send each embed as a separate message
for (const embed of embeds) {
await i.followUp({ embeds: [embed], ephemeral: false });
}
// await i.update({
// content: 'Here are the matches for the selected tournament:',
// components: []
// });
});
collector.on('end', (collected, reason) => {
if (reason === 'time') {
interaction.editReply({
content: 'You did not select a tournament in time.',
components: []
});
}
});
} catch (error) {
console.error(error);
await interaction.editReply(
'An error occurred while fetching tournaments or matches.'
);
}
}
};

View File

@@ -0,0 +1,170 @@
require('module-alias/register'); // Ensure this is at the top
const { SlashCommandBuilder } = require('discord.js');
const { listTournaments, getTournament } = require('@api/challonge.js'); // Import Challonge API
const {
ActionRowBuilder,
StringSelectMenuBuilder,
ComponentType
} = require('discord.js');
// Helper function to fetch and filter tournaments
async function fetchMatchingTournaments(tournamentName) {
const searchWords = tournamentName.toLowerCase().split(/\s+/);
const tournamentsResponse = await listTournaments();
return tournamentsResponse.filter(t =>
searchWords.every(word => t.tournament.name.toLowerCase().includes(word))
);
}
// Helper function to fetch participants for a tournament
async function fetchParticipants(tournamentId) {
const participantsResponse = await getTournament(tournamentId, {
includeParticipants: 1
});
return participantsResponse.tournament.participants;
}
// Helper function to create ranked participants list
function createRankedParticipantsList(participants) {
return participants
.sort((a, b) => {
const rankA = a.participant.final_rank ?? Number.MAX_SAFE_INTEGER;
const rankB = b.participant.final_rank ?? Number.MAX_SAFE_INTEGER;
return rankA - rankB;
})
.map(p => {
const rank = p.participant.final_rank ?? 'Unranked';
return `${participants.indexOf(p) + 1}. ${p.participant.name} - ${
rank !== 'Unranked' ? `** Rank ${rank}**` : rank
}`;
});
}
module.exports = {
data: new SlashCommandBuilder()
.setName('list-participants')
.setDescription('List participants of a specific tournament')
.addStringOption(option =>
option
.setName('tournament')
.setDescription('The name of the tournament')
.setRequired(true)
),
async execute(interaction) {
const tournamentName = interaction.options.getString('tournament');
try {
const matchingTournaments =
await fetchMatchingTournaments(tournamentName);
if (matchingTournaments.length === 0) {
await interaction.reply(
`No tournaments found with the name containing "${tournamentName}".`
);
return;
}
if (matchingTournaments.length > 1) {
const tournamentOptions = matchingTournaments.map((t, index) => ({
label: t.tournament.name,
value: index.toString()
}));
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('select-tournament')
.setPlaceholder('Select a tournament')
.addOptions(tournamentOptions)
);
const message = await interaction.reply({
content: 'Multiple tournaments found. Please select one:',
components: [row],
ephemeral: true
});
const collector = message.createMessageComponentCollector({
componentType: ComponentType.StringSelect,
time: 15_000
});
collector.on('collect', async i => {
if (i.user.id === interaction.user.id) {
const selectedIndex = parseInt(i.values[0], 10);
const selectedTournament =
matchingTournaments[selectedIndex].tournament;
collector.stop(); // Stop the collector after selection
const participants = await fetchParticipants(selectedTournament.id);
if (participants.length === 0) {
await i.update({
content: `No participants found for the tournament "${selectedTournament.name}".`,
components: []
});
return;
}
const rankedParticipants =
createRankedParticipantsList(participants);
const embed = {
color: 0x0099ff,
title: `Participants in "${selectedTournament.name}"`,
description: rankedParticipants.join('\n')
};
await i.update({
embeds: [embed],
components: [],
ephemeral: false
});
} else {
await i.reply({
content: `These options aren't for you!`,
ephemeral: true
});
}
});
collector.on('end', collected => {
if (collected.size === 0) {
interaction.editReply({
content: 'No selection was made. Please try again.',
components: []
});
}
});
return;
}
const tournament = matchingTournaments[0].tournament;
const participants = await fetchParticipants(tournament.id);
if (participants.length === 0) {
await interaction.reply(
`No participants found for the tournament "${tournament.name}".`
);
return;
}
const rankedParticipants = createRankedParticipantsList(participants);
const embed = {
color: 0x0099ff,
title: `Participants in "${tournament.name}"`,
description: rankedParticipants.join('\n')
};
await interaction.reply({ embeds: [embed], ephemeral: true });
} catch (error) {
console.error(error);
await interaction.reply(
'An error occurred while fetching the tournament or participants.'
);
}
}
};

View File

@@ -0,0 +1,48 @@
require('module-alias/register'); // Ensure this is at the top
const { SlashCommandBuilder } = require('discord.js');
const { listTournaments } = require('@api/challonge.js'); // Import Challonge API
const { handleError } = require('@discordUtilities/error-handler.js'); // Import error handler
module.exports = {
data: new SlashCommandBuilder()
.setName('list-tournaments')
.setDescription('Lists all tournaments from Challonge'),
async execute(interaction) {
await interaction.deferReply(); // Defer reply to allow time for API call
try {
// Fetch tournaments from Challonge
listTournaments()
.then(data => {
if (data.length === 0) {
return interaction.editReply('No tournaments found.');
}
// Format tournament list
const tournamentList = data
.map(
t =>
`- **${t.tournament.name}** \n - State: **${t.tournament.state}** (URL: ${t.tournament.full_challonge_url})`
)
.join('\n');
interaction.editReply(
`Here are the current tournaments:\n${tournamentList}`
);
})
.catch(error => {
handleError({
error,
interaction,
errorArea: 'Tournaments - Fetch All Tournaments'
});
});
} catch (error) {
handleError({
error,
interaction,
errorArea: 'Tournaments - List Tournaments'
}); // Handle any unexpected errors
}
}
};

View File

@@ -0,0 +1,480 @@
require('module-alias/register'); // Ensure this is at the top
const { SlashCommandBuilder } = require('@discordjs/builders');
const { InteractionResponseFlags } = require('discord.js');
const {
listTournaments,
getMatches,
getParticipants
} = require('@api/challonge.js');
const {
ActionRowBuilder,
StringSelectMenuBuilder,
EmbedBuilder
} = require('discord.js');
const axios = require('axios');
// --- Utility Functions ---
const EXPECTED_HEADERS = [
'player_id',
'first_name',
'last_name',
'country_code',
'division',
'screenname',
'email',
'tournament_id'
];
/**
* Normalize a screenname for reliable matching.
* Removes non-alphanumeric characters and lowercases.
* @param {string} name
* @returns {string}
*/
const normalizeScreenname = name =>
name?.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
const validateCsvHeaders = headers => {
if (!headers) throw new Error('CSV file is missing headers.');
if (headers.length !== EXPECTED_HEADERS.length) {
throw new Error(
`Invalid CSV file headers: Expected ${EXPECTED_HEADERS.length} headers but found ${headers.length}.`
);
}
const missingHeaders = EXPECTED_HEADERS.filter(h => !headers.includes(h));
if (missingHeaders.length) {
throw new Error(
`Invalid CSV file headers: Missing the following headers: ${missingHeaders.join(', ')}.`
);
}
};
const parseCsv = csvData => {
const rows = csvData
.split('\n')
.map(row => row.split(','))
.filter(row => row.some(cell => cell.trim() !== ''));
const headers = rows[0].map(header => header.trim());
validateCsvHeaders(headers);
for (let i = 1; i < rows.length; i++) {
if (rows[i].length !== EXPECTED_HEADERS.length) {
throw new Error(`Invalid row format at line ${i + 1}.`);
}
}
return rows.slice(1).reduce((acc, row) => {
const participant = {};
EXPECTED_HEADERS.forEach((header, idx) => {
participant[header] = row[idx];
});
acc[participant.screenname] = participant;
return acc;
}, {});
};
const sortRK9ParticipantData = rk9ParticipantData =>
Object.keys(rk9ParticipantData)
.sort((a, b) => {
const isANumeric = /^\d/.test(a);
const isBNumeric = /^\d/.test(b);
if (isANumeric && !isBNumeric) return -1;
if (!isANumeric && isBNumeric) return 1;
return a.localeCompare(b);
})
.reduce((acc, key) => {
acc[key] = rk9ParticipantData[key];
return acc;
}, {});
/**
* Merge RK9 participants with Challonge participants using normalized screennames.
* @param {Object} rk9Participants
* @param {Object} participantsById
* @returns {{participantsById: Object, issues: string[]}}
*/
const mergeRK9Participants = (rk9Participants, participantsById) => {
// Normalize RK9 keys for reliable lookup
const normalizedRK9 = Object.fromEntries(
Object.entries(rk9Participants).map(([key, value]) => [
normalizeScreenname(key),
value
])
);
Object.values(participantsById).forEach(participant => {
const normalized = normalizeScreenname(participant.name);
const rk9Participant = normalizedRK9[normalized];
if (rk9Participant) {
participant.rk9Data = rk9Participant;
participant.printIndex =
Object.keys(normalizedRK9).indexOf(normalized) + 1;
}
});
// Sort participantsById by participant.name
const sorted = Object.keys(participantsById)
.sort((a, b) => {
const nameA = participantsById[a].name.toLowerCase();
const nameB = participantsById[b].name.toLowerCase();
return nameA.localeCompare(nameB);
})
.reduce((acc, key) => {
acc[key] = participantsById[key];
return acc;
}, {});
const issues = Object.values(sorted).reduce((acc, participant) => {
if (!participant.rk9Data) acc.push(participant.name);
return acc;
}, []);
return { participantsById: sorted, issues };
};
const groupMatchesByIdentifier = matches =>
matches.reduce((acc, match) => {
if (match.match.player1_id !== null) {
const groupId = match.match.group_id;
if (!acc[groupId]) acc[groupId] = [];
acc[groupId].push(match);
}
return acc;
}, {});
const createEmbedsForGroups = (matchesByIdentifier, participantsById) =>
Object.keys(matchesByIdentifier).map(identifier => {
const matchesForIdentifier = matchesByIdentifier[identifier];
const players = matchesForIdentifier.reduce((acc, match) => {
if (match.match.player1_id !== null) {
acc.push(
`${participantsById?.[match.match.player1_id]?.printIndex}` ||
'undefined'
);
}
if (match.match.player2_id !== null) {
acc.push(
`${participantsById?.[match.match.player2_id]?.printIndex}` ||
'undefined'
);
}
return acc;
}, []);
const embed = new EmbedBuilder()
.setTitle(`Print string for Group: ${identifier}`)
.setColor(0x00ae86);
if (players.length > 0) {
embed.addFields({
name: 'Print screen pages in order appearing in the bracket',
value: players.join(',')
});
}
return embed;
});
/**
* Handles the case where there are unmatched participants.
* Escapes leading asterisks, chunks the message if too long, and sends the result.
* @param {object} interaction - The Discord interaction or component interaction.
* @param {string[]} issues - List of unmatched participant names.
* @returns {Promise<void>}
*/
async function handleUnmatchedParticipants(interaction, issues) {
// Escape leading asterisks for Discord formatting
const sanitizedIssues = issues.map(issue =>
issue.startsWith('*') ? `\\${issue}` : issue
);
const issueMessage = `The following Challonge participants' usernames have issues and could not be matched with RK9 data:`;
const issueMessageWithList = `${issueMessage}\n${sanitizedIssues.join(', ')}`;
if (issueMessageWithList.length > 2000) {
// Discord message limit: 2000 characters
const chunks = [];
let currentChunk = `${issueMessage}:\n`;
for (const name of sanitizedIssues) {
if ((currentChunk + name + ', ').length > 2000) {
chunks.push(currentChunk.slice(0, -2)); // Remove trailing ', '
currentChunk = '';
}
currentChunk += `${name}, `;
}
if (currentChunk) {
chunks.push(currentChunk.slice(0, -2));
}
for (const chunk of chunks) {
await interaction.followUp({ content: chunk });
}
} else {
await interaction.followUp({
content: issueMessageWithList,
components: []
});
}
}
// --- Main Command ---
module.exports = {
data: new SlashCommandBuilder()
.setName('print-team-sheets')
.setDescription(
'Give a list of players in order of the bracket to copy and print team sheets with'
),
async execute(interaction) {
try {
let rk9ParticipantData = {};
// Prompt the user to upload the RK9 CSV file
await interaction.reply({
content: 'Please upload the RK9 CSV file to proceed.',
components: []
});
// --- CSV File Upload ---
const fileFilter = m =>
m.author.id === interaction.user.id &&
m.attachments.size > 0 &&
m.attachments.first().name.endsWith('.csv');
const fileCollector = await interaction.channel.createMessageCollector({
filter: fileFilter,
max: 1,
time: 60_000
});
fileCollector.on('collect', async message => {
fileCollector.stop();
await interaction.editReply({
content: 'Thank you for sending the file!'
});
const fileUrl = message.attachments.first().url;
let rk9ParticipantData = {};
try {
const response = await axios.get(fileUrl);
rk9ParticipantData = parseCsv(response.data);
await message.delete();
await interaction.editReply({
content: 'CSV file received, validated, and deleted successfully.'
});
} catch (error) {
console.error('Error reading or validating the CSV file:', error);
await interaction.editReply({
content: `The uploaded CSV file is invalid. Error: ${error.message}`
});
return;
}
// --- Tournament Selection ---
let tournaments;
try {
tournaments = await listTournaments();
} catch (error) {
console.error('Error fetching tournaments:', error);
await interaction.editReply({
content: 'Failed to fetch tournaments. Please try again later.',
components: []
});
return;
}
if (!tournaments?.length) {
await interaction.editReply('No tournaments found.');
return;
}
const options = tournaments.map(tournament => ({
label: tournament.tournament.name,
value: tournament.tournament.id.toString()
}));
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('select-tournament')
.setPlaceholder('Select a tournament')
.addOptions(options)
);
await interaction.editReply({
content: 'Select a tournament to list matches:',
components: [row]
});
// --- Tournament Dropdown Collector ---
const filter = i =>
i.customId === 'select-tournament' &&
i.user.id === interaction.user.id;
const collector =
await interaction.channel.createMessageComponentCollector({
filter,
time: 60_000
});
collector.on('collect', async i => {
collector.stop();
const selectedTournamentId = i.values[0];
const selectedTournamentName = options.find(
option => option.value === selectedTournamentId
).label;
await i.deferReply();
// Replace the dropdown with a message indicating the selected tournament
await interaction.editReply({
content: `Tournament "${selectedTournamentName}" selected.`,
components: []
});
// --- Fetch Participants and Matches ---
let participantsResponse, matchesResponse;
try {
[participantsResponse, matchesResponse] = await Promise.all([
getParticipants(selectedTournamentId),
getMatches(selectedTournamentId)
]);
} catch (error) {
console.error('Error fetching participants or matches:', error);
await i.editReply({
content:
'Failed to fetch participants or matches. Please try again later.'
});
return;
}
const matches = matchesResponse ?? [];
const participants = (participantsResponse ?? []).sort((a, b) => {
const nameA = a.participant.name.toLowerCase();
const nameB = b.participant.name.toLowerCase();
return nameA.localeCompare(nameB);
});
participants.forEach((participant, index) => {
participant.participant.collectionIndex = index + 1;
});
const participantsObjById = participants.reduce(
(acc, participant) => {
acc[participant.participant.group_player_ids[0]] =
participant.participant;
return acc;
},
{}
);
const { participantsById, issues } = mergeRK9Participants(
rk9ParticipantData,
participantsObjById
);
if (issues.length > 0) {
await handleUnmatchedParticipants(i, issues);
return;
}
// Group matches by match.group_id
const matchesByIdentifier = matches.reduce((acc, match) => {
if (match.match.player1_id !== null) {
const groupId = match.match.group_id;
if (!acc[groupId]) {
acc[groupId] = [];
}
acc[groupId].push(match);
}
return acc;
}, {});
// Create an embed for each unique match.identifier
const embeds = Object.keys(matchesByIdentifier).map(identifier => {
const matchesForIdentifier = matchesByIdentifier[identifier];
const players = matchesForIdentifier.reduce((acc, match) => {
if (match.match.player1_id !== null) {
acc.push(
participantsById?.[match.match.player1_id]?.printIndex ||
'undefined'
);
}
if (match.match.player2_id !== null) {
acc.push(
participantsById?.[match.match.player2_id]?.printIndex ||
'undefined'
);
}
return acc;
}, []);
const embed = new EmbedBuilder()
.setTitle(`Print string for Group: ${identifier}`)
.setColor(0x00ae86);
if (players.length > 0) {
embed.addFields({
name: 'Print screen pages in order appearing in the bracket',
value: players.join(', ')
});
}
return embed;
});
// Provide a warning about printing in Chrome
await i.followUp({
content:
'⚠️ Warning: Opening the team sheets and printing directly from Chrome has issues where it does not follow the order of the pages we give it so it will print the bracket alphabetically. For best results, download the file and use Acrobat Reader to print.'
});
// Send each embed as a separate message
for (const embed of embeds) {
await i.followUp({ embeds: [embed] });
}
});
collector.on('end', async (collected, reason) => {
if (reason === 'time' && collected.size === 0) {
try {
await interaction.followUp({
content: 'You did not select a tournament in time.',
components: []
});
} catch (err) {
console.error('Failed to send timeout message:', err);
}
}
});
});
fileCollector.on('end', async (collected, reason) => {
if (reason === 'time' && collected.size === 0) {
try {
await interaction.followUp({
content: 'You did not upload the CSV file in time.',
components: []
});
} catch (err) {
console.error('Failed to send timeout message:', err);
}
}
});
} catch (error) {
console.error(error);
if (error.name === 'WarningError' || error.level === 'warning') {
// Log warnings to the console and do not notify the user
console.warn('Warning:', error.message);
return;
}
if (error.level === 'fatal' || error.level === 'error') {
try {
await interaction.followUp({
content:
'A critical error occurred. Please contact an administrator.',
flags: InteractionResponseFlags.Ephemeral
});
} catch (err) {
console.error('Failed to notify user of fatal error:', err);
}
}
}
}
};

View File

@@ -0,0 +1,114 @@
const fs = require('fs');
const path = require('path');
const { SlashCommandBuilder } = require('discord.js');
const { listTournaments } = require('@api/challonge.js'); // Import Challonge API
const { ActionRowBuilder, StringSelectMenuBuilder } = require('discord.js');
const environment = process.env.NODE_ENV || 'development';
const { saveServerData } = require('@discordUtilities/saveServerData');
const { getCachedApiData } = require('@utilities/redis/redisHelpers');
module.exports = {
data: new SlashCommandBuilder()
.setName('set-server-active-tournament')
.setDescription('Set the active tournament for the server'),
async execute(interaction) {
await interaction.deferReply();
try {
const serverDataFilePath = path.join(
__dirname,
`../../store/${environment}-serverData.json`
);
const serverData = JSON.parse(
fs.readFileSync(serverDataFilePath, 'utf8')
);
const userId = interaction.user.id;
const [pendingResponse, inProgressResponse] = await Promise.all([
getCachedApiData(`pendingTournaments_${userId}`, async () => {
return await listTournaments({ state: 'pending' });
}),
getCachedApiData(`inProgressTournaments_${userId}`, async () => {
return await listTournaments({ state: 'in_progress' });
})
]);
const tournaments = [...pendingResponse, ...inProgressResponse];
if (tournaments.length === 0) {
return interaction.editReply('No tournaments found.');
}
// Create a dropdown menu with tournament names
const options = tournaments.map(tournament => ({
label: tournament.tournament.name,
value: tournament.tournament.id.toString()
}));
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('select-tournament')
.setPlaceholder('Select a tournament')
.addOptions(options)
);
await interaction.followUp({
content: 'Select a tournament to list matches:',
components: [row]
});
// Create a collector to handle the dropdown selection
const filter = i =>
i.customId === 'select-tournament' && i.user.id === interaction.user.id;
const collector = interaction.channel.createMessageComponentCollector({
filter,
time: 60_000
});
collector.on('collect', async i => {
collector.stop(); // Stop the collector after one selection
const selectedTournamentId = i.values[0];
const selectedTournamentName = options.find(
option => option.value === selectedTournamentId
).label;
const guildId = interaction.guild.id;
// Update the server data with the selected tournament
serverData[guildId] = serverData[guildId] || {};
serverData[guildId].activeTournamentId = selectedTournamentId;
// Save the updated server data back to the file
saveServerData(serverData);
await i.update({
content: `Tournament "${selectedTournamentName}" set as the active tournament for all future calls.`,
components: []
});
// Fetch a list of all pinned messages in the channel
const pinnedMessages = await interaction.channel.messages.fetchPinned();
// Unpin any messages that contain the specified text
for (const message of pinnedMessages.values()) {
if (
message.content.includes(
'set as the active tournament for all future calls'
)
) {
await message.unpin();
}
}
// Pin the updated message
const updatedMessage = await i.fetchReply();
await updatedMessage.pin();
});
} catch (error) {
console.error(error);
await interaction.reply({
content: 'There was an error setting the active tournament.',
ephemeral: true
});
}
}
};

View File

@@ -0,0 +1,58 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const { CommandInteraction } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('create-tournament')
.setDescription('Create a new tournament')
.addStringOption(option =>
option
.setName('tournament_name')
.setDescription('The name of the tournament')
.setRequired(true)
)
.addStringOption(option =>
option
.setName('sanction_id')
.setDescription('The sanction ID for the tournament')
.setRequired(true)
)
.addStringOption(option =>
option
.setName('challonge_key')
.setDescription('The Challonge API key')
.setRequired(true)
)
.addStringOption(option =>
option
.setName('start_date_time')
.setDescription(
'The start date and time of the tournament (YYYY-MM-DD HH:mm)'
)
.setRequired(true)
)
.addStringOption(option =>
option
.setName('end_date_time')
.setDescription(
'The end date and time of the tournament (YYYY-MM-DD HH:mm)'
)
.setRequired(true)
),
async execute(interaction) {
const tournamentName = interaction.options.getString('tournament_name');
const sanctionId = interaction.options.getString('sanction_id');
const challongeKey = interaction.options.getString('challonge_key');
const startDateTime = interaction.options.getString('start_date_time');
const endDateTime = interaction.options.getString('end_date_time');
// Validate date formats and other inputs here
// Logic to create the tournament using the provided details
await interaction.reply(
`Tournament "${tournamentName}" created successfully!`
);
}
};

View File

@@ -0,0 +1,185 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const {
ActionRowBuilder,
ButtonStyle,
ButtonBuilder,
EmbedBuilder,
ModalBuilder,
TextInputBuilder,
TextInputStyle
} = require('discord.js');
const dataStore = require('../../store/datastore');
module.exports = {
data: new SlashCommandBuilder()
.setName('tournament-setup')
.setDescription('Setup a regional tournament'),
async execute(interaction) {
const embed = new EmbedBuilder()
.setTitle('Tournament Setup')
.addFields(
{ name: 'Tournament Name', value: 'Not Set', inline: false },
{ name: 'Tournament Sanctioning ID', value: 'Not Set', inline: false },
{ name: 'Challonge Link', value: 'Not Set', inline: false },
{ name: 'Start Date', value: 'Not Set', inline: true },
{ name: 'End Date', value: 'Not Set', inline: true }
)
.toJSON(); // Ensure fields are properly initialized
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('setTournamentName')
.setLabel('Set Tournament Name')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('setSanctioningId')
.setLabel('Set Sanctioning ID')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('setChallongeLink')
.setLabel('Set Challonge Link')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('setStartDate')
.setLabel('Set Start Date')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('setEndDate')
.setLabel('Set End Date')
.setStyle(ButtonStyle.Primary)
);
await interaction.reply({ embeds: [embed], components: [row] });
const filter = i =>
i.customId.startsWith('set') && i.user.id === interaction.user.id;
const collector = interaction.channel.createMessageComponentCollector({
filter,
time: 60000
});
collector.on('collect', async i => {
switch (i.customId) {
case 'setTournamentName': {
const modal = new ModalBuilder()
.setCustomId('tournamentNameModal')
.setTitle('Set Tournament Name')
.addComponents(
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('tournamentNameInput')
.setLabel('Tournament Name')
.setStyle(TextInputStyle.Short)
)
);
await i.showModal(modal);
const modalSubmit = await i.awaitModalSubmit({ time: 60000 });
const tournamentName = modalSubmit.fields.getTextInputValue(
'tournamentNameInput'
);
dataStore.tournamentName = tournamentName;
embed.fields[0].value = tournamentName;
await modalSubmit.update({ embeds: [embed] });
break;
}
case 'setSanctioningId': {
const modal = new ModalBuilder()
.setCustomId('sanctioningIdModal')
.setTitle('Set Sanctioning ID')
.addComponents(
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('sanctioningIdInput')
.setLabel('Tournament Sanctioning ID')
.setStyle(TextInputStyle.Short)
)
);
await i.showModal(modal);
const modalSubmit = await i.awaitModalSubmit({ time: 60000 });
const sanctioningId =
modalSubmit.fields.getTextInputValue('sanctioningIdInput');
dataStore.sanctioningId = sanctioningId;
embed.fields[1].value = sanctioningId;
await modalSubmit.update({ embeds: [embed] });
break;
}
case 'setChallongeLink': {
const modal = new ModalBuilder()
.setCustomId('challongeLinkModal')
.setTitle('Set Challonge Link')
.addComponents(
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('challongeLinkInput')
.setLabel('Challonge Link')
.setStyle(TextInputStyle.Short)
)
);
await i.showModal(modal);
const modalSubmit = await i.awaitModalSubmit({ time: 60000 });
const challongeLink =
modalSubmit.fields.getTextInputValue('challongeLinkInput');
dataStore.challongeLink = challongeLink;
embed.fields[2].value = challongeLink;
await modalSubmit.update({ embeds: [embed] });
break;
}
case 'setStartDate': {
const modal = new ModalBuilder()
.setCustomId('datesModal')
.setTitle('Set Dates')
.addComponents(
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('startDateInput')
.setLabel('Start Date')
.setStyle(TextInputStyle.Short)
.setPlaceholder('YYYY-MM-DD')
)
);
await i.showModal(modal);
const modalSubmit = await i.awaitModalSubmit({ time: 60000 });
const startDate =
modalSubmit.fields.getTextInputValue('startDateInput');
const endDate = modalSubmit.fields.getTextInputValue('endDateInput');
dataStore.startDate = startDate;
dataStore.endDate = endDate;
embed.fields[3].value = startDate;
embed.fields[4].value = endDate;
await modalSubmit.update({ embeds: [embed] });
break;
}
case 'setEndDate': {
const modal = new ModalBuilder()
.setCustomId('datesModal')
.setTitle('Set Dates')
.addComponents(
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('endDateInput')
.setLabel('End Date')
.setStyle(TextInputStyle.Short)
.setPlaceholder('YYYY-MM-DD')
)
);
await i.showModal(modal);
const modalSubmit = await i.awaitModalSubmit({ time: 60000 });
const startDate =
modalSubmit.fields.getTextInputValue('startDateInput');
const endDate = modalSubmit.fields.getTextInputValue('endDateInput');
dataStore.startDate = startDate;
dataStore.endDate = endDate;
embed.fields[3].value = startDate;
embed.fields[4].value = endDate;
await modalSubmit.update({ embeds: [embed] });
break;
}
}
});
}
};

View File

@@ -0,0 +1,53 @@
require('module-alias/register'); // Ensure this is at the top
const { SlashCommandBuilder } = require('@discordjs/builders');
const { CommandInteraction } = require('discord.js');
const { handleError } = require('@discordUtilities/error-handler.js'); // Import error handler
module.exports = {
data: new SlashCommandBuilder()
.setName('clear-chat')
.setDescription('Clears all messages in the channel'),
/**
* @param {CommandInteraction} interaction
*/
async execute(interaction) {
// Defer the reply if the command execution might take longer than 3 seconds
await interaction.deferReply({ ephemeral: false });
if (!interaction.member.permissions.has('MANAGE_MESSAGES')) {
return interaction.editReply({
content: 'You do not have permission to use this command.',
ephemeral: true
});
}
const channel = interaction.channel;
try {
const fetched = await channel.messages.fetch({ limit: 1 });
if (fetched.size === 0) {
return interaction.followUp({
content: 'All good here, no messages to clear!',
ephemeral: true
});
}
let batch;
while (true) {
batch = await channel.messages.fetch({ limit: 100 });
if (batch.size > 0) {
await channel.bulkDelete(batch);
}
if (batch.size < 100) break;
}
} catch (error) {
handleError({
error,
interaction,
customMessage: 'There was an error trying to clear the channel.',
errorArea: 'Command Utilities - deleteChat.js'
}); // Handle any unexpected errors
}
}
};

View File

@@ -0,0 +1,96 @@
import { CommandInteraction } from '../../../../__mocks__/discord.js';
import deleteChat from './deleteChat.js';
describe('deleteChat command', () => {
let interaction;
beforeEach(() => {
interaction = {
deferReply: jest.fn().mockResolvedValue(),
editReply: jest.fn().mockResolvedValue(),
followUp: jest.fn().mockResolvedValue(),
member: {
permissions: {
has: jest.fn()
}
},
channel: {
messages: {
fetch: jest.fn()
},
bulkDelete: jest.fn().mockResolvedValue()
}
};
});
test('should defer reply', async () => {
interaction.member.permissions.has.mockReturnValue(true);
interaction.channel.messages.fetch.mockResolvedValue({ size: 1 });
await deleteChat.execute(interaction);
expect(interaction.deferReply).toHaveBeenCalledWith({ ephemeral: false });
});
test('should deny access if user lacks MANAGE_MESSAGES permission', async () => {
interaction.member.permissions.has.mockReturnValue(false);
await deleteChat.execute(interaction);
expect(interaction.editReply).toHaveBeenCalledWith({
content: 'You do not have permission to use this command.',
ephemeral: true
});
});
test('should notify if there are no messages to clear', async () => {
interaction.member.permissions.has.mockReturnValue(true);
interaction.channel.messages.fetch.mockResolvedValue({ size: 0 });
await deleteChat.execute(interaction);
expect(interaction.followUp).toHaveBeenCalledWith({
content: 'All good here, no messages to clear!',
ephemeral: true
});
});
test('should clear messages in batches', async () => {
interaction.member.permissions.has.mockReturnValue(true);
const messagesBatch1 = Array.from({ length: 100 }, (_, i) => ({
id: `messageId${i}`
}));
const messagesBatch2 = Array.from({ length: 50 }, (_, i) => ({
id: `messageId${i + 100}`
}));
interaction.channel.messages.fetch
.mockResolvedValueOnce({
size: 100,
...messagesBatch1
})
.mockResolvedValueOnce({
size: 50,
...messagesBatch2
});
await deleteChat.execute(interaction);
expect(interaction.channel.messages.fetch).toHaveBeenCalledTimes(1);
expect(interaction.channel.bulkDelete).toHaveBeenCalledTimes(2);
});
test('should handle errors gracefully', async () => {
interaction.member.permissions.has.mockReturnValue(true);
interaction.channel.messages.fetch.mockRejectedValue(
new Error('Fetch error')
);
await deleteChat.execute(interaction);
expect(interaction.followUp).toHaveBeenCalledWith({
content: 'There was an error trying to clear the channel.',
ephemeral: true
});
});
});

View File

@@ -0,0 +1,57 @@
require('module-alias/register'); // Ensure this is at the top
const { SlashCommandBuilder } = require('@discordjs/builders');
const { handleError } = require('@discordUtilities/error-handler.js'); // Import error handler
module.exports = {
data: new SlashCommandBuilder()
.setName('delete-messages')
.setDescription('Deletes a specified number of messages.')
.addIntegerOption(option =>
option
.setName('number')
.setDescription('Number of messages to delete')
.setRequired(true)
),
async execute(interaction) {
// Defer the reply if the command execution might take longer than 3 seconds
await interaction.deferReply({ ephemeral: false });
const number = interaction.options.getInteger('number') || null;
if (number <= 0) {
return interaction.reply('Please provide a positive number.');
}
const channel = interaction.channel;
const messages =
number > channel.messages.cache.size
? await channel.messages.fetch()
: await channel.messages.fetch({ limit: number + 1 });
const filteredMessages = messages.filter(
message =>
Date.now() - message.createdTimestamp < 14 * 24 * 60 * 60 * 1000
);
if (filteredMessages.size === 0) {
return interaction.editReply({
content: 'No messages to delete (all are older than 14 days).',
ephemeral: true
});
}
channel
.bulkDelete(filteredMessages)
.then(() =>
interaction.editReply({ content: 'Messages deleted.', ephemeral: true })
)
.catch(error => {
handleError({
error,
interaction,
customMessage: 'Failed to delete messages',
errorArea: 'Command Utilities - deleteMessages.js'
}); // Handle any unexpected errors
});
}
};

View File

@@ -0,0 +1,101 @@
import { SlashCommandBuilder } from '@discordjs/builders';
import deleteMessages from './deleteMessages.js';
describe('deleteMessages Command', () => {
let interaction;
beforeEach(() => {
interaction = {
deferReply: jest.fn().mockResolvedValue(),
editReply: jest.fn().mockResolvedValue(),
reply: jest.fn().mockResolvedValue(),
options: {
getString: jest.fn()
},
channel: {
messages: {
cache: {
size: 10
},
fetch: jest.fn()
},
bulkDelete: jest.fn()
}
};
});
it('should defer the reply', async () => {
interaction.options.getString.mockReturnValue('5');
interaction.channel.messages.fetch.mockResolvedValue(new Map());
await deleteMessages.execute(interaction);
expect(interaction.deferReply).toHaveBeenCalledWith({ ephemeral: false });
});
it('should reply with an error if the number is less than or equal to 0', async () => {
interaction.options.getString.mockReturnValue('0');
await deleteMessages.execute(interaction);
expect(interaction.reply).toHaveBeenCalledWith(
'Please provide a positive number.'
);
});
it('should fetch all messages if the number exceeds the cache size', async () => {
interaction.options.getString.mockReturnValue('15');
interaction.channel.messages.fetch.mockResolvedValue(new Map());
await deleteMessages.execute(interaction);
expect(interaction.channel.messages.fetch).toHaveBeenCalled();
});
it('should fetch a limited number of messages if the number is within the cache size', async () => {
interaction.options.getString.mockReturnValue('5');
interaction.channel.messages.fetch.mockResolvedValue(new Map());
await deleteMessages.execute(interaction);
expect(interaction.channel.messages.fetch).toHaveBeenCalledWith({
limit: 6
});
});
it('should call bulkDelete with the fetched messages', async () => {
const messages = new Map();
interaction.options.getString.mockReturnValue('5');
interaction.channel.messages.fetch.mockResolvedValue(messages);
await deleteMessages.execute(interaction);
expect(interaction.channel.bulkDelete).toHaveBeenCalledWith(messages);
});
it('should handle errors during bulkDelete', async () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
interaction.options.getString.mockReturnValue('5');
interaction.channel.messages.fetch.mockResolvedValue(new Map());
interaction.channel.bulkDelete.mockRejectedValue(new Error('Test Error'));
await deleteMessages.execute(interaction);
expect(consoleSpy).toHaveBeenCalledWith(
'Failed to delete messages: Error: Test Error'
);
consoleSpy.mockRestore();
});
it('should edit the reply after successful deletion', async () => {
interaction.options.getString.mockReturnValue('5');
interaction.channel.messages.fetch.mockResolvedValue(new Map());
await deleteMessages.execute(interaction);
expect(interaction.editReply).toHaveBeenCalledWith({
content: 'Messages deleted.',
ephemeral: true
});
});
});

View File

@@ -0,0 +1,62 @@
require('module-alias/register'); // Ensure this is at the top
const { SlashCommandBuilder } = require('@discordjs/builders');
const { exec } = require('child_process');
const path = require('path');
const { PermissionsBitField } = require('discord.js');
const { handleError } = require('@discordUtilities/error-handler.js'); // Import error handler
const ALLOWED_ROLES = ['1260647293422403614']; // Replace with the actual role IDs
module.exports = {
data: new SlashCommandBuilder()
.setName('deploy-commands')
.setDescription('Deploys the application commands'),
async execute(interaction) {
// Defer the reply if the command execution might take longer than 3 seconds
await interaction.deferReply({ ephemeral: false });
const OWNER_ID = '203292966670958592';
const userId = interaction.user.id;
const member = interaction.guild.members.cache.get(userId);
// Check if the user is the owner
if (userId !== OWNER_ID) {
return interaction.editReply(
'You do not have permission to use this command.'
);
}
const scriptPath = path.resolve(
__dirname,
'../../utilities/deploy-commands.js'
);
exec(`node "${scriptPath}"`, (error, stdout, stderr) => {
if (error) {
handleError({
error,
interaction,
customMessage:
'Error executing script: There was an error deploying the commands.',
errorArea: 'Command Utilities - deploy-commands.js'
}); // Handle any unexpected errors
}
if (stderr) {
handleError({
error: stderr,
interaction,
customMessage:
'Script stderr: There was an error deploying the commands.',
errorArea: 'Command Utilities - deploy-commands.js'
}); // Handle any unexpected errors
}
interaction.editReply({
content: 'Commands deployed successfully.',
ephemeral: true
});
});
}
};

View File

@@ -0,0 +1,90 @@
import { exec } from 'child_process';
import { resolve } from 'path';
import deployCommands from './deployCommands';
jest.mock('child_process', () => ({
exec: jest.fn()
}));
jest.mock('path', () => ({
resolve: jest.fn()
}));
describe('deployCommands', () => {
const mockInteraction = {
deferReply: jest.fn(),
editReply: jest.fn(),
user: { id: '203292966670958592' },
guild: {
members: {
cache: {
get: jest.fn()
}
}
}
};
beforeEach(() => {
jest.clearAllMocks();
});
it('should defer the reply', async () => {
await deployCommands.execute(mockInteraction);
expect(mockInteraction.deferReply).toHaveBeenCalledWith({
ephemeral: false
});
});
it('should deny access if the user is not the owner', async () => {
mockInteraction.user.id = '123456789';
await deployCommands.execute(mockInteraction);
expect(mockInteraction.editReply).toHaveBeenCalledWith(
'You do not have permission to use this command.'
);
});
it('should execute the deploy script if the user is the owner', async () => {
mockInteraction.user.id = '203292966670958592';
resolve.mockReturnValue('/mock/path/to/deploy-commands.js');
exec.mockImplementation((cmd, callback) => callback(null, 'Success', ''));
await deployCommands.execute(mockInteraction);
expect(exec).toHaveBeenCalledWith(
'node "/mock/path/to/deploy-commands.js"',
expect.any(Function)
);
expect(mockInteraction.editReply).toHaveBeenCalledWith({
content: 'Commands deployed successfully.',
ephemeral: true
});
});
it('should handle script execution errors', async () => {
mockInteraction.user.id = '203292966670958592';
resolve.mockReturnValue('/mock/path/to/deploy-commands.js');
exec.mockImplementation((cmd, callback) =>
callback(new Error('Script error'), '', '')
);
await deployCommands.execute(mockInteraction);
expect(mockInteraction.editReply).toHaveBeenCalledWith(
'There was an error deploying the commands.'
);
});
it('should handle script stderr output', async () => {
mockInteraction.user.id = '203292966670958592';
resolve.mockReturnValue('/mock/path/to/deploy-commands.js');
exec.mockImplementation((cmd, callback) =>
callback(null, '', 'Some stderr output')
);
await deployCommands.execute(mockInteraction);
expect(mockInteraction.editReply).toHaveBeenCalledWith(
'There was an error deploying the commands.'
);
});
});

View File

@@ -0,0 +1,146 @@
require('module-alias/register'); // Ensure this is at the top
const fs = require('fs');
const path = require('path');
const { ActionRowBuilder, ButtonBuilder } = require('@discordjs/builders');
const { handleError } = require('@discordUtilities/error-handler.js'); // Import error handler
module.exports = {
data: {
name: 'roles',
description: 'Manage roles'
},
async execute(interaction) {
// Defer the reply if the command execution might take longer than 3 seconds
if (!interaction.deferred && !interaction.replied) {
await interaction.deferReply({ ephemeral: false });
}
const referencesFolder = path.join(__dirname, '../../references');
// Check if the directory exists
if (!fs.existsSync(referencesFolder)) {
await interaction.reply({
content: 'The references directory does not exist.',
ephemeral: true
});
return;
}
let files = [];
// Read the directory
try {
files = fs.readdirSync(referencesFolder);
const row = new ActionRowBuilder();
files
.filter(file => file.endsWith('.txt'))
.forEach(file => {
const fileName = file.replace('.txt', '');
const buttonLabel = fileName
.replace(/-/g, ' ')
.replace(/\b\w/g, c => c.toUpperCase());
const button = new ButtonBuilder()
.setCustomId(fileName)
.setLabel(buttonLabel)
.setStyle('Primary');
row.addComponents(button);
});
await interaction.editReply({
content: 'What role do you want to know more about:',
components: [row]
});
const filter = i => i.customId && i.user.id === interaction.user.id;
const collector = interaction.channel.createMessageComponentCollector({
filter,
time: 15000
});
collector.on('collect', async i => {
if (i.customId) {
const filePath = path.join(referencesFolder, `${i.customId}.txt`);
try {
const fileContent = fs.readFileSync(filePath, 'utf8');
const titleMatch = fileContent.match(/^##\s*(.+)$/m);
const title = titleMatch
? titleMatch[1]
: `Content of ${i.customId}`;
const descriptionMatch = fileContent.match(/(\*\*.+)$/s);
const description = descriptionMatch
? descriptionMatch[1].trim()
: 'No description available.';
const embeds = [];
let remainingDescription = description;
while (remainingDescription.length > 2000) {
let splitIndex = remainingDescription.lastIndexOf('- **', 2000);
if (splitIndex === -1) {
splitIndex = 2000;
}
const embed = {
color: 0x0099ff,
title: title,
description: remainingDescription.substring(0, splitIndex),
timestamp: new Date(),
footer: {
text: 'Role Information'
}
};
embeds.push(embed);
remainingDescription = remainingDescription.substring(splitIndex);
}
const finalEmbed = {
color: 0x0099ff,
title: title,
description: remainingDescription,
timestamp: new Date(),
footer: {
text: 'Role Information'
}
};
embeds.push(finalEmbed);
await i.reply({
embeds: embeds,
ephemeral: true
});
} catch (error) {
handleError({
error,
interaction: i,
customMessage: `There was an error reading the file: ${i.customId}`,
errorArea: 'Command Utilities - roles.js'
}); // Handle any unexpected errors
}
}
});
collector.on('end', collected => {
if (collected.size === 0) {
interaction.followUp({
content: 'You did not click any button in time.',
ephemeral: true
});
}
});
} catch (error) {
handleError({
error,
interaction: i,
customMessage: `There was an error while processing the files.`,
errorArea: 'Command Utilities - roles.js'
}); // Handle any unexpected errors
}
}
};

View File

@@ -0,0 +1,128 @@
import fs from 'fs';
import path from 'path';
import { ActionRowBuilder, ButtonBuilder } from '@discordjs/builders';
import rolesCommand from './roles.js';
describe('roles.js', () => {
let interaction;
beforeEach(() => {
interaction = {
deferReply: jest.fn().mockResolvedValue(),
reply: jest.fn().mockResolvedValue(),
editReply: jest.fn().mockResolvedValue(),
followUp: jest.fn().mockResolvedValue(),
user: { id: '12345' },
channel: {
createMessageComponentCollector: jest.fn()
}
};
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
jest.spyOn(fs, 'readdirSync').mockReturnValue([]);
jest.spyOn(fs, 'readFileSync').mockReturnValue('');
});
afterEach(() => {
jest.restoreAllMocks();
});
it('should defer the reply', async () => {
await rolesCommand.execute(interaction);
expect(interaction.deferReply).toHaveBeenCalledWith({ ephemeral: false });
});
it('should reply if the references directory does not exist', async () => {
fs.existsSync.mockReturnValue(false);
await rolesCommand.execute(interaction);
expect(interaction.reply).toHaveBeenCalledWith({
content: 'The references directory does not exist.',
ephemeral: true
});
});
it('should edit the reply with buttons for each .txt file', async () => {
fs.readdirSync.mockReturnValue(['role1.txt', 'role2.txt']);
await rolesCommand.execute(interaction);
expect(interaction.editReply).toHaveBeenCalledWith({
content: 'What role do you want to know more about:',
components: expect.any(Array)
});
});
it('should handle file reading errors gracefully', async () => {
fs.readdirSync.mockReturnValue(['role1.txt']);
fs.readFileSync.mockImplementation(() => {
throw new Error('File read error');
});
const mockCollector = {
on: jest.fn((event, callback) => {
if (event === 'collect') {
callback({ customId: 'role1', reply: jest.fn() });
}
})
};
interaction.channel.createMessageComponentCollector.mockReturnValue(
mockCollector
);
await rolesCommand.execute(interaction);
expect(mockCollector.on).toHaveBeenCalledWith(
'collect',
expect.any(Function)
);
});
it('should send embeds with role information when a button is clicked', async () => {
fs.readdirSync.mockReturnValue(['role1.txt']);
fs.readFileSync.mockReturnValue('## Role Title\n**Description**');
const mockReply = jest.fn();
const mockCollector = {
on: jest.fn((event, callback) => {
if (event === 'collect') {
callback({ customId: 'role1', reply: mockReply });
}
})
};
interaction.channel.createMessageComponentCollector.mockReturnValue(
mockCollector
);
await rolesCommand.execute(interaction);
expect(mockReply).toHaveBeenCalledWith({
embeds: expect.any(Array),
ephemeral: true
});
});
it('should follow up if no button is clicked in time', async () => {
const mockCollector = {
on: jest.fn((event, callback) => {
if (event === 'end') {
callback([]);
}
})
};
interaction.channel.createMessageComponentCollector.mockReturnValue(
mockCollector
);
await rolesCommand.execute(interaction);
expect(interaction.followUp).toHaveBeenCalledWith({
content: 'You did not click any button in time.',
ephemeral: true
});
});
});

View File

@@ -0,0 +1,9 @@
const { Events } = require('discord.js');
module.exports = {
name: Events.ClientReady,
once: true,
execute(client) {
console.log(`Ready! Logged in as ${client.user.tag}`);
}
};

View File

@@ -0,0 +1,33 @@
import { Events } from 'discord.js';
import clientReady from './clientReady.js';
// Ensure Jest globals are available
import 'jest';
describe('clientReady Event', () => {
let mockClient;
beforeEach(() => {
mockClient = {
user: {
tag: 'TestBot#1234'
}
};
jest.spyOn(console, 'log').mockImplementation(() => {});
});
afterEach(() => {
jest.restoreAllMocks();
});
test('should have the correct name and once properties', () => {
expect(clientReady.name).toBe(Events.ClientReady);
expect(clientReady.once).toBe(true);
});
test('should log the correct message when executed', () => {
clientReady.execute(mockClient);
expect(console.log).toHaveBeenCalledWith(
'Ready! Logged in as TestBot#1234'
);
});
});

View File

@@ -0,0 +1,17 @@
require('module-alias/register'); // Ensure this is at the top
const { Events } = require('discord.js');
const { saveServerData } = require('@discordUtilities/saveServerData');
module.exports = {
name: Events.GuildCreate,
execute(guild, serverData) {
if (!serverData[guild.id]) {
serverData[guild.id] = {
messageCount: 0
};
saveServerData(serverData);
}
console.log(`Joined new guild: ${guild.name}`);
}
};

View File

@@ -0,0 +1,47 @@
import { Events } from 'discord.js';
import guildCreate from './guildCreate.js';
import { saveServerData } from '../utilities/saveServerData.js';
jest.mock('../utilities/saveServerData', () => ({
saveServerData: jest.fn()
}));
describe('guildCreate Event Handler', () => {
let mockGuild;
let mockServerData;
beforeEach(() => {
mockGuild = {
id: '123456789',
name: 'Test Guild'
};
mockServerData = {};
jest.clearAllMocks();
});
test('should add new guild to serverData if it does not exist', () => {
guildCreate.execute(mockGuild, mockServerData);
expect(mockServerData[mockGuild.id]).toEqual({ messageCount: 0 });
expect(saveServerData).toHaveBeenCalledWith(mockServerData);
});
test('should not overwrite existing guild data in serverData', () => {
mockServerData[mockGuild.id] = { messageCount: 42 };
guildCreate.execute(mockGuild, mockServerData);
expect(mockServerData[mockGuild.id]).toEqual({ messageCount: 42 });
expect(saveServerData).not.toHaveBeenCalled();
});
test('should log the name of the joined guild', () => {
console.log = jest.fn();
guildCreate.execute(mockGuild, mockServerData);
expect(console.log).toHaveBeenCalledWith(
`Joined new guild: ${mockGuild.name}`
);
});
});

View File

@@ -0,0 +1,96 @@
require('module-alias/register'); // Ensure this is at the top
const fs = require('fs');
const path = require('path');
const { Events, Client, GatewayIntentBits, Collection } = require('discord.js');
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages]
});
const { handleError } = require('@discordUtilities/error-handler.js'); // Import error handler
client.commands = new Collection();
const commandFiles = getCommandFiles('src/discord/commands');
function getCommandFiles(directory) {
const files = fs.readdirSync(directory);
let commandFiles = [];
for (const file of files) {
const filePath = path.join(directory, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
commandFiles = commandFiles.concat(getCommandFiles(filePath));
} else if (file.endsWith('.js') && !file.endsWith('.spec.js')) {
commandFiles.push(filePath);
}
}
return commandFiles;
}
for (const file of commandFiles) {
const commandModule = require(path.resolve(file));
if (Array.isArray(commandModule)) {
for (const command of commandModule) {
if (command.data && command.data.name) {
client.commands.set(command.data.name, command);
} else {
handleError({
customMessage: `Command in array at ${file} is missing a 'data' property or 'data.name'`,
updateInteraction: false,
sendToUser: false,
errorArea: 'Events - interactionCreate.js'
}); // Handle any unexpected errors
}
}
} else {
if (commandModule.data && commandModule.data.name) {
client.commands.set(commandModule.data.name, commandModule);
} else {
handleError({
customMessage: `Command at ${file} is missing a 'data' property or 'data.name'`,
updateInteraction: false,
sendToUser: false,
errorArea: 'Events - interactionCreate.js'
}); // Handle any unexpected errors
}
}
}
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
// Check if the interaction is from an excluded guild
// 1168200542405808178 = Go Prof Chat
const excludedGuilds = ['1168200542405808178']; // Add guild IDs to exclude
if (interaction.guild && excludedGuilds.includes(interaction.guild.id)) {
console.log(
`Ignored interaction from excluded guild: ${interaction.guild.id}`
);
return; // Ignore interactions from excluded guilds
}
if (!interaction.isCommand()) {
return;
}
const command = client.commands.get(interaction.commandName);
if (!command) {
return;
}
try {
await command.execute(interaction);
} catch (error) {
handleError({
error,
interaction,
updateInteraction: false,
errorArea: 'Events - interactionCreate.js'
}); // Handle any unexpected errors
}
}
};

View File

@@ -0,0 +1,90 @@
import { Events } from 'discord.js';
import interactionCreate from './interactionCreate.js';
describe('interactionCreate Event', () => {
let mockInteraction;
let mockCommand;
beforeEach(() => {
mockInteraction = {
isCommand: jest.fn(),
commandName: '',
replied: false,
deferred: false,
reply: jest.fn(),
editReply: jest.fn()
};
mockCommand = {
execute: jest.fn()
};
interactionCreate.client = {
commands: new Map()
};
});
it('should do nothing if interaction is not a command', async () => {
mockInteraction.isCommand.mockReturnValue(false);
await interactionCreate.execute(mockInteraction);
expect(mockInteraction.isCommand).toHaveBeenCalled();
expect(mockInteraction.reply).not.toHaveBeenCalled();
expect(mockInteraction.editReply).not.toHaveBeenCalled();
});
it('should do nothing if command is not found', async () => {
mockInteraction.isCommand.mockReturnValue(true);
mockInteraction.commandName = 'nonexistentCommand';
await interactionCreate.execute(mockInteraction);
expect(mockInteraction.isCommand).toHaveBeenCalled();
expect(mockInteraction.reply).not.toHaveBeenCalled();
expect(mockInteraction.editReply).not.toHaveBeenCalled();
});
it('should execute the command if it exists', async () => {
mockInteraction.isCommand.mockReturnValue(true);
mockInteraction.commandName = 'testCommand';
interactionCreate.client.commands.set('testCommand', mockCommand);
await interactionCreate.execute(mockInteraction);
expect(mockInteraction.isCommand).toHaveBeenCalled();
expect(mockCommand.execute).toHaveBeenCalledWith(mockInteraction);
});
it('should reply with an error if command execution fails', async () => {
mockInteraction.isCommand.mockReturnValue(true);
mockInteraction.commandName = 'testCommand';
interactionCreate.client.commands.set('testCommand', mockCommand);
mockCommand.execute.mockRejectedValue(new Error('Command failed'));
await interactionCreate.execute(mockInteraction);
expect(mockInteraction.isCommand).toHaveBeenCalled();
expect(mockCommand.execute).toHaveBeenCalledWith(mockInteraction);
expect(mockInteraction.reply).toHaveBeenCalledWith({
content: 'There was an error while executing this command!',
ephemeral: true
});
});
it('should edit reply if interaction is already replied or deferred', async () => {
mockInteraction.isCommand.mockReturnValue(true);
mockInteraction.commandName = 'testCommand';
interactionCreate.client.commands.set('testCommand', mockCommand);
mockCommand.execute.mockRejectedValue(new Error('Command failed'));
mockInteraction.replied = true;
await interactionCreate.execute(mockInteraction);
expect(mockInteraction.isCommand).toHaveBeenCalled();
expect(mockCommand.execute).toHaveBeenCalledWith(mockInteraction);
expect(mockInteraction.editReply).toHaveBeenCalledWith({
content: 'Your command has been deferred or replied to already!'
});
});
});

View File

@@ -0,0 +1,34 @@
require('module-alias/register'); // Ensure this is at the top
const { Events } = require('discord.js');
const handleCCOMention = require('@discordIntents/handleCCOMention');
const { saveServerData } = require('@discordUtilities/saveServerData');
module.exports = {
name: Events.MessageCreate,
async execute(message, serverData) {
if (message.author.bot) {
return;
}
const excludedGuilds = ['1168200542405808178']; // Add guild IDs to exclude
if (message.guild && excludedGuilds.includes(message.guild.id)) {
console.log(`Ignored message from excluded guild: ${message.guild.id}`);
return; // Ignore messages from excluded guilds
}
await handleCCOMention(message);
if (!serverData[message.guild.id]) {
serverData[message.guild.id] = {
messageCount: 0
};
}
serverData[message.guild.id].messageCount++;
saveServerData(serverData);
console.log(
`Message count for guild ${message.guild.name} in channel ${message.channel.name}: ${serverData[message.guild.id].messageCount}`
);
}
};

View File

@@ -0,0 +1,69 @@
import { Events } from 'discord.js';
import messageCreate from './messageCreate.js';
import handleCCOMention from '../intents/handleCCOMention.js';
import { saveServerData } from '../utilities/saveServerData.js';
jest.mock('../intents/handleCCOMention.js');
jest.mock('../utilities/saveServerData.js');
describe('messageCreate event handler', () => {
let message;
let serverData;
beforeEach(() => {
message = {
author: { bot: false },
guild: { id: '12345', name: 'Test Guild' }
};
serverData = {};
jest.clearAllMocks();
});
it('should return early if the message is from a bot', async () => {
message.author.bot = true;
await messageCreate.execute(message, serverData);
expect(handleCCOMention).not.toHaveBeenCalled();
expect(saveServerData).not.toHaveBeenCalled();
});
it('should call handleCCOMention with the message', async () => {
await messageCreate.execute(message, serverData);
expect(handleCCOMention).toHaveBeenCalledWith(message);
});
it('should initialize server data if it does not exist', async () => {
await messageCreate.execute(message, serverData);
expect(serverData['12345']).toEqual({ messageCount: 1 });
});
it('should increment the message count for the guild', async () => {
serverData['12345'] = { messageCount: 5 };
await messageCreate.execute(message, serverData);
expect(serverData['12345'].messageCount).toBe(6);
});
it('should save the updated server data', async () => {
await messageCreate.execute(message, serverData);
expect(saveServerData).toHaveBeenCalledWith(serverData);
});
it('should log the updated message count', async () => {
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
serverData['12345'] = { messageCount: 2 };
await messageCreate.execute(message, serverData);
expect(consoleSpy).toHaveBeenCalledWith(
'Message count for guild Test Guild: 3'
);
consoleSpy.mockRestore();
});
});

View File

@@ -0,0 +1,29 @@
const fs = require('fs');
const path = require('path');
// Load the JSON file
const copypastaFilePath = path.join(
__dirname,
'./tts-copypasta-hall-of-fame.json'
);
let copypastaData = null;
if (fs.existsSync(copypastaFilePath)) {
copypastaData = JSON.parse(fs.readFileSync(copypastaFilePath, 'utf8'));
}
module.exports = async message => {
if (message.content.toLowerCase().includes('cco')) {
// Select a random object from the JSON data
if (!copypastaData) {
await message.reply('I miss Charl');
} else {
const randomIndex = Math.floor(
Math.random() * copypastaData?.messages.length
);
const randomCopypasta = copypastaData.messages[randomIndex];
// Reply with the content key value
await message.reply(randomCopypasta.content);
}
}
};

View File

@@ -0,0 +1,85 @@
import handleCCOMention from './handleCCOMention.js';
import fs from 'fs';
import path from 'path';
import { jest } from '@jest/globals';
jest.mock('fs');
jest.mock('path');
describe('handleCCOMention', () => {
let mockMessage;
beforeEach(() => {
mockMessage = {
content: '',
reply: jest.fn()
};
jest.clearAllMocks();
});
it('should reply with "I miss Charl" if the JSON file does not exist', async () => {
fs.existsSync.mockReturnValue(false);
mockMessage.content = 'CCO is great!';
await handleCCOMention(mockMessage);
expect(mockMessage.reply).toHaveBeenCalledWith('I miss Charl');
});
it('should reply with a random message from the JSON file if it exists', async () => {
const mockData = {
messages: [
{ content: 'Message 1' },
{ content: 'Message 2' },
{ content: 'Message 3' }
]
};
fs.existsSync.mockReturnValue(true);
fs.readFileSync.mockReturnValue(JSON.stringify(mockData));
mockMessage.content = 'CCO is great!';
await handleCCOMention(mockMessage);
expect(mockMessage.reply).toHaveBeenCalled();
const replyContent = mockMessage.reply.mock.calls[0][0];
expect(mockData.messages.map(msg => msg.content)).toContain(replyContent);
});
it('should not reply if the message does not include "cco"', async () => {
fs.existsSync.mockReturnValue(true);
fs.readFileSync.mockReturnValue(
JSON.stringify({ messages: [{ content: 'Message 1' }] })
);
mockMessage.content = 'Hello world!';
await handleCCOMention(mockMessage);
expect(mockMessage.reply).not.toHaveBeenCalled();
});
it('should handle case-insensitive "cco" mentions', async () => {
const mockData = {
messages: [{ content: 'Message 1' }]
};
fs.existsSync.mockReturnValue(true);
fs.readFileSync.mockReturnValue(JSON.stringify(mockData));
mockMessage.content = 'I love CCO!';
await handleCCOMention(mockMessage);
expect(mockMessage.reply).toHaveBeenCalledWith('Message 1');
});
it('should handle empty JSON data gracefully', async () => {
fs.existsSync.mockReturnValue(true);
fs.readFileSync.mockReturnValue(JSON.stringify({ messages: [] }));
mockMessage.content = 'CCO is great!';
await handleCCOMention(mockMessage);
expect(mockMessage.reply).not.toHaveBeenCalled();
});
});

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
// dataStore.js
const dataStore = {
timeclock: {},
disputes: {},
tournaments: {}
};
module.exports = dataStore;

View File

@@ -0,0 +1,13 @@
{
"1260646229180944464": {
"messageCount": 159,
"activeTournamentId": "16175733"
},
"1168200542405808178": {
"messageCount": 263
},
"1364949980707819520": {
"messageCount": 141,
"activeTournamentId": "16155033"
}
}

View File

@@ -0,0 +1,11 @@
{
"1260646229180944464": {
"messageCount": 134
},
"1168200542405808178": {
"messageCount": 263
},
"1364949980707819520": {
"messageCount": 70
}
}

View File

@@ -0,0 +1,18 @@
require('module-alias/register'); // Ensure this is at the top
const {
EPHEMERAL_MESSAGE_DURATION_MILLISECS
} = require('@utilities/constants.js');
function deleteInteraction(interaction) {
interaction.then(() =>
setTimeout(
() => interaction.deleteReply(),
EPHEMERAL_MESSAGE_DURATION_MILLISECS
)
);
}
module.exports = {
deleteInteraction
};

View File

@@ -0,0 +1,92 @@
require('module-alias/register'); // Ensure this is at the top
const { REST, Routes, Client, GatewayIntentBits } = require('discord.js');
const { discordClientId, discordToken } = require('@config');
const fs = require('fs');
const path = require('path');
const { handleError } = require('@discordUtilities/error-handler.js'); // Import error handler
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const commands = [];
const commandFiles = getCommandFiles('src/discord/commands');
function getCommandFiles(directory) {
let commandFiles = [];
const files = fs.readdirSync(directory);
for (const file of files) {
const filePath = path.join(directory, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
// Recurse into subdirectory
commandFiles = commandFiles.concat(getCommandFiles(filePath));
} else if (file.endsWith('.js') && !file.endsWith('.spec.js')) {
// Add .js files excluding .spec.js
commandFiles.push(filePath);
}
}
return commandFiles;
}
for (const file of commandFiles) {
const commandModule = require(path.resolve(file));
if (Array.isArray(commandModule)) {
commandModule.forEach(command => {
if (command?.data) {
commands.push(command.data);
} else {
console.warn(`Command in file ${file} is invalid.`);
}
});
} else {
if (commandModule && commandModule.data) {
commands.push(commandModule.data);
} else {
console.warn(`Command in file ${file} is invalid.`);
}
}
}
const rest = new REST({ version: '10' }).setToken(discordToken);
client.once('ready', async () => {
try {
console.log('Started refreshing application (/) commands.');
// Fetch the list of guilds the bot is in
const guilds = client.guilds.cache.map(guild => guild.id);
// Register commands for each guild
for (const guildId of guilds) {
await rest.put(
Routes.applicationGuildCommands(discordClientId, guildId),
{
body: commands
}
);
console.log(
`Successfully reloaded application (/) commands for guild ${guildId}.`
);
}
console.log(
'Successfully reloaded application (/) commands for all guilds.'
);
} catch (error) {
handleError({
error,
updateInteraction: false,
errorArea: 'Utilities - deploy-commands.js'
}); // Handle any unexpected errors
} finally {
client.destroy();
}
});
// Log in to Discord with your client's token
client.login(discordToken);

View File

@@ -0,0 +1,101 @@
import { REST, Routes, Client, GatewayIntentBits } from 'discord.js';
import fs from 'fs';
import path from 'path';
import { getCommandFiles } from './deploy-commands.js';
import { discordClientId, discordToken } from '../../config.js';
import deployCommands from './deploy-commands.js';
jest.mock('discord.js');
jest.mock('fs');
jest.mock('path');
describe('deploy-commands.js', () => {
let mockClient;
let mockRest;
beforeEach(() => {
mockClient = {
once: jest.fn(),
login: jest.fn(),
destroy: jest.fn(),
guilds: {
cache: {
map: jest.fn()
}
}
};
mockRest = {
put: jest.fn(),
setToken: jest.fn().mockReturnThis()
};
Client.mockImplementation(() => mockClient);
REST.mockImplementation(() => mockRest);
});
afterEach(() => {
jest.clearAllMocks();
});
describe('getCommandFiles', () => {
it('should recursively fetch all .js files in a directory', () => {
fs.readdirSync.mockReturnValue(['file1.js', 'subdir']);
fs.statSync.mockImplementation(filePath => ({
isDirectory: () => filePath === 'src/commands/subdir'
}));
path.join.mockImplementation((...args) => args.join('/'));
fs.readdirSync.mockReturnValueOnce(['file1.js', 'subdir']);
fs.readdirSync.mockReturnValueOnce(['file2.js']);
const result = getCommandFiles('src/commands');
expect(result).toEqual([
'src/commands/file1.js',
'src/commands/subdir/file2.js'
]);
});
});
describe('Command registration', () => {
it('should register commands for all guilds', async () => {
const commands = [{ name: 'test', description: 'test command' }];
const guildIds = ['guild1', 'guild2'];
mockClient.guilds.cache.map.mockReturnValue(guildIds);
mockClient.once.mockImplementation((event, callback) => {
if (event === 'ready') callback();
});
await deployCommands;
expect(mockRest.put).toHaveBeenCalledTimes(guildIds.length);
guildIds.forEach((guildId, index) => {
expect(mockRest.put).toHaveBeenNthCalledWith(
index + 1,
Routes.applicationGuildCommands(discordClientId, guildId),
{ body: commands }
);
});
expect(mockClient.destroy).toHaveBeenCalled();
});
it('should log an error if command registration fails', async () => {
const error = new Error('Test error');
mockRest.put.mockRejectedValue(error);
const consoleErrorSpy = jest
.spyOn(console, 'error')
.mockImplementation(() => {});
mockClient.once.mockImplementation((event, callback) => {
if (event === 'ready') callback();
});
await deployCommands;
expect(consoleErrorSpy).toHaveBeenCalledWith(error);
consoleErrorSpy.mockRestore();
});
});
});

View File

@@ -0,0 +1,99 @@
const { EmbedBuilder } = require('discord.js');
// /Users/fragginwagon/Developer/Source Code/discord/GODispute/src/discord/utilities/error-handling.js
/**
* Universal error handler for a Discord.js bot.
* @param {Object} options - Options for error handling.
* @param {Object} options.error - The error object to handle.
* @param {Object} options.user - The user to send the error message to (if applicable).
* @param {string} [options.customMessage] - A custom error message to send to the user.
* @param {Object} [options.logger=console] - Optional logger for logging errors (e.g., console or a logging library).
* @param {Object} options.interaction - The Discord interaction object associated with the command.
* @param {string} [options.errorArea='Unknown Area'] - A string indicating the area or context where the error occurred.
* @param {boolean} [options.sendToUser=true] - Whether to send the error message to the user via direct message.
* @param {boolean} [options.updateInteraction=true] - Whether to reply to or edit the interaction response with an error message.
* @description Handles errors by logging them, optionally sending a message to a user, and replying to or editing the interaction response.
*/
async function handleError({
error,
user = '203292966670958592', // Default to a specific user ID
customMessage,
logger = console,
interaction,
errorArea = 'Unknown Area',
sendToUser = true,
updateInteraction = true
}) {
// Log the error
logger.error('An error occurred:', error || customMessage);
// Default error message
const defaultErrorMessage =
'An unexpected error occurred. Please try again later.';
// If a user is provided, send them a direct message
if (sendToUser && user) {
const embed = new EmbedBuilder()
.setColor('#FF0000')
.setTitle('Error')
.setDescription(
`${customMessage || defaultErrorMessage}
\n\n\`\`\`${error.stack || error.message}\`\`\``
)
.setTimestamp();
try {
// Fetch the user object if user is a string (user ID)
const targetUser =
typeof user === 'string'
? await interaction?.client?.users?.fetch(user)
: user;
if (!targetUser) {
logger.error('User not found:', user);
return;
}
targetUser.send({ embeds: [embed] }).catch(err => {
logger.error('Failed to send error message to user:', err);
});
} catch (err) {
logger.error('Failed to fetch user or send message:', err);
}
}
if (updateInteraction) {
try {
if (!interaction.replied && !interaction.deferred) {
return await interaction.deferReply({ ephemeral: true }).catch(err => {
logger.error('Failed to defer interaction reply:', err);
});
}
if (interaction.deferred && !interaction.replied) {
await interaction
.editReply({
content: customMessage || defaultErrorMessage
})
.catch(err => {
logger.error('Failed to edit interaction reply:', err);
});
}
if (!interaction.deferred && interaction.replied) {
await interaction
.followUp({
content: customMessage || defaultErrorMessage,
ephemeral: true
})
.catch(err => {
logger.error('Failed to follow up on interaction reply:', err);
});
}
} catch (err) {
logger.error('Failed to handle interaction response:', err);
}
}
}
module.exports = { handleError };

View File

@@ -0,0 +1,18 @@
const fs = require('fs');
const path = require('path');
const environment = process.env.NODE_ENV || 'development';
const serverDataFilePath = path.join(
__dirname,
`../store/${environment}-serverData.json`
);
function saveServerData(serverData) {
fs.writeFileSync(
serverDataFilePath,
JSON.stringify(serverData, null, 2),
'utf8'
);
}
module.exports = { saveServerData };

View File

@@ -0,0 +1,47 @@
import fs from 'fs';
import path from 'path';
import { jest } from '@jest/globals';
import { saveServerData } from './saveServerData.js';
jest.mock('fs');
describe('saveServerData', () => {
const mockServerData = { guildId: '12345', settings: { prefix: '!' } };
const serverDataFilePath = path.join(
new URL('.', import.meta.url).pathname,
'../store/serverData.json'
);
afterEach(() => {
jest.clearAllMocks();
});
it('should write the server data to the correct file path', () => {
saveServerData(mockServerData);
expect(fs.writeFileSync).toHaveBeenCalledWith(
serverDataFilePath,
JSON.stringify(mockServerData, null, 2),
'utf8'
);
});
it('should throw an error if writing to the file fails', () => {
fs.writeFileSync.mockImplementation(() => {
throw new Error('File write error');
});
expect(() => saveServerData(mockServerData)).toThrow('File write error');
});
it('should serialize the server data as a JSON string', () => {
saveServerData(mockServerData);
const jsonString = JSON.stringify(mockServerData, null, 2);
expect(fs.writeFileSync).toHaveBeenCalledWith(
serverDataFilePath,
jsonString,
'utf8'
);
});
});

View File

@@ -0,0 +1,171 @@
# Play! Pokémon GO Judge Roles
## Pokémon GO Floor Judge
**Duties and Responsibilities:**
- **On-the-Ground Support:** Floor Judges are responsible for handling issues and inquiries from participants during the event. Theyre the first point of contact for players who need assistance or have questions.
- **Rule Enforcement:** They ensure that the rules of the tournament or event are being followed. This includes monitoring gameplay, addressing rule violations, and making sure that matches are conducted fairly.
- **Match Oversight:** Floor Judges may be assigned to oversee specific matches, ensuring that they are played according to the established rules and resolving any disputes that arise.
- **Player Assistance:** They provide guidance and support to players, including helping them with registration issues, understanding event procedures, and addressing any concerns they might have.
- **Reporting Issues:** They report any significant issues or disputes to the higher-ranking judges (Assistant Head Judge or Head Judge) for resolution.
- **Technical Issues:** Help the players with logging in and more importantly when logging out how to remove personal information from the phones.
- **Team Checks:** On an as needed bases, check the players team posted on RK9 and compare it to the team shown on the phone they are using. In addition, using gameplay footage to verify is always good to do if you have time.
- **Match Reporting:** Using Challonge to update what tables are playing currently as well as the final scores when a player raises their hands.
- **Crowd Control:** Making sure other players are giving an appropriate distance from the table to give the active players comfortable and focused on the games at hand. Also assists with deterring cheating.
- **Housekeeping:** Making sure the stations where players will be playing is clean, free from debris or clutter. In addition, phones are connected to the chargers and back on the stands. Chairs should be pushed in and ready for the next player.
- **Phone Testing:** Logging in to the phones with the organizers' Google login to make sure that assets are downloaded, game functions properly, and battles do not seem to have any issues.
- **Game Disputes:** Handle any game disputes the players might have. You are the first line of defense in terms of being able to solve their problem and make a ruling. After making a ruling always explain to them if they would like to appeal to a head judge they may ask for that.
- **Penalties:** Handle explaining any penalties the player might incur from being late, not submitting a team, not having the same Pokémon registered in RK9 vs what they are playing with in a manner they can understand and can comply with.
## Pokémon GO Assistant Head Judge
**Duties and Responsibilities:**
- **Support to Head Judge:** Work closely with the Head Judge to help manage the event, including providing support for decision-making and overall event management.
- **Rule Interpretation:** Assist in interpreting and applying rules during the event, particularly in more complex situations or when disputes arise.
- **Dispute Resolution:** Handle disputes or rule violations that are escalated from Floor Judges. Provide fair and consistent resolutions based on the event rules and guidelines.
- **Judge Coordination:** Help coordinate and manage the Floor Judges, ensuring they are performing their duties correctly and effectively.
- **Logistical Support:** Assist with the logistical aspects of the event, including scheduling, match management, and ensuring the event progresses smoothly.
## Pokémon GO Head Judge
**Duties and Responsibilities:**
- **Event Management:** Oversee the entire event, ensuring that it is conducted according to the established rules and regulations.
- **Final Decision-Making:** Make final decisions on disputes and rule violations that have been escalated from the Assistant Head Judge. Their decisions are authoritative and final.
- **Rule Consistency:** Ensure that the rules are applied consistently across all matches and that all participants are treated fairly.
- **Team Oversight:** Manage and oversee the judging team, including Floor Judges and Assistant Head Judge. Provide guidance, support, and address any issues within the judging team.
- **Communication:** Act as the primary liaison between the event organizers and the judging team, ensuring that any major issues or changes are communicated effectively.
## Pokémon GO Lead Judge
**Duties and Responsibilities:**
- **Event Planning:** Involved in the planning and preparation stages of the event, working with organizers to ensure all aspects of the event are properly coordinated.
- **Judge Training:** Responsible for the training and preparation of the judging team, including Floor Judges and Assistant Head Judges, to ensure they are well-versed in the rules and their roles.
- **Strategic Oversight:** Provide strategic oversight for the event, making high-level decisions to ensure the event runs smoothly and addressing any significant issues that arise.
- **Complex Issue Resolution:** Handle complex or high-profile disputes and problems that may arise during the event, ensuring fair and balanced resolutions.
- **Reporting and Evaluation:** Provide post-event reports and evaluations to organizers and stakeholders, summarizing the event's success, challenges, and areas for improvement.
# Toronto Information
Chain of Command
GO Head Judge and AHJ will report to the GO Lead
All GO Floor Judges will report to either the GO HJ or AHJ
GO Bracket Admin will report the GO Lead
GO Activity Desk staff will report to the GO Lead
Floor Judges should report any tech related issues to the HJ team, who will then escalate to the GO lead or Gaming Generations if needed
Event Roles & Responsibilities
GO Lead - Pete
Ensures the GO main event Floor & Stream, proceeds on schedule
Oversees the whole team
Schedules breaks for the Bracket Admin & HJ Team
Can provide support during complicated rulings and penalties
Communicates directly with all other tournament areas and Organizer when required
GO Head Judge Team - Charles & Allison
Keep their team of floor judges organized
First Point of escalation for the floor judges
Schedule breaks & stream rotations for floor judges
Final decision & authorization of penalties
Final level of appeal for all game rulings
Will provide active feedback during the event to all Floor Judges
GO Bracket Admin - Kieng
Print all player team sheets
Completes all Challonge related admin work
Assigns players, a table number for each round
Communicates effectively with the GO stream team about match preferences
Informs the floor about end of round issues
GO Floor Judges Matt, Sabrina, Illya, Ryan, Kate, Greg
First level on contact for player questions on the floor
Provide game reviews to players to help solve technical disputes
Use Challonge to mark floor matches as active and to enter final match results
Complete player team checks
Issue Warnings and “No Show” penalties to players
Possibly judge matches on the live stream
GO Activity Desk Patrick & Bizz
Often the first point of contact for GO related questions
Will explain & issue Pokemon GO themed scavenger hunt cards
Verify completed scavenger hunt cards when players return them
Useful Information
Penalties
• Any issued Penalties MUST be reported using the Penalty Reporting Discord thread
• Penalties higher in severity than a warning MUST be escalated to and then verified by the HJ team.
This INCLUDES penalties where you would like to ESCALATE or DEESCALATE the awarded penalty
Some examples are:
The initial penalty is a GAME LOSS, but you would like to award a WARNING: This De-escalation must be approved by a Head Judge
The initial penalty is a WARNING, but you would like to award a GAME LOSS: This Escalation must be approved by a Head Judge
Only exceptions are single “No-Show” penalties given at the 5 & 10 min marks after a round has started
• If you are unsure of the correct penalty at any time, please ask a fellow Floor Judge to help
Please avoid requesting the Head Judge to assist - if you need further support, please go to the AHJ first.
This maintains the players route to escalation for Head Judge appeal
Team Checks & Result Entering
• Team Checks should be done on every winner for every round after Round 1, when time permits
• Team checks MUST be performed before entering final match results on Challonge
• Team lists can be found on RK9, access will be provided before the event starts
• If the floor is very busy team checks may be temporarily skipped, but this will be decided by the HJ team
• Team checks MUST include a look through a players recorded battle footage to verify correct move sets
• Once a team check is complete it needs to be entered into the Discord Team Check Reporting Thread
• Challonge Admin access will be provided before the event begins
• If a double no show occurs, it should be entered as -1 & -2 on Challonge, with the -1 going to the higher seeded player/the player on top of the matchup
Please alert the HJ team of this, as a round loss penalty will also need to be applied to the player who still moved on, during the next round
Game Reviews & Disputes
• Any Reviews MUST be reported using the “Game Review Reporting Discord Thread”
• When first starting the review, give each player the opportunity to explain to you their version of what happened
• Carefully watch the video footage of the issue on each phone, to get both perspectives entirely
• The players will need to point out the specific technical issue that affected them, which means you should not be looking for the issues yourself
• If the game review is complicated and if you're not confident with your decision, please ask another judge to look at the footage with you
Please avoid requesting the Head Judge to assist - if you need further support, please go to the AHJ first.
This maintains the players route to escalation for Head Judge appeal
• Be mindful of the time you spend trying to resolve the dispute. If you've been only watching video footage for over 5-10 mins you could possibly be overthinking it.
• Explain your ruling clearly to both players, and remind them that they can appeal to the head judge team
• Once leaving the table, you must enter the review details in the corresponding discord thread
• Please don't put yourself in situations where you can be accused of being Biased. You should not be making rulings on matches that involve family, friends or faction teammates. Get another judge to take over in situations like this
Stream Judging
• Team checks are to be performed on both players before the match begins. This will be done by another judge before hand & not by the active judge on stream
• Blank match slips will be provided. Please fill them out and have both players sign it. This is to mark the official ending of the match before they leave the stream stage. Which means no further appeals can happen
• Keep an out for possible signaling from spectators, by ensuring players are not looking into crowd during games
• Players have 2 min in-between games to lock in team selections
• Matches are to be recorded using the provided device on stage
• Remember to communicate with production about any technical issues using the laptop provided on stage
• All staff will be shown how the stream equipment works on Saturday morning by the GO Stage Manager
• Be mindful of your actions and demeanor while being a stream judge. Lots of eyes will be on you
How to Prepare Before the Event
• Read all documents posted by the tournament organizer, Gaming Generations
• Refresh yourself with all aspects of the GO Tournament & Play rule books
• Take a look at the linktree posted above
• Make sure your familiar with and that you have the ability to sign into “Challonge”
• Ensure your able to sign into “RK9”
• Please make sure you sleep and arrive well rested
• Wear comfy shoes and pack a water bottle, to help stay hydrated. Snacks are always a great idea too.
• Bring a power bank for your phone. Your phone will be used a lot during the event
• Pack a clipboard or note pad if you like taking paper notes during the event
• If you have the ability to bring a tablet, you should. It will make navigating Challonge so much easier with the bigger screen (Not Required)
• Please ask any questions you might have via our discord channel, or directly via DM

View File

@@ -0,0 +1,9 @@
## Pokémon GO Assistant Head Judge
**Duties and Responsibilities:**
- **Support to Head Judge:** Work closely with the Head Judge to help manage the event, including providing support for decision-making and overall event management.
- **Rule Interpretation:** Assist in interpreting and applying rules during the event, particularly in more complex situations or when disputes arise.
- **Dispute Resolution:** Handle disputes or rule violations that are escalated from Floor Judges. Provide fair and consistent resolutions based on the event rules and guidelines.
- **Judge Coordination:** Help coordinate and manage the Floor Judges, ensuring they are performing their duties correctly and effectively.
- **Logistical Support:** Assist with the logistical aspects of the event, including scheduling, match management, and ensuring the event progresses smoothly.

View File

@@ -0,0 +1,17 @@
## Pokémon GO Floor Judge
**Duties and Responsibilities:**
- **On-the-Ground Support:** Floor Judges are responsible for handling issues and inquiries from participants during the event. Theyre the first point of contact for players who need assistance or have questions.
- **Rule Enforcement:** They ensure that the rules of the tournament or event are being followed. This includes monitoring gameplay, addressing rule violations, and making sure that matches are conducted fairly.
- **Match Oversight:** Floor Judges may be assigned to oversee specific matches, ensuring that they are played according to the established rules and resolving any disputes that arise.
- **Player Assistance:** They provide guidance and support to players, including helping them with registration issues, understanding event procedures, and addressing any concerns they might have.
- **Reporting Issues:** They report any significant issues or disputes to the higher-ranking judges (Assistant Head Judge or Head Judge) for resolution.
- **Technical Issues:** Help the players with logging in and more importantly when logging out how to remove personal information from the phones.
- **Team Checks:** On an as needed bases, check the players team posted on RK9 and compare it to the team shown on the phone they are using. In addition, using gameplay footage to verify is always good to do if you have time.
- **Match Reporting:** Using Challonge to update what tables are playing currently as well as the final scores when a player raises their hands.
- **Crowd Control:** Making sure other players are giving an appropriate distance from the table to give the active players comfortable and focused on the games at hand. Also assists with deterring cheating.
- **Housekeeping:** Making sure the stations where players will be playing is clean, free from debris or clutter. In addition, phones are connected to the chargers and back on the stands. Chairs should be pushed in and ready for the next player.
- **Phone Testing:** Logging in to the phones with the organizers' Google login to make sure that assets are downloaded, game functions properly, and battles do not seem to have any issues.
- **Game Disputes:** Handle any game disputes the players might have. You are the first line of defense in terms of being able to solve their problem and make a ruling. After making a ruling always explain to them if they would like to appeal to a head judge they may ask for that.
- **Penalties:** Handle explaining any penalties the player might incur from being late, not submitting a team, not having the same Pokémon registered in RK9 vs what they are playing with in a manner they can understand and can comply with.

View File

@@ -0,0 +1,9 @@
## Pokémon GO Head Judge
**Duties and Responsibilities:**
- **Event Management:** Oversee the entire event, ensuring that it is conducted according to the established rules and regulations.
- **Final Decision-Making:** Make final decisions on disputes and rule violations that have been escalated from the Assistant Head Judge. Their decisions are authoritative and final.
- **Rule Consistency:** Ensure that the rules are applied consistently across all matches and that all participants are treated fairly.
- **Team Oversight:** Manage and oversee the judging team, including Floor Judges and Assistant Head Judge. Provide guidance, support, and address any issues within the judging team.
- **Communication:** Act as the primary liaison between the event organizers and the judging team, ensuring that any major issues or changes are communicated effectively.

View File

@@ -0,0 +1,9 @@
## Pokémon GO Lead Judge
**Duties and Responsibilities:**
- **Event Planning:** Involved in the planning and preparation stages of the event, working with organizers to ensure all aspects of the event are properly coordinated.
- **Judge Training:** Responsible for the training and preparation of the judging team, including Floor Judges and Assistant Head Judges, to ensure they are well-versed in the rules and their roles.
- **Strategic Oversight:** Provide strategic oversight for the event, making high-level decisions to ensure the event runs smoothly and addressing any significant issues that arise.
- **Complex Issue Resolution:** Handle complex or high-profile disputes and problems that may arise during the event, ensuring fair and balanced resolutions.
- **Reporting and Evaluation:** Provide post-event reports and evaluations to organizers and stakeholders, summarizing the event's success, challenges, and areas for improvement.

View File

@@ -0,0 +1,51 @@
const fs = require('fs');
const path = require('path');
const readline = require('readline');
function logAction(action) {
console.log(`[ACTION]: ${action}`);
}
async function parseAndAddEmails(inputFilePath) {
logAction('Starting to process the CSV file.');
const outputFilePath = inputFilePath.replace('.csv', '-with-emails.csv');
const readStream = fs.createReadStream(inputFilePath);
const writeStream = fs.createWriteStream(outputFilePath);
const rl = readline.createInterface({
input: readStream,
crlfDelay: Infinity
});
let isHeader = true;
for await (const line of rl) {
const columns = line.split(',');
if (isHeader) {
logAction('Processing header row.');
writeStream.write(
`${columns.slice(0, 6).join(',')},email,${columns[6]}\n`
);
isHeader = false;
} else {
logAction('Processing a data row.');
const screenname = columns[5];
const email = `${screenname}@example.com`;
writeStream.write(
`${columns.slice(0, 6).join(',')},${email},${columns[6]}\n`
);
}
}
logAction('Finished processing the CSV file.');
writeStream.end();
logAction(`Output written to ${outputFilePath}`);
}
// Example usage
const inputFilePath =
'/Users/fragginwagon/Developer/Source Code/discord/GODispute/docsNrefs/registrations/20250504-MK03mHVg2MthNoBwub5w-registrations.csv';
parseAndAddEmails(inputFilePath).catch(err =>
console.error(`[ERROR]: ${err.message}`)
);

View File

@@ -0,0 +1,883 @@
const axios = require('axios');
const { CHALLONGE_API_BASE_URL } = require('../constants');
const { challongeApiKey } = require('../../config');
let challongeApi = axios.create({
baseURL: CHALLONGE_API_BASE_URL,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
params: {
api_key: challongeApiKey
}
});
const handleError = error => {
return Promise.reject({ 'Challonge API Error': error });
};
/**
* Retrieves a list of tournaments created with your account.
*
* @param {Object} params - Query parameters for filtering tournaments.
* @param {string} [params.state] - Filter by state (all, pending, in_progress, ended).
* @param {string} [params.type] - Filter by type (single_elimination, double_elimination, round_robin, swiss).
* @param {string} [params.created_after] - Filter by creation date after (YYYY-MM-DD).
* @param {string} [params.created_before] - Filter by creation date before (YYYY-MM-DD).
* @param {string} [params.subdomain] - Filter by subdomain (organization-hosted tournaments).
* @returns {Promise<Object>} - A promise resolving to the list of tournaments.
*/
const listTournaments = async (params = {}) => {
try {
const url = '/tournaments';
challongeApi.defaults.params = {
...challongeApi.defaults.params,
...params
};
const response = await challongeApi.get(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Creates a new tournament.
*
* @param {Object} data - The tournament data.
* @param {string} data.name - Your event's name/title (Max: 60 characters) (required).
* @param {string} [data.tournament_type] - Single elimination (default), double elimination, round robin, swiss.
* @param {string} [data.url] - Custom URL (letters, numbers, and underscores only).
* @param {string} [data.subdomain] - Subdomain for the tournament.
* @param {string} [data.description] - Description/instructions to be displayed above the bracket.
* @param {boolean} [data.open_signup] - True or false. Host a sign-up page.
* @param {boolean} [data.hold_third_place_match] - True or false. Include a match between semifinal losers.
* @param {number} [data.pts_for_match_win] - Points for match win (Swiss only).
* @param {number} [data.pts_for_match_tie] - Points for match tie (Swiss only).
* @param {number} [data.pts_for_game_win] - Points for game win (Swiss only).
* @param {number} [data.pts_for_game_tie] - Points for game tie (Swiss only).
* @param {number} [data.pts_for_bye] - Points for bye (Swiss only).
* @param {number} [data.swiss_rounds] - Number of Swiss rounds.
* @param {string} [data.ranked_by] - Ranking method ('match wins', 'game wins', 'points scored', etc.).
* @param {number} [data.rr_pts_for_match_win] - Round Robin points for match win (custom only).
* @param {number} [data.rr_pts_for_match_tie] - Round Robin points for match tie (custom only).
* @param {number} [data.rr_pts_for_game_win] - Round Robin points for game win (custom only).
* @param {number} [data.rr_pts_for_game_tie] - Round Robin points for game tie (custom only).
* @param {boolean} [data.accept_attachments] - Allow match attachment uploads.
* @param {boolean} [data.hide_forum] - Hide the forum tab on the Challonge page.
* @param {boolean} [data.show_rounds] - Label each round above the bracket.
* @param {boolean} [data.private] - Hide this tournament from the public index.
* @param {boolean} [data.notify_users_when_matches_open] - Notify participants when matches open.
* @param {boolean} [data.notify_users_when_the_tournament_ends] - Notify participants when the tournament ends.
* @param {boolean} [data.sequential_pairings] - Use sequential pairings instead of traditional seeding rules.
* @param {number} [data.signup_cap] - Maximum number of participants.
* @param {string} [data.start_at] - Planned start time for the tournament (ISO 8601 format).
* @param {number} [data.check_in_duration] - Length of the check-in window in minutes.
* @param {string} [data.grand_finals_modifier] - Grand finals modifier ('single match', 'skip', or null).
*
* @returns {Promise<Object>} - A promise resolving to the created tournament data.
*/
const createTournament = async data => {
try {
const url = '/tournaments';
const response = await challongeApi.post(url, { tournament: data });
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Retrieves a single tournament record created with your account.
*
* @param {string} id - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {Object} [options] - Optional parameters for the request.
* @param {string} [options.apiKey] - Your API key (required unless using HTTP basic authentication).
* @param {boolean} [options.includeParticipants=false] - Whether to include an array of associated participant records.
* @param {boolean} [options.includeMatches=false] - Whether to include an array of associated match records.
* @returns {Promise<Object>} A promise that resolves to the tournament data.
* @throws {Error} If the request fails or the API returns an error.
*/
const getTournament = async (id, options = {}) => {
// GET: Retrieve a single tournament record created with your account
try {
const url = `/tournaments/${id}`;
const response = await challongeApi.get(url, {
params: {
include_participants: options?.includeParticipants || false,
include_matches: options?.includeMatches || false
}
});
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Updates a tournament's attributes.
*
* @param {string} id - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {Object} data - The tournament data to update.
* @param {string} [data.name] - Your event's name/title (Max: 60 characters).
* @param {string} [data.tournament_type] - Single elimination (default), double elimination, round robin, swiss.
* @param {string} [data.url] - Custom URL (letters, numbers, and underscores only).
* @param {string} [data.subdomain] - Subdomain for the tournament.
* @param {string} [data.description] - Description/instructions to be displayed above the bracket.
* @param {boolean} [data.open_signup] - True or false. Host a sign-up page.
* @param {boolean} [data.hold_third_place_match] - True or false. Include a match between semifinal losers.
* @param {number} [data.pts_for_match_win] - Points for match win (Swiss only).
* @param {number} [data.pts_for_match_tie] - Points for match tie (Swiss only).
* @param {number} [data.pts_for_game_win] - Points for game win (Swiss only).
* @param {number} [data.pts_for_game_tie] - Points for game tie (Swiss only).
* @param {number} [data.pts_for_bye] - Points for bye (Swiss only).
* @param {number} [data.swiss_rounds] - Number of Swiss rounds.
* @param {string} [data.ranked_by] - Ranking method ('match wins', 'game wins', 'points scored', etc.).
* @param {number} [data.rr_pts_for_match_win] - Round Robin points for match win (custom only).
* @param {number} [data.rr_pts_for_match_tie] - Round Robin points for match tie (custom only).
* @param {number} [data.rr_pts_for_game_win] - Round Robin points for game win (custom only).
* @param {number} [data.rr_pts_for_game_tie] - Round Robin points for game tie (custom only).
* @param {boolean} [data.accept_attachments] - Allow match attachment uploads.
* @param {boolean} [data.hide_forum] - Hide the forum tab on the Challonge page.
* @param {boolean} [data.show_rounds] - Label each round above the bracket.
* @param {boolean} [data.private] - Hide this tournament from the public index.
* @param {boolean} [data.notify_users_when_matches_open] - Notify participants when matches open.
* @param {boolean} [data.notify_users_when_the_tournament_ends] - Notify participants when the tournament ends.
* @param {boolean} [data.sequential_pairings] - Use sequential pairings instead of traditional seeding rules.
* @param {number} [data.signup_cap] - Maximum number of participants.
* @param {string} [data.start_at] - Planned start time for the tournament (ISO 8601 format).
* @param {number} [data.check_in_duration] - Length of the check-in window in minutes.
* @param {string} [data.grand_finals_modifier] - Grand finals modifier ('single match', 'skip', or null).
*
* @returns {Promise<Object>} - A promise resolving to the updated tournament data.
* @throws {Error} If the request fails or the API returns an error.
*/
const updateTournament = async (id, data) => {
try {
const url = `/tournaments/${id}`;
const response = await challongeApi.put(url, { tournament: data });
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Deletes a tournament along with all its associated records.
* There is no undo, so use with care!
*
* @param {string} id - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @returns {Promise<Object>} - A promise resolving to the response data.
* @throws {Error} If the request fails or the API returns an error.
*/
const deleteTournament = async id => {
try {
const url = `/tournaments/${id}`;
const response = await challongeApi.delete(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Processes check-in results for a tournament.
* This should be invoked after a tournament's check-in window closes and before the tournament is started.
*
* Marks participants who have not checked in as inactive.
* Moves inactive participants to bottom seeds (ordered by original seed).
* Transitions the tournament state from 'checking_in' to 'checked_in'.
* NOTE: Checked-in participants on the waiting list will be promoted if slots become available.
*
* @param {string} id - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {Object} [options] - Optional parameters for the request.
* @param {boolean} [options.includeParticipants=false] - Whether to include an array of associated participant records.
* @param {boolean} [options.includeMatches=false] - Whether to include an array of associated match records.
* @returns {Promise<Object>} - A promise resolving to the updated tournament data.
* @throws {Error} If the request fails or the API returns an error.
*/
const processCheckIns = async (id, options = {}) => {
try {
const url = `/tournaments/${id}/process_check_ins`;
const response = await challongeApi.post(url, null, {
params: {
include_participants: options.includeParticipants || false,
include_matches: options.includeMatches || false
}
});
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Aborts check-in for a tournament.
* Makes all participants active and clears their checked_in_at times.
* Transitions the tournament state from 'checking_in' or 'checked_in' to 'pending'.
*
* @param {string} id - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {Object} [options] - Optional parameters for the request.
* @param {boolean} [options.includeParticipants=false] - Whether to include an array of associated participant records.
* @param {boolean} [options.includeMatches=false] - Whether to include an array of associated match records.
* @returns {Promise<Object>} - A promise resolving to the updated tournament data.
* @throws {Error} If the request fails or the API returns an error.
*/
const abortCheckIn = async (id, options = {}) => {
try {
const url = `/tournaments/${id}/abort_check_in`;
const response = await challongeApi.post(url, null, {
params: {
include_participants: options.includeParticipants || false,
include_matches: options.includeMatches || false
}
});
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Starts a tournament, opening up first-round matches for score reporting.
* The tournament must have at least 2 participants.
*
* @param {string} id - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {Object} [options] - Optional parameters for the request.
* @param {boolean} [options.includeParticipants=false] - Whether to include an array of associated participant records.
* @param {boolean} [options.includeMatches=false] - Whether to include an array of associated match records.
* @returns {Promise<Object>} - A promise resolving to the updated tournament data.
* @throws {Error} If the request fails or the API returns an error.
*/
const startTournament = async (id, options = {}) => {
try {
const url = `/tournaments/${id}/start`;
const response = await challongeApi.post(url, null, {
params: {
include_participants: options.includeParticipants || false,
include_matches: options.includeMatches || false
}
});
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Finalizes a tournament that has had all match scores submitted, rendering its results permanent.
*
* @param {string} id - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {Object} [options] - Optional parameters for the request.
* @param {boolean} [options.includeParticipants=false] - Whether to include an array of associated participant records.
* @param {boolean} [options.includeMatches=false] - Whether to include an array of associated match records.
* @returns {Promise<Object>} - A promise resolving to the finalized tournament data.
* @throws {Error} If the request fails or the API returns an error.
*/
const finalizeTournament = async (id, options = {}) => {
try {
const url = `/tournaments/${id}/finalize`;
const response = await challongeApi.post(url, null, {
params: {
include_participants: options.includeParticipants || false,
include_matches: options.includeMatches || false
}
});
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Resets a tournament, clearing all of its scores and attachments.
* This allows you to add, remove, or edit participants before starting the tournament again.
*
* @param {string} id - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {Object} [options] - Optional parameters for the request.
* @param {boolean} [options.includeParticipants=false] - Whether to include an array of associated participant records.
* @param {boolean} [options.includeMatches=false] - Whether to include an array of associated match records.
* @returns {Promise<Object>} - A promise resolving to the reset tournament data.
* @throws {Error} If the request fails or the API returns an error.
*/
const resetTournament = async (id, options = {}) => {
try {
const url = `/tournaments/${id}/reset`;
const response = await challongeApi.post(url, null, {
params: {
include_participants: options.includeParticipants || false,
include_matches: options.includeMatches || false
}
});
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Opens a tournament for predictions.
* Sets the state of the tournament to start accepting predictions.
* Your tournament's 'prediction_method' attribute must be set to 1 (exponential scoring)
* or 2 (linear scoring) to use this option.
* Note: Once open for predictions, match records will be persisted, so participant additions
* and removals will no longer be permitted.
*
* @param {string} id - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {Object} [options] - Optional parameters for the request.
* @param {boolean} [options.includeParticipants=false] - Whether to include an array of associated participant records.
* @param {boolean} [options.includeMatches=false] - Whether to include an array of associated match records.
* @returns {Promise<Object>} - A promise resolving to the updated tournament data.
* @throws {Error} If the request fails or the API returns an error.
*/
const openForPredictions = async (id, options = {}) => {
try {
const url = `/tournaments/${id}/open_for_predictions`;
const response = await challongeApi.post(url, null, {
params: {
include_participants: options.includeParticipants || false,
include_matches: options.includeMatches || false
}
});
return response.data;
} catch (error) {
return handleError(error);
}
};
// Participants API
/**
* Retrieves a tournament's participant list.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @returns {Promise<Object>} - A promise resolving to the list of participants.
* @throws {Error} If the request fails or the API returns an error.
*/
const getParticipants = async tournamentId => {
try {
const url = `/tournaments/${tournamentId}/participants`;
const response = await challongeApi.get(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Adds a participant to a tournament (up until it is started).
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {Object} data - The participant data.
* @param {string} [data.name] - The name displayed in the bracket/schedule. Must be unique per tournament.
* @param {string} [data.challonge_username] - Challonge username of the participant (optional).
* @param {string} [data.email] - Email of the participant (optional).
* @param {number} [data.seed] - The participant's new seed (integer).
* @param {string} [data.misc] - Multi-purpose field (max: 255 characters).
* @returns {Promise<Object>} - A promise resolving to the added participant data.
* @throws {Error} If the request fails or the API returns an error.
*/
const addParticipant = async (tournamentId, data) => {
try {
const url = `/tournaments/${tournamentId}/participants`;
const response = await challongeApi.post(url, { participant: data });
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Bulk adds participants to a tournament (up until it is started).
* If an invalid participant is detected, bulk participant creation will halt,
* and any previously added participants (from this API request) will be rolled back.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {Array<Object>} data - An array of participant objects to add.
* @param {string} [data[].name] - The name displayed in the bracket/schedule. Must be unique per tournament.
* @param {string} [data[].invite_name_or_email] - Challonge username or email for inviting participants.
* @param {number} [data[].seed] - The participant's new seed (integer).
* @param {string} [data[].misc] - Multi-purpose field (max: 255 characters).
* @returns {Promise<Object>} - A promise resolving to the response data.
* @throws {Error} If the request fails or the API returns an error.
*/
const bulkAddParticipants = async (tournamentId, data) => {
try {
const url = `/tournaments/${tournamentId}/participants/bulk_add`;
const response = await challongeApi.post(url, { participants: data });
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Retrieves a single participant record for a tournament.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} participantId - The participant's unique ID.
* @param {Object} [options] - Optional parameters for the request.
* @param {boolean} [options.includeMatches=false] - Whether to include an array of associated match records.
* @returns {Promise<Object>} - A promise resolving to the participant data.
* @throws {Error} If the request fails or the API returns an error.
*/
const getParticipant = async (tournamentId, participantId, options = {}) => {
try {
const url = `/tournaments/${tournamentId}/participants/${participantId}`;
const response = await challongeApi.get(url, {
params: {
include_matches: options.includeMatches || false
}
});
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Updates the attributes of a tournament participant.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} participantId - The participant's unique ID.
* @param {Object} data - The participant data to update.
* @param {string} [data.name] - The name displayed in the bracket/schedule. Must be unique per tournament.
* @param {string} [data.challonge_username] - Challonge username of the participant (optional).
* @param {string} [data.email] - Email of the participant (optional).
* @param {number} [data.seed] - The participant's new seed (integer).
* @param {string} [data.misc] - Multi-purpose field (max: 255 characters).
* @returns {Promise<Object>} - A promise resolving to the updated participant data.
* @throws {Error} If the request fails or the API returns an error.
*/
const updateParticipant = async (tournamentId, participantId, data) => {
try {
const url = `/tournaments/${tournamentId}/participants/${participantId}`;
const response = await challongeApi.put(url, { participant: data });
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Checks a participant in, setting checked_in_at to the current time.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} participantId - The participant's unique ID.
* @returns {Promise<Object>} - A promise resolving to the updated participant data.
* @throws {Error} If the request fails or the API returns an error.
*/
const checkInParticipant = async (tournamentId, participantId) => {
try {
const url = `/tournaments/${tournamentId}/participants/${participantId}/check_in`;
const response = await challongeApi.post(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Undoes the check-in for a participant, setting checked_in_at to null.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} participantId - The participant's unique ID.
* @returns {Promise<Object>} - A promise resolving to the updated participant data.
* @throws {Error} If the request fails or the API returns an error.
*/
const undoCheckInParticipant = async (tournamentId, participantId) => {
try {
const url = `/tournaments/${tournamentId}/participants/${participantId}/undo_check_in`;
const response = await challongeApi.post(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Deletes or deactivates a participant in a tournament.
* If the tournament has not started, the participant is deleted, and the abandoned seed number is filled in.
* If the tournament is underway, the participant is marked inactive, forfeiting their remaining matches.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} participantId - The participant's unique ID.
* @returns {Promise<Object>} - A promise resolving to the response data.
* @throws {Error} If the request fails or the API returns an error.
*/
const deleteParticipant = async (tournamentId, participantId) => {
try {
const url = `/tournaments/${tournamentId}/participants/${participantId}`;
const response = await challongeApi.delete(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Deletes all participants in a tournament.
* This action is only allowed if the tournament hasn't started yet.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @returns {Promise<Object>} - A promise resolving to the response data.
* @throws {Error} If the request fails or the API returns an error.
*/
const clearParticipants = async tournamentId => {
try {
const url = `/tournaments/${tournamentId}/participants/clear`;
const response = await challongeApi.delete(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Randomizes seeds among participants in a tournament.
* This action is only applicable before the tournament has started.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @returns {Promise<Object>} - A promise resolving to the response data.
* @throws {Error} If the request fails or the API returns an error.
*/
const randomizeParticipants = async tournamentId => {
try {
const url = `/tournaments/${tournamentId}/participants/randomize`;
const response = await challongeApi.post(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
// Matches API
/**
* Retrieves a tournament's match list.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {Object} [params] - Optional query parameters for filtering matches.
* @param {string} [params.state] - Filter by match state ('all', 'pending', 'open', 'complete').
* @param {string} [params.participant_id] - Only retrieve matches that include the specified participant.
* @returns {Promise<Object>} - A promise resolving to the list of matches.
* @throws {Error} If the request fails or the API returns an error.
*/
const getMatches = async (tournamentId, params = {}) => {
try {
const url = `/tournaments/${tournamentId}/matches`;
const response = await challongeApi.get(url, { params });
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Retrieves a single match record for a tournament.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} matchId - The match's unique ID.
* @param {Object} [options] - Optional parameters for the request.
* @param {boolean} [options.includeAttachments=false] - Whether to include an array of associated attachment records.
* @returns {Promise<Object>} - A promise resolving to the match data.
* @throws {Error} If the request fails or the API returns an error.
*/
const getMatch = async (tournamentId, matchId, options = {}) => {
try {
const url = `/tournaments/${tournamentId}/matches/${matchId}`;
const response = await challongeApi.get(url, {
params: {
include_attachments: options.includeAttachments || false
}
});
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Updates or submits the score(s) for a match.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} matchId - The match's unique ID.
* @param {Object} data - The match data to update.
* @param {string} [data.scores_csv] - Comma-separated set/game scores with player 1 score first (e.g., "1-3,3-0,3-2").
* @param {string} [data.winner_id] - The participant ID of the winner or "tie" if applicable (Round Robin and Swiss).
* NOTE: If you change the outcome of a completed match, all matches in the bracket
* that branch from the updated match will be reset.
* @param {number} [data.player1_votes] - Overwrites the number of votes for player 1.
* @param {number} [data.player2_votes] - Overwrites the number of votes for player 2.
* @returns {Promise<Object>} - A promise resolving to the updated match data.
* @throws {Error} If the request fails or the API returns an error.
*/
const updateMatch = async (tournamentId, matchId, data) => {
try {
const url = `/tournaments/${tournamentId}/matches/${matchId}`;
const response = await challongeApi.put(url, { match: data });
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Reopens a match that was marked completed, automatically resetting matches that follow it.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} matchId - The match's unique ID.
* @returns {Promise<Object>} - A promise resolving to the updated match data.
* @throws {Error} If the request fails or the API returns an error.
*/
const reopenMatch = async (tournamentId, matchId) => {
try {
const url = `/tournaments/${tournamentId}/matches/${matchId}/reopen`;
const response = await challongeApi.post(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Marks a match as underway.
* Sets "underway_at" to the current time and highlights the match in the bracket.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} matchId - The match's unique ID.
* @returns {Promise<Object>} - A promise resolving to the updated match data.
* @throws {Error} If the request fails or the API returns an error.
*/
const markMatchAsUnderway = async (tournamentId, matchId) => {
try {
const url = `/tournaments/${tournamentId}/matches/${matchId}/mark_as_underway`;
const response = await challongeApi.post(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Unmarks a match as underway.
* Clears "underway_at" and unhighlights the match in the bracket.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} matchId - The match's unique ID.
* @returns {Promise<Object>} - A promise resolving to the updated match data.
* @throws {Error} If the request fails or the API returns an error.
*/
const unmarkMatchAsUnderway = async (tournamentId, matchId) => {
try {
const url = `/tournaments/${tournamentId}/matches/${matchId}/unmark_as_underway`;
const response = await challongeApi.post(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
// Match Attachments API
/**
* Retrieves a match's attachments.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} matchId - The match's unique ID.
* @returns {Promise<Object>} - A promise resolving to the list of match attachments.
* @throws {Error} If the request fails or the API returns an error.
*/
const getMatchAttachments = async (tournamentId, matchId) => {
try {
const url = `/tournaments/${tournamentId}/matches/${matchId}/attachments`;
const response = await challongeApi.get(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Creates a match attachment by adding a file, link, or text attachment to a match.
* NOTE: The associated tournament's "accept_attachments" attribute must be true for this action to succeed.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} matchId - The match's unique ID.
* @param {Object} data - The attachment data.
* @param {File} [data.asset] - A file upload (250KB max, no more than 4 attachments per match). If provided, the url parameter will be ignored.
* @param {string} [data.url] - A web URL.
* @param {string} [data.description] - Text to describe the file or URL attachment, or this can simply be standalone text.
* At least one of `asset`, `url`, or `description` must be provided.
* @returns {Promise<Object>} - A promise resolving to the created match attachment data.
* @throws {Error} If the request fails or the API returns an error.
*/
const createMatchAttachment = async (tournamentId, matchId, data) => {
try {
const url = `/tournaments/${tournamentId}/matches/${matchId}/attachments`;
const response = await challongeApi.post(url, { match_attachment: data });
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Retrieves a single match attachment record.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} matchId - The match's unique ID.
* @param {string} attachmentId - The attachment's unique ID.
* @returns {Promise<Object>} - A promise resolving to the match attachment data.
* @throws {Error} If the request fails or the API returns an error.
*/
const getMatchAttachment = async (tournamentId, matchId, attachmentId) => {
try {
const url = `/tournaments/${tournamentId}/matches/${matchId}/attachments/${attachmentId}`;
const response = await challongeApi.get(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Updates the attributes of a match attachment.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} matchId - The match's unique ID.
* @param {string} attachmentId - The attachment's unique ID.
* @param {Object} data - The attachment data to update.
* @param {File} [data.asset] - A file upload (250KB max, no more than 4 attachments per match). If provided, the url parameter will be ignored.
* @param {string} [data.url] - A web URL.
* @param {string} [data.description] - Text to describe the file or URL attachment, or this can simply be standalone text.
* At least one of `asset`, `url`, or `description` must be provided.
* @returns {Promise<Object>} - A promise resolving to the updated match attachment data.
* @throws {Error} If the request fails or the API returns an error.
*/
const updateMatchAttachment = async (
tournamentId,
matchId,
attachmentId,
data
) => {
try {
const url = `/tournaments/${tournamentId}/matches/${matchId}/attachments/${attachmentId}`;
const response = await challongeApi.put(url, { match_attachment: data });
return response.data;
} catch (error) {
return handleError(error);
}
};
/**
* Deletes a match attachment.
*
* @param {string} tournamentId - The tournament ID (e.g., 10230) or URL (e.g., 'single_elim' for challonge.com/single_elim).
* If assigned to a subdomain, the URL format must be :subdomain-:tournament_url
* (e.g., 'test-mytourney' for test.challonge.com/mytourney).
* @param {string} matchId - The match's unique ID.
* @param {string} attachmentId - The attachment's unique ID.
* @returns {Promise<Object>} - A promise resolving to the response data.
* @throws {Error} If the request fails or the API returns an error.
*/
const deleteMatchAttachment = async (tournamentId, matchId, attachmentId) => {
try {
const url = `/tournaments/${tournamentId}/matches/${matchId}/attachments/${attachmentId}`;
const response = await challongeApi.delete(url);
return response.data;
} catch (error) {
return handleError(error);
}
};
module.exports = {
listTournaments,
createTournament,
getTournament,
updateTournament,
deleteTournament,
processCheckIns,
abortCheckIn,
startTournament,
finalizeTournament,
resetTournament,
openForPredictions,
getParticipants,
addParticipant,
bulkAddParticipants,
getParticipant,
updateParticipant,
checkInParticipant,
undoCheckInParticipant,
deleteParticipant,
clearParticipants,
randomizeParticipants,
getMatches,
getMatch,
updateMatch,
reopenMatch,
markMatchAsUnderway,
unmarkMatchAsUnderway,
getMatchAttachments,
createMatchAttachment,
getMatchAttachment,
updateMatchAttachment,
deleteMatchAttachment
};

View File

@@ -0,0 +1,114 @@
const {
listTournaments,
createTournament,
getTournament,
updateTournament,
deleteTournament,
processCheckIns,
abortCheckIn,
startTournament,
finalizeTournament,
resetTournament,
openForPredictions,
getParticipants,
addParticipant,
bulkAddParticipants,
getParticipant,
updateParticipant,
checkInParticipant,
undoCheckInParticipant,
deleteParticipant,
clearParticipants,
randomizeParticipants,
getMatches,
getMatch,
updateMatch,
reopenMatch,
markMatchAsUnderway,
unmarkMatchAsUnderway,
getMatchAttachments,
createMatchAttachment,
getMatchAttachment,
updateMatchAttachment,
deleteMatchAttachment
} = require('./challonge');
const axios = require('axios');
jest.mock('axios');
describe('Challonge API', () => {
afterEach(() => {
jest.clearAllMocks();
});
describe('listTournaments', () => {
it('should fetch a list of tournaments with default parameters', async () => {
const mockResponse = {
data: [
{ id: 1, name: 'Tournament 1' },
{ id: 2, name: 'Tournament 2' }
]
};
axios.get.mockResolvedValueOnce(mockResponse);
const result = await listTournaments();
expect(axios.get).toHaveBeenCalledWith('/tournaments', {
params: {}
});
expect(result).toEqual(mockResponse.data);
});
it('should fetch a list of tournaments with provided parameters', async () => {
const params = { state: 'in_progress', type: 'single_elimination' };
const mockResponse = { data: [{ id: 3, name: 'Tournament 3' }] };
axios.get.mockResolvedValueOnce(mockResponse);
const result = await listTournaments(params);
expect(axios.get).toHaveBeenCalledWith('/tournaments.json', { params });
expect(result).toEqual(mockResponse.data);
});
it('should handle errors when fetching tournaments', async () => {
const mockError = new Error('Network Error');
axios.get.mockRejectedValueOnce(mockError);
await expect(listTournaments()).rejects.toThrow('Network Error');
expect(axios.get).toHaveBeenCalledWith('/tournaments.json', {
params: {}
});
});
});
// createTournament;
// getTournament;
// updateTournament;
// deleteTournament;
// processCheckIns;
// abortCheckIn;
// startTournament;
// finalizeTournament;
// resetTournament;
// openForPredictions;
// getParticipants;
// addParticipant;
// bulkAddParticipants;
// getParticipant;
// updateParticipant;
// checkInParticipant;
// undoCheckInParticipant;
// deleteParticipant;
// clearParticipants;
// randomizeParticipants;
// getMatches;
// getMatch;
// updateMatch;
// reopenMatch;
// markMatchAsUnderway;
// unmarkMatchAsUnderway;
// getMatchAttachments;
// createMatchAttachment;
// getMatchAttachment;
// updateMatchAttachment;
// deleteMatchAttachment;
});

View File

@@ -0,0 +1,995 @@
Challonge API v1 Documentation
The Challonge API expands tournament creation and control to the programmatic level. You can create tournaments on the fly and report scores directly from your application. This allows you to define score reporting permissions that fit your user model, and provide a more seamless tournament experience for your users.
The API is accessible over a secure connection at https://api.challonge.com/v1/
________________
Authentication
All interactions with the API require a Challonge account with a verified email address and API key. You can generate one from your developer settings page. We support HTTP basic authentication. Username = your Challonge username, Password = your API key. Many clients format these requests as: https://username:api-key@api.challonge.com/v1/... Or, if you prefer, you can just pass your API key as parameter api_key to all method calls.
API methods with GET request types are permitted for any tournament, whether belonging to you or not. All other API methods are scoped to tournaments that you either own or have admin access to.
________________
Response Formats
XML or JSON. The extension in your request indicates your desired response. e.g. https://api.challonge.com/v1/tournaments.xml or https://api.challonge.com/v1/tournaments.json - you may also set your request headers to accept application/json, text/xml or application/xml
________________
Response Codes
The following HTTP response codes are issued by the API. All other codes are the result of a request not reaching the application.
* 200- OK
* 401- Unauthorized (Invalid API key or insufficient permissions)
* 404- Object not found within your account scope
* 406- Requested format is not supported - request JSON or XML only
* 422- Validation error(s) for create or update method
* 500- Something went wrong on our end. If you continually receive this, please contact us.
________________
Validation Errors
Requests that complete but have validation errors or other issues will return an array of error messages and status code 422. e.g.:
* XML
* JSON
{
"errors": [
"Name can't be blank",
"URL can't be blank"
]
}
________________
REST API Methods
Please note, two-stage tournaments are not yet supported by our public API. They'll be available in V2 along with 3+ participant per match support.
Tournaments
Index
GET
Retrieve a set of tournaments created with your account.
Create
POST
Create a new tournament.
Show
GET
Retrieve a single tournament record created with your account.
Update
PUT
Update a tournament's attributes.
Destroy
DELETE
Deletes a tournament along with all its associated records. There is no undo, so use with care!
Process Check-ins
POST
This should be invoked after a tournament's check-in window closes before the tournament is started.
1. Marks participants who have not checked in as inactive.
2. Moves inactive participants to bottom seeds (ordered by original seed).
3. Transitions the tournament state from 'checking_in' to 'checked_in'
NOTE: Checked in participants on the waiting list will be promoted if slots become available.
Abort Check-in
POST
When your tournament is in a 'checking_in' or 'checked_in' state, there's no way to edit the tournament's start time (start_at) or check-in duration (check_in_duration). You must first abort check-in, then you may edit those attributes.
1. Makes all participants active and clears their checked_in_at times.
2. Transitions the tournament state from 'checking_in' or 'checked_in' to 'pending'
Start
POST
Start a tournament, opening up first round matches for score reporting. The tournament must have at least 2 participants.
Finalize
POST
Finalize a tournament that has had all match scores submitted, rendering its results permanent.
Reset
POST
Reset a tournament, clearing all of its scores and attachments. You can then add/remove/edit participants before starting the tournament again.
Open for predictions
POST
Sets the state of the tournament to start accepting predictions. Your tournament's 'prediction_method' attribute must be set to 1 (exponential scoring) or 2 (linear scoring) to use this option. Note: Once open for predictions, match records will be persisted, so participant additions and removals will no longer be permitted.
Participants
Index
GET
Retrieve a tournament's participant list.
Create
POST
Add a participant to a tournament (up until it is started).
Bulk Add
POST
Bulk add participants to a tournament (up until it is started). If an invalid participant is detected, bulk participant creation will halt and any previously added participants (from this API request) will be rolled back.
Show
GET
Retrieve a single participant record for a tournament.
Update
PUT
Update the attributes of a tournament participant.
Check in
POST
Checks a participant in, setting checked_in_at to the current time.
Undo Check In
POST
Marks a participant as having not checked in, setting checked_in_at to nil.
Destroy
DELETE
If the tournament has not started, delete a participant, automatically filling in the abandoned seed number. If tournament is underway, mark a participant inactive, automatically forfeiting his/her remaining matches.
Clear
DELETE
Deletes all participants in a tournament. (Only allowed if tournament hasn't started yet)
Randomize
POST
Randomize seeds among participants. Only applicable before a tournament has started.
Matches
Index
GET
Retrieve a tournament's match list.
Show
GET
Retrieve a single match record for a tournament.
Update
PUT
Update/submit the score(s) for a match.
Reopen
POST
Reopens a match that was marked completed, automatically resetting matches that follow it
Mark as underway
POST
Sets "underway_at" to the current time and highlights the match in the bracket
Unmark as underway
POST
Clears "underway_at" and unhighlights the match in the bracket
Match Attachments
Index
GET
Retrieve a match's attachments.
Create
POST
Add a file, link, or text attachment to a match. NOTE: The associated tournament's "accept_attachments" attribute must be true for this action to succeed.
Show
GET
Retrieve a single match attachment record.
Update
PUT
Update the attributes of a match attachment.
Destroy
DELETE
Delete a match attachment.
Tournaments API Calls
List tournaments (index)
Retrieve a set of tournaments created with your account.
________________
URL
GET https://api.challonge.com/v1/tournaments.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
state
all, pending, in_progress, ended
type
single_elimination, double_elimination, round_robin, swiss
created_after
YYYY-MM-DD
created_before
YYYY-MM-DD
subdomain
A Challonge subdomain you've published tournaments to. NOTE: Until v2 of our API, the subdomain parameter is required to retrieve a list of your organization-hosted tournaments.
Create a tournament
Create a new tournament.
________________
URL
POST https://api.challonge.com/v1/tournaments.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
tournament[name]
Your event's name/title (Max: 60 characters)
tournament[tournament_type]
Single elimination (default), double elimination, round robin, swiss
tournament[url]
challonge.com/url (letters, numbers, and underscores only); when blank on create, a random URL will be generated for you
tournament[subdomain]
subdomain.challonge.com/url (Requires write access to the specified subdomain)
tournament[description]
Description/instructions to be displayed above the bracket
tournament[open_signup]
True or false. Have Challonge host a sign-up page (otherwise, you manually add all participants)
tournament[hold_third_place_match]
True or false - Single Elimination only. Include a match between semifinal losers? (default: false)
tournament[pts_for_match_win]
Decimal (to the nearest tenth) - Swiss only - default: 1.0
tournament[pts_for_match_tie]
Decimal (to the nearest tenth) - Swiss only - default: 0.5
tournament[pts_for_game_win]
Decimal (to the nearest tenth) - Swiss only - default: 0.0
tournament[pts_for_game_tie]
Decimal (to the nearest tenth) - Swiss only - default: 0.0
tournament[pts_for_bye]
Decimal (to the nearest tenth) - Swiss only - default: 1.0
tournament[swiss_rounds]
Integer - Swiss only - We recommend limiting the number of rounds to less than two-thirds the number of players. Otherwise, an impossible pairing situation can be reached and your tournament may end before the desired number of rounds are played.
tournament[ranked_by]
One of the following: 'match wins', 'game wins', 'points scored', 'points difference', 'custom' Help
tournament[rr_pts_for_match_win]
Decimal (to the nearest tenth) - Round Robin "custom only" - default: 1.0
tournament[rr_pts_for_match_tie]
Decimal (to the nearest tenth) - Round Robin "custom" only - default: 0.5
tournament[rr_pts_for_game_win]
Decimal (to the nearest tenth) - Round Robin "custom" only - default: 0.0
tournament[rr_pts_for_game_tie]
Decimal (to the nearest tenth) - Round Robin "custom" only - default: 0.0
tournament[accept_attachments]
True or false - Allow match attachment uploads (default: false)
tournament[hide_forum]
True or false - Hide the forum tab on your Challonge page (default: false)
tournament[show_rounds]
True or false - Single &amp; Double Elimination only - Label each round above the bracket (default: false)
tournament[private]
True or false - Hide this tournament from the public browsable index and your profile (default: false)
tournament[notify_users_when_matches_open]
True or false - Email registered Challonge participants when matches open up for them (default: false)
tournament[notify_users_when_the_tournament_ends]
True or false - Email registered Challonge participants the results when this tournament ends (default: false)
tournament[sequential_pairings]
True or false - Instead of traditional seeding rules, make pairings by going straight down the list of participants. First round matches are filled in top to bottom, then qualifying matches (if applicable). (default: false)
tournament[signup_cap]
Integer - Maximum number of participants in the bracket. A waiting list (attribute on Participant) will capture participants once the cap is reached.
tournament[start_at]
Datetime - the planned or anticipated start time for the tournament (Used with check_in_duration to determine participant check-in window). Timezone defaults to Eastern.
tournament[check_in_duration]
Integer - Length of the participant check-in window in minutes.
tournament[grand_finals_modifier]
String - This option only affects double elimination. null/blank (default) - give the winners bracket finalist two chances to beat the losers bracket finalist, 'single match' - create only one grand finals match, 'skip' - don't create a finals match between winners and losers bracket finalists
Get a tournament (show)
Retrieve a single tournament record created with your account.
________________
URL
GET https://api.challonge.com/v1/tournaments/{tournament}.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
include_participants
0 or 1; includes an array of associated participant records
include_matches
0 or 1; includes an array of associated match records
Update a tournament
Update a tournament's attributes.
________________
URL
PUT Help https://api.challonge.com/v1/tournaments/{tournament}.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
tournament[name]
Your event's name/title (Max: 60 characters)
tournament[tournament_type]
Single elimination (default), double elimination, round robin, swiss
tournament[url]
challonge.com/url (letters, numbers, and underscores only); when blank on create, a random URL will be generated for you
tournament[subdomain]
subdomain.challonge.com/url (Requires write access to the specified subdomain)
tournament[description]
Description/instructions to be displayed above the bracket
tournament[open_signup]
True or false. Have Challonge host a sign-up page (otherwise, you manually add all participants)
tournament[hold_third_place_match]
True or false - Single Elimination only. Include a match between semifinal losers? (default: false)
tournament[pts_for_match_win]
Decimal (to the nearest tenth) - Swiss only - default: 1.0
tournament[pts_for_match_tie]
Decimal (to the nearest tenth) - Swiss only - default: 0.5
tournament[pts_for_game_win]
Decimal (to the nearest tenth) - Swiss only - default: 0.0
tournament[pts_for_game_tie]
Decimal (to the nearest tenth) - Swiss only - default: 0.0
tournament[pts_for_bye]
Decimal (to the nearest tenth) - Swiss only - default: 1.0
tournament[swiss_rounds]
Integer - Swiss only - We recommend limiting the number of rounds to less than two-thirds the number of players. Otherwise, an impossible pairing situation can be reached and your tournament may end before the desired number of rounds are played.
tournament[ranked_by]
One of the following: 'match wins', 'game wins', 'points scored', 'points difference', 'custom' Help
tournament[rr_pts_for_match_win]
Decimal (to the nearest tenth) - Round Robin "custom only" - default: 1.0
tournament[rr_pts_for_match_tie]
Decimal (to the nearest tenth) - Round Robin "custom" only - default: 0.5
tournament[rr_pts_for_game_win]
Decimal (to the nearest tenth) - Round Robin "custom" only - default: 0.0
tournament[rr_pts_for_game_tie]
Decimal (to the nearest tenth) - Round Robin "custom" only - default: 0.0
tournament[accept_attachments]
True or false - Allow match attachment uploads (default: false)
tournament[hide_forum]
True or false - Hide the forum tab on your Challonge page (default: false)
tournament[show_rounds]
True or false - Single &amp; Double Elimination only - Label each round above the bracket (default: false)
tournament[private]
True or false - Hide this tournament from the public browsable index and your profile (default: false)
tournament[notify_users_when_matches_open]
True or false - Email registered Challonge participants when matches open up for them (default: false)
tournament[notify_users_when_the_tournament_ends]
True or false - Email registered Challonge participants the results when this tournament ends (default: false)
tournament[sequential_pairings]
True or false - Instead of traditional seeding rules, make pairings by going straight down the list of participants. First round matches are filled in top to bottom, then qualifying matches (if applicable). (default: false)
tournament[signup_cap]
Integer - Maximum number of participants in the bracket. A waiting list (attribute on Participant) will capture participants once the cap is reached.
tournament[start_at]
Datetime - the planned or anticipated start time for the tournament (Used with check_in_duration to determine participant check-in window). Timezone defaults to Eastern.
tournament[check_in_duration]
Integer - Length of the participant check-in window in minutes.
tournament[grand_finals_modifier]
String - This option only affects double elimination. null/blank (default) - give the winners bracket finalist two chances to beat the losers bracket finalist, 'single match' - create only one grand finals match, 'skip' - don't create a finals match between winners and losers bracket finalists
Delete a tournament
Deletes a tournament along with all its associated records. There is no undo, so use with care!
________________
URL
DELETE Help https://api.challonge.com/v1/tournaments/{tournament}.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Process check-in results for a tournament
This should be invoked after a tournament's check-in window closes before the tournament is started.
1. Marks participants who have not checked in as inactive.
2. Moves inactive participants to bottom seeds (ordered by original seed).
3. Transitions the tournament state from 'checking_in' to 'checked_in'
NOTE: Checked in participants on the waiting list will be promoted if slots become available.
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/process_check_ins.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
include_participants
0 or 1; includes an array of associated participant records
include_matches
0 or 1; includes an array of associated match records
Abort check-in for a tournament
When your tournament is in a 'checking_in' or 'checked_in' state, there's no way to edit the tournament's start time (start_at) or check-in duration (check_in_duration). You must first abort check-in, then you may edit those attributes.
1. Makes all participants active and clears their checked_in_at times.
2. Transitions the tournament state from 'checking_in' or 'checked_in' to 'pending'
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/abort_check_in.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
include_participants
0 or 1; includes an array of associated participant records
include_matches
0 or 1; includes an array of associated match records
Start a tournament
Start a tournament, opening up first round matches for score reporting. The tournament must have at least 2 participants.
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/start.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
include_participants
0 or 1; includes an array of associated participant records
include_matches
0 or 1; includes an array of associated match records
Finalize a tournament
Finalize a tournament that has had all match scores submitted, rendering its results permanent.
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/finalize.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
include_participants
0 or 1; includes an array of associated participant records
include_matches
0 or 1; includes an array of associated match records
Reset a tournament
Reset a tournament, clearing all of its scores and attachments. You can then add/remove/edit participants before starting the tournament again.
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/reset.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
include_participants
0 or 1; includes an array of associated participant records
include_matches
0 or 1; includes an array of associated match records
Open the tournament for predictions
Sets the state of the tournament to start accepting predictions. Your tournament's 'prediction_method' attribute must be set to 1 (exponential scoring) or 2 (linear scoring) to use this option. Note: Once open for predictions, match records will be persisted, so participant additions and removals will no longer be permitted.
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/open_for_predictions.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
include_participants
0 or 1; includes an array of associated participant records
include_matches
0 or 1; includes an array of associated match records
PArticipant API Calls
List a tournament's participants (index)
Retrieve a tournament's participant list.
________________
URL
GET https://api.challonge.com/v1/tournaments/{tournament}/participants.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Create a participant
Add a participant to a tournament (up until it is started).
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/participants.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
participant[name]
The name displayed in the bracket/schedule - not required if email or challonge_username is provided. Must be unique per tournament.
participant[challonge_username]
Provide this if the participant has a Challonge account. He or she will be invited to the tournament.
participant[email]
Providing this will first search for a matching Challonge account. If one is found, this will have the same effect as the "challonge_username" attribute. If one is not found, the "new-user-email" attribute will be set, and the user will be invited via email to create an account.
participant[seed]
integer - The participant's new seed. Must be between 1 and the current number of participants (including the new record). Overwriting an existing seed will automatically bump other participants as you would expect.
participant[misc]
string - Max: 255 characters. Multi-purpose field that is only visible via the API and handy for site integration (e.g. key to your users table)
Bulk create participants
Bulk add participants to a tournament (up until it is started). If an invalid participant is detected, bulk participant creation will halt and any previously added participants (from this API request) will be rolled back.
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/participants/bulk_add.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
participants[][name]
The name displayed in the bracket/schedule - not required if email or challonge_username is provided. Must be unique per tournament.
participants[][invite_name_or_email]
Username can be provided if the participant has a Challonge account. Providing email will first search for a matching Challonge account. If one is found, the user will be invited. If not, the "new-user-email" attribute will be set, and the user will be invited via email to create an account.
participants[][seed]
integer - The participant's new seed. Must be between 1 and the current number of participants (including the new record). Overwriting an existing seed will automatically bump other participants as you would expect.
participants[][misc]
string - Max: 255 characters. Multi-purpose field that is only visible via the API and handy for site integration (e.g. key to your users table)
Get a participant (show)
Retrieve a single participant record for a tournament.
________________
URL
GET https://api.challonge.com/v1/tournaments/{tournament}/participants/{participant_id}.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{participant_id} (in URL string)
The participant's unique ID
include_matches
0 or 1; includes an array of associated match records
Update a participant
Update the attributes of a tournament participant.
________________
URL
PUT Help https://api.challonge.com/v1/tournaments/{tournament}/participants/{participant_id}.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{participant_id} (in URL string)
The participant's unique ID
participant[name]
The name displayed in the bracket/schedule - not required if email or challonge_username is provided. Must be unique per tournament.
participant[challonge_username]
Provide this if the participant has a Challonge account. He or she will be invited to the tournament.
participant[email]
Providing this will first search for a matching Challonge account. If one is found, this will have the same effect as the "challonge_username" attribute. If one is not found, the "new-user-email" attribute will be set, and the user will be invited via email to create an account.
participant[seed]
integer - The participant's new seed. Must be between 1 and the current number of participants (including the new record). Overwriting an existing seed will automatically bump other participants as you would expect.
participant[misc]
string - Max: 255 characters. Multi-purpose field that is only visible via the API and handy for site integration (e.g. key to your users table)
Check in a participant
Checks a participant in, setting checked_in_at to the current time.
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/participants/{participant_id}/check_in.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{participant_id} (in URL string)
The participant's unique ID
Undo check-in for a participant
Marks a participant as having not checked in, setting checked_in_at to nil.
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/participants/{participant_id}/undo_check_in.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{participant_id} (in URL string)
The participant's un
Delete/deactivate a participant
If the tournament has not started, delete a participant, automatically filling in the abandoned seed number. If tournament is underway, mark a participant inactive, automatically forfeiting his/her remaining matches.
________________
URL
DELETE Help https://api.challonge.com/v1/tournaments/{tournament}/participants/{participant_id}.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{participant_id} (in URL string)
The participant'
Clear/delete all participants
Deletes all participants in a tournament. (Only allowed if tournament hasn't started yet)
________________
URL
DELETE Help https://api.challonge.com/v1/tournaments/{tournament}/participants/clear.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Randomize a tournament's participants
Randomize seeds among participants. Only applicable before a tournament has started.
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/participants/randomize.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Match API Calls
List a tournament's matches (index)
Retrieve a tournament's match list.
________________
URL
GET https://api.challonge.com/v1/tournaments/{tournament}/matches.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
state
all (default), pending, open, complete
participant_id
Only retrieve matches that include the specified participant.
Get a match (show)
Retrieve a single match record for a tournament.
________________
URL
GET https://api.challonge.com/v1/tournaments/{tournament}/matches/{match_id}.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{match_id} (in URL string)
The match's unique ID
include_attachments
0 or 1; include an array of associated attachment records
Update a match
Update/submit the score(s) for a match.
________________
URL
PUT Help https://api.challonge.com/v1/tournaments/{tournament}/matches/{match_id}.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{match_id} (in URL string)
The match's unique ID
match[scores_csv]
Comma separated set/game scores with player 1 score first (e.g. "1-3,3-0,3-2")
match[winner_id]
The participant ID of the winner or "tie" if applicable (Round Robin and Swiss). NOTE: If you change the outcome of a completed match, all matches in the bracket that branch from the updated match will be reset.
match[player1_votes]
Overwrites the number of votes for player 1
match[player2_votes]
Overwrites the number of votes for player 2
* If you're updating winner_id, scores_csv must also be provided. You may, however, update score_csv without providing winner_id for live score updates.
Reopen a match
Reopens a match that was marked completed, automatically resetting matches that follow it
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/matches/{match_id}/reopen.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{match_id} (in URL string)
The match's unique ID
Mark a match as underway
Sets "underway_at" to the current time and highlights the match in the bracket
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/matches/{match_id}/mark_as_underway.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{match_id} (in URL string)
The match's unique ID
Unmark a match as underway
Clears "underway_at" and unhighlights the match in the bracket
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/matches/{match_id}/unmark_as_underway.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{match_id} (in URL string)
The match's unique ID
Attachment API Calls
List a match's attachments (index)
Retrieve a match's attachments.
________________
URL
GET https://api.challonge.com/v1/tournaments/{tournament}/matches/{match_id}/attachments.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{match_id} (in URL string)
The match's
Create a match attachment
Add a file, link, or text attachment to a match. NOTE: The associated tournament's "accept_attachments" attribute must be true for this action to succeed.
________________
URL
POST https://api.challonge.com/v1/tournaments/{tournament}/matches/{match_id}/attachments.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{match_id} (in URL string)
The match's unique ID
match_attachment[asset]
A file upload (250KB max, no more than 4 attachments per match). If provided, the url parameter will be ignored.
match_attachment[url]
A web URL
match_attachment[description]
Text to describe the file or URL attachment, or this can simply be standalone text.
* At least 1 of the 3 optional parameters must be provided.
* Files up to 25MB are allowed for tournaments hosted by Premier badge Challonge Premier subscribers.
Get a match attachment (show)
Retrieve a single match attachment record.
________________
URL
GET https://api.challonge.com/v1/tournaments/{tournament}/matches/{match_id}/attachments/{attachment_id}.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{match_id} (in URL string)
The match's unique ID
Required
{attachment_id} (in URL string)
The attachment's unique ID
Update a match attachment
Update the attributes of a match attachment.
________________
URL
PUT Help https://api.challonge.com/v1/tournaments/{tournament}/matches/{match_id}/attachments/{attachment_id}.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{match_id} (in URL string)
The match's unique ID
match_attachment[asset]
A file upload (250KB max, no more than 4 attachments per match). If provided, the url parameter will be ignored.
match_attachment[url]
A web URL
match_attachment[description]
Text to describe the file or URL attachment, or this can simply be standalone text.
* At least 1 of the 3 optional parameters must be provided.
* Files up to 25MB are allowed for tournaments hosted by Premier badge Challonge Premier subscribers.
Delete a match attachment
Delete a match attachment.
________________
URL
DELETE Help https://api.challonge.com/v1/tournaments/{tournament}/matches/{match_id}/attachments/{attachment_id}.{json|xml}
________________
Parameters
Name
Description
Required
api_key
Your API key (required unless you're using HTTP basic authentication)
Required
{tournament} (in URL string)
Tournament ID (e.g. 10230) or URL (e.g. 'single_elim' for challonge.com/single_elim). If assigned to a subdomain, URL format must be :subdomain-:tournament_url (e.g. 'test-mytourney' for test.challonge.com/mytourney)
Required
{match_id} (in URL string)
The match's unique ID
Required
{attachment_id} (in URL string)
The attachment's unique ID

View File

@@ -0,0 +1,7 @@
const EPHEMERAL_MESSAGE_DURATION_MILLISECS = 5000;
const CHALLONGE_API_BASE_URL = 'https://api.challonge.com/v1/';
module.exports = {
EPHEMERAL_MESSAGE_DURATION_MILLISECS,
CHALLONGE_API_BASE_URL
};

View File

@@ -0,0 +1,68 @@
const EXPECTED_HEADERS = [
'player_id',
'first_name',
'last_name',
'country_code',
'division',
'screenname',
'email',
'tournament_id'
];
/**
* Normalize a screenname for reliable matching.
*/
const normalizeScreenname = name =>
name?.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
/**
* Validate CSV headers.
*/
const validateCsvHeaders = headers => {
if (!headers) throw new Error('CSV file is missing headers.');
if (headers.length !== EXPECTED_HEADERS.length) {
throw new Error(
`Invalid CSV file headers: Expected ${EXPECTED_HEADERS.length} headers but found ${headers.length}.`
);
}
const missingHeaders = EXPECTED_HEADERS.filter(h => !headers.includes(h));
if (missingHeaders.length) {
throw new Error(
`Invalid CSV file headers: Missing the following headers: ${missingHeaders.join(', ')}.`
);
}
};
/**
* Parse CSV data into an object keyed by screenname.
*/
const parseCsv = csvData => {
const rows = csvData
.split('\n')
.map(row => row.split(','))
.filter(row => row.some(cell => cell.trim() !== ''));
const headers = rows[0].map(header => header.trim());
validateCsvHeaders(headers);
for (let i = 1; i < rows.length; i++) {
if (rows[i].length !== EXPECTED_HEADERS.length) {
throw new Error(`Invalid row format at line ${i + 1}.`);
}
}
return rows.slice(1).reduce((acc, row) => {
const participant = {};
EXPECTED_HEADERS.forEach((header, idx) => {
participant[header] = row[idx];
});
acc[participant.screenname] = participant;
return acc;
}, {});
};
module.exports = {
normalizeScreenname,
validateCsvHeaders,
parseCsv,
EXPECTED_HEADERS
};

View File

@@ -0,0 +1,63 @@
const fs = require('fs');
const path = require('path');
const saveResponseToJson = require('../log-output-to-json.js');
const gamemasterFilePath = path.join(__dirname, `gamemaster/latest.json`);
const gamemaster = JSON.parse(fs.readFileSync(gamemasterFilePath, 'utf8'));
const regionCheck = ['alola', 'galarian', 'hisuian', 'paldea'];
const { pokemon, moves } = gamemaster.reduce(
(acc, item) => {
const templateId = item.templateId;
// POKEMON FILTER
// IF the templateId begins with 'V'
// AND the templateId includes the word 'pokemon'
if (
templateId.startsWith('V') &&
templateId.toLowerCase().includes('pokemon')
) {
const pokemonSettings = item.data?.pokemonSettings;
const pokemonId = pokemonSettings?.pokemonId;
if (
// If the acc.seen has the pokemonId
// OR if the acc.see has the pokemon id AND the pokemonSettings.form contains a keyword from the regionCheck array
!acc.pokemonSeen.has(pokemonId) ||
(acc.pokemonSeen.has(pokemonId) &&
regionCheck.includes(
pokemonSettings?.form?.split('_')[1].toLowerCase()
))
) {
acc.pokemonSeen.add(pokemonId); // Mark pokemonId as seen
acc.pokemon.push(item); // Add the item to the pokemon acc array
}
}
// POKEMON MOVE FILTER
if (
templateId.startsWith('V') &&
templateId.toLowerCase().includes('move')
) {
const moveSettings = item.data?.moveSettings;
const moveId = moveSettings?.movementId;
if (!acc.pokemonSeen.has(moveId)) {
acc.moveSeen.add(moveId); // Mark pokemonId as seen
acc.moves.push(item); // Add the item to the pokemon acc array
}
}
return acc;
},
{ pokemon: [], pokemonSeen: new Set(), moves: [], moveSeen: new Set() }
);
saveResponseToJson({
response: pokemon,
filename: 'pokemon.json',
savePath: path.resolve(__dirname, 'gamemaster')
});
saveResponseToJson({
response: moves,
filename: 'pokemon-moves.json',
savePath: path.resolve(__dirname, 'gamemaster')
});
// console.log(AllPokemon);

View File

@@ -0,0 +1,40 @@
const fs = require('fs');
const path = require('path');
const simpleGit = require('simple-git');
const REPO_URL = 'https://github.com/PokeMiners/game_masters.git';
const TEMP_DIR = path.join(__dirname, 'temp-repo');
const TARGET_FILES = ['latest/latest.json'];
const OUTPUT_FILE = path.join(`${__dirname}/gamemaster/`, 'latest.json'); // File to expose in the package
(async () => {
const git = simpleGit();
try {
// Clone the repository into a temporary directory
console.log('Cloning repository...');
await git.clone(REPO_URL, TEMP_DIR);
console.log('Repository cloned successfully!');
// Copy the desired file to the package directory
for (const targetFile of TARGET_FILES) {
const sourceFile = path.join(TEMP_DIR, targetFile);
const outputFile = path.join(
`${__dirname}/gamemaster/`,
path.basename(targetFile)
);
if (fs.existsSync(sourceFile)) {
fs.copyFileSync(sourceFile, outputFile);
console.log(`File copied to ${outputFile}`);
} else {
console.error(`File not found: ${sourceFile}`);
}
}
// Clean up the temporary directory
fs.rmSync(TEMP_DIR, { recursive: true, force: true });
console.log('Temporary files cleaned up.');
} catch (error) {
console.error('Error during postinstall:', error);
}
})();

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More