mirror of
https://github.com/xHyroM/roles-bot.git
synced 2024-11-21 16:11:04 +01:00
refactor(eslint)
This commit is contained in:
parent
85dbdfe907
commit
a93f35b2ef
14 changed files with 2152 additions and 215 deletions
4
.eslintignore
Normal file
4
.eslintignore
Normal file
|
@ -0,0 +1,4 @@
|
|||
dist/
|
||||
tests/
|
||||
src/web/
|
||||
webpack.config.js
|
33
.eslintrc.json
Normal file
33
.eslintrc.json
Normal file
|
@ -0,0 +1,33 @@
|
|||
{
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/recommended"
|
||||
],
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 12
|
||||
},
|
||||
"plugins": [
|
||||
"@typescript-eslint"
|
||||
],
|
||||
"rules": {
|
||||
"indent": [
|
||||
"error",
|
||||
"tab"
|
||||
],
|
||||
"linebreak-style": [
|
||||
"error",
|
||||
"unix"
|
||||
],
|
||||
"quotes": [
|
||||
"error",
|
||||
"single"
|
||||
],
|
||||
"semi": [
|
||||
"error",
|
||||
"always"
|
||||
],
|
||||
"prefer-const": "error",
|
||||
"@typescript-eslint/no-explicit-any": "off"
|
||||
}
|
||||
}
|
1909
package-lock.json
generated
1909
package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
@ -13,7 +13,9 @@
|
|||
"@cloudflare/workers-types": "^3.3.0",
|
||||
"@types/jest": "^27.0.3",
|
||||
"@types/service-worker-mock": "^2.0.1",
|
||||
"@typescript-eslint/eslint-plugin": "^5.8.1",
|
||||
"discord-api-types": "^0.25.2",
|
||||
"eslint": "^8.6.0",
|
||||
"service-worker-mock": "^2.0.5",
|
||||
"ts-loader": "^9.2.6",
|
||||
"typescript": "^4.5.4",
|
||||
|
|
221
src/bot/bot.ts
221
src/bot/bot.ts
|
@ -3,138 +3,139 @@ import { isJSON } from './isJson';
|
|||
import { isSnowflake } from './snowflakeUtils';
|
||||
import { verify } from './verify';
|
||||
|
||||
const respond = (response: APIInteractionResponse) => new Response(JSON.stringify(response), {headers: {'content-type': 'application/json'}})
|
||||
const respond = (response: APIInteractionResponse) => new Response(JSON.stringify(response), {headers: {'content-type': 'application/json'}});
|
||||
|
||||
const badFormatting = (rolesMax?: boolean) => {
|
||||
return respond({
|
||||
type: InteractionResponseType.ChannelMessageWithSource,
|
||||
data: {
|
||||
flags: 64,
|
||||
content: `${rolesMax ? 'You can have maximum 25 buttons. (5x5)' : 'Bad formatting, generate [here](https://xhyrom.github.io/roles-bot)'}`
|
||||
}
|
||||
})
|
||||
}
|
||||
return respond({
|
||||
type: InteractionResponseType.ChannelMessageWithSource,
|
||||
data: {
|
||||
flags: 64,
|
||||
content: `${rolesMax ? 'You can have maximum 25 buttons. (5x5)' : 'Bad formatting, generate [here](https://xhyrom.github.io/roles-bot)'}`
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const handleRequest = async(request: Request): Promise<Response> => {
|
||||
if (!request.headers.get('X-Signature-Ed25519') || !request.headers.get('X-Signature-Timestamp')) return Response.redirect('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
|
||||
if (!await verify(request)) return new Response('', { status: 401 })
|
||||
if (!request.headers.get('X-Signature-Ed25519') || !request.headers.get('X-Signature-Timestamp')) return Response.redirect('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
|
||||
if (!await verify(request)) return new Response('', { status: 401 });
|
||||
|
||||
const interaction = await request.json() as APIPingInteraction | APIApplicationCommandInteraction | APIMessageComponentInteraction;
|
||||
const interaction = await request.json() as APIPingInteraction | APIApplicationCommandInteraction | APIMessageComponentInteraction;
|
||||
|
||||
if (interaction.type === InteractionType.Ping)
|
||||
return respond({
|
||||
type: InteractionResponseType.Pong
|
||||
})
|
||||
if (interaction.type === InteractionType.Ping)
|
||||
return respond({
|
||||
type: InteractionResponseType.Pong
|
||||
});
|
||||
|
||||
if (interaction.type === InteractionType.ApplicationCommand && interaction.data.name === 'setup') {
|
||||
// @ts-ignore
|
||||
if ((interaction.member?.permissions & 0x10) !== 0x10) return respond({
|
||||
type: InteractionResponseType.ChannelMessageWithSource,
|
||||
data: {
|
||||
flags: 64,
|
||||
content: `Required permissions: \`MANAGE_ROLES\``
|
||||
}
|
||||
})
|
||||
if (interaction.type === InteractionType.ApplicationCommand && interaction.data.name === 'setup') {
|
||||
|
||||
// @ts-ignore
|
||||
const json = isJSON(interaction.data.options[0].value) ? JSON.parse(interaction.data.options[0].value) : null;
|
||||
if ((Number(interaction.member?.permissions) & 0x10) !== 0x10) return respond({
|
||||
type: InteractionResponseType.ChannelMessageWithSource,
|
||||
data: {
|
||||
flags: 64,
|
||||
content: 'Required permissions: `MANAGE_ROLES`'
|
||||
}
|
||||
});
|
||||
|
||||
if (!json) return badFormatting();
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const json = isJSON(interaction.data.options[0].value) ? JSON.parse(interaction.data.options[0].value) : null;
|
||||
|
||||
const channelId = json.channel;
|
||||
const message = json.message?.toString();
|
||||
let roles = json.roles;
|
||||
if (!json) return badFormatting();
|
||||
|
||||
if (!channelId) return badFormatting();
|
||||
if (!message) return badFormatting();
|
||||
if (!roles || Object.values(json.roles).filter((role: any) => role.id && role.label).length === 0 || roles.length === 0 || roles.length > 25) return badFormatting(roles.length > 25);
|
||||
const channelId = json.channel;
|
||||
const message = json.message?.toString();
|
||||
let roles = json.roles;
|
||||
|
||||
roles = roles.map((r: any) => {
|
||||
let o: any = {
|
||||
type: 2,
|
||||
style: r.style || 2,
|
||||
label: r.label,
|
||||
custom_id: r.id
|
||||
}
|
||||
if (!channelId) return badFormatting();
|
||||
if (!message) return badFormatting();
|
||||
if (!roles || Object.values(json.roles).filter((role: any) => role.id && role.label).length === 0 || roles.length === 0 || roles.length > 25) return badFormatting(roles.length > 25);
|
||||
|
||||
if (r.emoji) {
|
||||
if (isSnowflake(r.emoji)) o.emoji = { id: r.emoji, name: null };
|
||||
else o.emoji = { id: null, name: r.emoji };
|
||||
}
|
||||
roles = roles.map((r: any) => {
|
||||
const o: any = {
|
||||
type: 2,
|
||||
style: r.style || 2,
|
||||
label: r.label,
|
||||
custom_id: r.id
|
||||
};
|
||||
|
||||
return o;
|
||||
})
|
||||
if (r.emoji) {
|
||||
if (isSnowflake(r.emoji)) o.emoji = { id: r.emoji, name: null };
|
||||
else o.emoji = { id: null, name: r.emoji };
|
||||
}
|
||||
|
||||
const finalComponents = [];
|
||||
for (let i = 0; i <= roles.length; i += 5) {
|
||||
const row: any = {
|
||||
type: 1,
|
||||
components: []
|
||||
}
|
||||
return o;
|
||||
});
|
||||
|
||||
const btnslice: any = roles.slice(i, i + 5);
|
||||
const finalComponents = [];
|
||||
for (let i = 0; i <= roles.length; i += 5) {
|
||||
const row: any = {
|
||||
type: 1,
|
||||
components: []
|
||||
};
|
||||
|
||||
for (let y: number = 0; y < btnslice.length; y++) row.components.push(btnslice[y]);
|
||||
const btnslice: any = roles.slice(i, i + 5);
|
||||
|
||||
for (let y = 0; y < btnslice.length; y++) row.components.push(btnslice[y]);
|
||||
|
||||
finalComponents.push(row);
|
||||
}
|
||||
finalComponents.push(row);
|
||||
}
|
||||
|
||||
await fetch(`${RouteBases.api}/channels/${channelId}/messages`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bot ${CLIENT_TOKEN}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
content: message,
|
||||
components: finalComponents
|
||||
})
|
||||
}).catch(e => e)
|
||||
await fetch(`${RouteBases.api}/channels/${channelId}/messages`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bot ${CLIENT_TOKEN}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
content: message,
|
||||
components: finalComponents
|
||||
})
|
||||
}).catch(e => e);
|
||||
|
||||
return respond({
|
||||
type: InteractionResponseType.ChannelMessageWithSource,
|
||||
data: {
|
||||
flags: 64,
|
||||
content: 'Done!'
|
||||
}
|
||||
})
|
||||
} else if (interaction.type === InteractionType.MessageComponent) {
|
||||
const roleId = interaction.data.custom_id;
|
||||
const url = `${RouteBases.api}${Routes.guildMemberRole(interaction.guild_id || '', interaction.member?.user.id || '', roleId)}`;
|
||||
return respond({
|
||||
type: InteractionResponseType.ChannelMessageWithSource,
|
||||
data: {
|
||||
flags: 64,
|
||||
content: 'Done!'
|
||||
}
|
||||
});
|
||||
} else if (interaction.type === InteractionType.MessageComponent) {
|
||||
const roleId = interaction.data.custom_id;
|
||||
const url = `${RouteBases.api}${Routes.guildMemberRole(interaction.guild_id || '', interaction.member?.user.id || '', roleId)}`;
|
||||
|
||||
let method = "";
|
||||
let content = "";
|
||||
let method = '';
|
||||
let content = '';
|
||||
|
||||
if (!interaction?.member?.roles?.includes(roleId)) {
|
||||
content = `Gave the <@&${roleId}> role!`;
|
||||
method = 'PUT';
|
||||
} else {
|
||||
content = `Removed the <@&${roleId}> role!`;
|
||||
method = 'DELETE';
|
||||
}
|
||||
if (!interaction?.member?.roles?.includes(roleId)) {
|
||||
content = `Gave the <@&${roleId}> role!`;
|
||||
method = 'PUT';
|
||||
} else {
|
||||
content = `Removed the <@&${roleId}> role!`;
|
||||
method = 'DELETE';
|
||||
}
|
||||
|
||||
await fetch(url, {
|
||||
method: method,
|
||||
headers: {
|
||||
'Authorization': `Bot ${CLIENT_TOKEN}`
|
||||
}
|
||||
}).catch(e => e);
|
||||
await fetch(url, {
|
||||
method: method,
|
||||
headers: {
|
||||
'Authorization': `Bot ${CLIENT_TOKEN}`
|
||||
}
|
||||
}).catch(e => e);
|
||||
|
||||
return respond({
|
||||
type: InteractionResponseType.ChannelMessageWithSource,
|
||||
data: {
|
||||
flags: MessageFlags.Ephemeral,
|
||||
content: content,
|
||||
allowed_mentions: { parse: [] }
|
||||
}
|
||||
})
|
||||
}
|
||||
return respond({
|
||||
type: InteractionResponseType.ChannelMessageWithSource,
|
||||
data: {
|
||||
flags: MessageFlags.Ephemeral,
|
||||
content: content,
|
||||
allowed_mentions: { parse: [] }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return respond({
|
||||
type: InteractionResponseType.ChannelMessageWithSource,
|
||||
data: {
|
||||
flags: MessageFlags.Ephemeral,
|
||||
content: 'Beep boop, boop beep?'
|
||||
}
|
||||
})
|
||||
}
|
||||
return respond({
|
||||
type: InteractionResponseType.ChannelMessageWithSource,
|
||||
data: {
|
||||
flags: MessageFlags.Ephemeral,
|
||||
content: 'Beep boop, boop beep?'
|
||||
}
|
||||
});
|
||||
};
|
|
@ -1,5 +1,5 @@
|
|||
import { handleRequest } from './bot'
|
||||
import { handleRequest } from './bot';
|
||||
|
||||
addEventListener('fetch', (event) => {
|
||||
event.respondWith(handleRequest(event.request))
|
||||
})
|
||||
event.respondWith(handleRequest(event.request));
|
||||
});
|
|
@ -1,11 +1,11 @@
|
|||
export const isJSON = (data: any): boolean => {
|
||||
if (typeof data !== 'string') return false;
|
||||
try {
|
||||
const result = JSON.parse(data);
|
||||
const type = result.toString();
|
||||
if (typeof data !== 'string') return false;
|
||||
try {
|
||||
const result = JSON.parse(data);
|
||||
const type = result.toString();
|
||||
|
||||
return type === '[object Object]' || type === '[object Array]';
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return type === '[object Object]' || type === '[object Array]';
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
};
|
|
@ -1,6 +1,6 @@
|
|||
export const toSnowflake = (snowflake: number, epoch = DISCORD_EPOCH) => {
|
||||
return new Date(snowflake / 4194304 + epoch)
|
||||
}
|
||||
return new Date(snowflake / 4194304 + epoch);
|
||||
};
|
||||
|
||||
export const DISCORD_EPOCH = 1420070400000;
|
||||
|
||||
|
@ -12,4 +12,4 @@ export const isSnowflake = (snowflake: number, epoch?: number) => {
|
|||
if (isNaN(timestamp.getTime())) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
4
src/bot/types.d.ts
vendored
4
src/bot/types.d.ts
vendored
|
@ -1,2 +1,2 @@
|
|||
declare const CLIENT_PUBLIC_KEY: string
|
||||
declare const CLIENT_TOKEN: string
|
||||
declare const CLIENT_PUBLIC_KEY: string;
|
||||
declare const CLIENT_TOKEN: string;
|
|
@ -3,35 +3,35 @@
|
|||
'use strict';
|
||||
|
||||
function hex2bin(hex: string) {
|
||||
const buf = new Uint8Array(Math.ceil(hex.length / 2));
|
||||
for (var i = 0; i < buf.length; i++) {
|
||||
buf[i] = parseInt(hex.substr(i * 2, 2), 16);
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
const buf = new Uint8Array(Math.ceil(hex.length / 2));
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
buf[i] = parseInt(hex.substr(i * 2, 2), 16);
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
const PUBLIC_KEY = crypto.subtle.importKey(
|
||||
'raw',
|
||||
hex2bin(CLIENT_PUBLIC_KEY || ''),
|
||||
{
|
||||
name: 'NODE-ED25519',
|
||||
namedCurve: 'NODE-ED25519',
|
||||
},
|
||||
true,
|
||||
['verify'],
|
||||
'raw',
|
||||
hex2bin(CLIENT_PUBLIC_KEY || ''),
|
||||
{
|
||||
name: 'NODE-ED25519',
|
||||
namedCurve: 'NODE-ED25519',
|
||||
},
|
||||
true,
|
||||
['verify'],
|
||||
);
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
export async function verify(request: Request) {
|
||||
const signature = hex2bin(request.headers.get('X-Signature-Ed25519')!);
|
||||
const timestamp = request.headers.get('X-Signature-Timestamp');
|
||||
const unknown = await request.clone().text();
|
||||
const signature = hex2bin(request.headers.get('X-Signature-Ed25519') || '');
|
||||
const timestamp = request.headers.get('X-Signature-Timestamp');
|
||||
const unknown = await request.clone().text();
|
||||
|
||||
return await crypto.subtle.verify(
|
||||
'NODE-ED25519',
|
||||
await PUBLIC_KEY,
|
||||
signature,
|
||||
encoder.encode(timestamp + unknown),
|
||||
);
|
||||
return await crypto.subtle.verify(
|
||||
'NODE-ED25519',
|
||||
await PUBLIC_KEY,
|
||||
signature,
|
||||
encoder.encode(timestamp + unknown),
|
||||
);
|
||||
}
|
|
@ -2,5 +2,5 @@ import '../styles/css/style.css';
|
|||
import type { AppProps } from 'next/app';
|
||||
|
||||
export default function MyApp({ Component, pageProps }: AppProps) {
|
||||
return <Component {...pageProps} />
|
||||
return <Component {...pageProps} />;
|
||||
}
|
|
@ -1,34 +1,34 @@
|
|||
import Head from "next/head";
|
||||
import Script from "next/script";
|
||||
import Head from 'next/head';
|
||||
import Script from 'next/script';
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div>
|
||||
<Head>
|
||||
<title>Roles Bot</title>
|
||||
<link rel="icon" href="logo.ico" />
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/styles/default.min.css" />
|
||||
return (
|
||||
<div>
|
||||
<Head>
|
||||
<title>Roles Bot</title>
|
||||
<link rel="icon" href="logo.ico" />
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/styles/default.min.css" />
|
||||
|
||||
<script src="https://kit.fontawesome.com/5acf4d9e80.js" crossOrigin="anonymous"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/highlight.min.js"></script>
|
||||
</Head>
|
||||
<section className="flex-container">
|
||||
<div className="container animate__animated animate__fadeIn">
|
||||
<h1>Generate</h1>
|
||||
<form>
|
||||
<input placeholder="Your Message" name="message" id="message"/><br />
|
||||
<input placeholder="Channel Id" name="channel" id="channel"/>
|
||||
</form>
|
||||
<button id="addRole">Add Role</button>
|
||||
<button id="buttonCopy">Copy</button>
|
||||
<pre className={`hljs language-json copy`} id="jsonPre"><code id="json" className="code"></code></pre>
|
||||
</div>
|
||||
</section>
|
||||
<script src="https://kit.fontawesome.com/5acf4d9e80.js" crossOrigin="anonymous"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/highlight.min.js"></script>
|
||||
</Head>
|
||||
<section className="flex-container">
|
||||
<div className="container animate__animated animate__fadeIn">
|
||||
<h1>Generate</h1>
|
||||
<form>
|
||||
<input placeholder="Your Message" name="message" id="message"/><br />
|
||||
<input placeholder="Channel Id" name="channel" id="channel"/>
|
||||
</form>
|
||||
<button id="addRole">Add Role</button>
|
||||
<button id="buttonCopy">Copy</button>
|
||||
<pre className={'hljs language-json copy'} id="jsonPre"><code id="json" className="code"></code></pre>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
|
||||
<Script src="script.js"></Script>
|
||||
<Script id='hljs'>hljs.initHighlightingOnLoad();</Script>
|
||||
</div>
|
||||
)
|
||||
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
|
||||
<Script src="script.js"></Script>
|
||||
<Script id='hljs'>hljs.initHighlightingOnLoad();</Script>
|
||||
</div>
|
||||
);
|
||||
}
|
|
@ -1,8 +1,8 @@
|
|||
module.exports = {
|
||||
"message": "lol",
|
||||
"channel": "862700556438732851",
|
||||
"roles": [
|
||||
{"id": "777805077825060867","label":"Bots","emoji":"😦"},
|
||||
{"id":"922762668841009152","label":"Ping","emoji":"🤩"}
|
||||
]
|
||||
}
|
||||
'message': 'lol',
|
||||
'channel': '862700556438732851',
|
||||
'roles': [
|
||||
{'id': '777805077825060867','label':'Bots','emoji':'😦'},
|
||||
{'id':'922762668841009152','label':'Ping','emoji':'🤩'}
|
||||
]
|
||||
};
|
|
@ -3,25 +3,25 @@ const path = require('path');
|
|||
const mode = process.env.NODE_ENV || 'production';
|
||||
|
||||
module.exports = {
|
||||
output: {
|
||||
filename: `worker.${mode}.js`,
|
||||
path: path.join(__dirname, 'dist'),
|
||||
},
|
||||
mode,
|
||||
resolve: {
|
||||
extensions: ['.ts', '.tsx', '.js'],
|
||||
plugins: [],
|
||||
fallback: { util: false }
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
loader: 'ts-loader',
|
||||
options: {
|
||||
transpileOnly: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
output: {
|
||||
filename: `worker.${mode}.js`,
|
||||
path: path.join(__dirname, 'dist'),
|
||||
},
|
||||
mode,
|
||||
resolve: {
|
||||
extensions: ['.ts', '.tsx', '.js'],
|
||||
plugins: [],
|
||||
fallback: { util: false }
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
loader: 'ts-loader',
|
||||
options: {
|
||||
transpileOnly: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
Loading…
Reference in a new issue