refactor(eslint)

This commit is contained in:
xhyrom 2022-01-02 18:54:19 +01:00
parent 85dbdfe907
commit a93f35b2ef
14 changed files with 2152 additions and 215 deletions

4
.eslintignore Normal file
View file

@ -0,0 +1,4 @@
dist/
tests/
src/web/
webpack.config.js

33
.eslintrc.json Normal file
View 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

File diff suppressed because it is too large Load diff

View file

@ -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",

View file

@ -3,7 +3,7 @@ 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({
@ -12,30 +12,31 @@ const badFormatting = (rolesMax?: boolean) => {
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;
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({
if ((Number(interaction.member?.permissions) & 0x10) !== 0x10) return respond({
type: InteractionResponseType.ChannelMessageWithSource,
data: {
flags: 64,
content: `Required permissions: \`MANAGE_ROLES\``
content: 'Required permissions: `MANAGE_ROLES`'
}
})
});
// 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;
@ -50,12 +51,12 @@ export const handleRequest = async(request: Request): Promise<Response> => {
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);
roles = roles.map((r: any) => {
let o: any = {
const o: any = {
type: 2,
style: r.style || 2,
label: r.label,
custom_id: r.id
}
};
if (r.emoji) {
if (isSnowflake(r.emoji)) o.emoji = { id: r.emoji, name: null };
@ -63,18 +64,18 @@ export const handleRequest = async(request: Request): Promise<Response> => {
}
return o;
})
});
const finalComponents = [];
for (let i = 0; i <= roles.length; i += 5) {
const row: any = {
type: 1,
components: []
}
};
const btnslice: any = roles.slice(i, i + 5);
for (let y: number = 0; y < btnslice.length; y++) row.components.push(btnslice[y]);
for (let y = 0; y < btnslice.length; y++) row.components.push(btnslice[y]);
finalComponents.push(row);
}
@ -89,7 +90,7 @@ export const handleRequest = async(request: Request): Promise<Response> => {
content: message,
components: finalComponents
})
}).catch(e => e)
}).catch(e => e);
return respond({
type: InteractionResponseType.ChannelMessageWithSource,
@ -97,13 +98,13 @@ export const handleRequest = async(request: Request): Promise<Response> => {
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!`;
@ -127,7 +128,7 @@ export const handleRequest = async(request: Request): Promise<Response> => {
content: content,
allowed_mentions: { parse: [] }
}
})
});
}
return respond({
@ -136,5 +137,5 @@ export const handleRequest = async(request: Request): Promise<Response> => {
flags: MessageFlags.Ephemeral,
content: 'Beep boop, boop beep?'
}
})
}
});
};

View file

@ -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));
});

View file

@ -8,4 +8,4 @@ export const isJSON = (data: any): boolean => {
} catch (err) {
return false;
}
}
};

View file

@ -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
View file

@ -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;

View file

@ -4,7 +4,7 @@
function hex2bin(hex: string) {
const buf = new Uint8Array(Math.ceil(hex.length / 2));
for (var i = 0; i < buf.length; i++) {
for (let i = 0; i < buf.length; i++) {
buf[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return buf;
@ -24,7 +24,7 @@ const PUBLIC_KEY = crypto.subtle.importKey(
const encoder = new TextEncoder();
export async function verify(request: Request) {
const signature = hex2bin(request.headers.get('X-Signature-Ed25519')!);
const signature = hex2bin(request.headers.get('X-Signature-Ed25519') || '');
const timestamp = request.headers.get('X-Signature-Timestamp');
const unknown = await request.clone().text();

View file

@ -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} />;
}

View file

@ -1,5 +1,5 @@
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 (
@ -22,7 +22,7 @@ export default function Home() {
</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>
<pre className={'hljs language-json copy'} id="jsonPre"><code id="json" className="code"></code></pre>
</div>
</section>
@ -30,5 +30,5 @@ export default function Home() {
<Script src="script.js"></Script>
<Script id='hljs'>hljs.initHighlightingOnLoad();</Script>
</div>
)
);
}

View file

@ -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':'🤩'}
]
}
};

View file

@ -24,4 +24,4 @@ module.exports = {
},
],
},
}
};