Innit commit

This commit is contained in:
Zankuro 2020-10-29 22:02:00 +01:00
parent 8e706b062e
commit 1f4bb73d26
7 changed files with 13593 additions and 0 deletions

13139
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

33
package.json Normal file
View File

@ -0,0 +1,33 @@
{
"name": "discord-cli",
"version": "1.0.0",
"description": "",
"main": "dist/index.js",
"scripts": {
"run": "concurrently \"tsc\" \"node dist/index.js\"",
"dev": "concurrently \"tsc -w\" \"nodemon dist/index.js\"",
"compile": "tsc"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"concurrently": "^5.3.0",
"nodemon": "^2.0.6"
},
"dependencies": {
"@types/lodash": "^4.14.163",
"@types/node": "^14.14.5",
"@types/terminal-kit": "^1.28.2",
"@types/websocket": "^1.0.1",
"@types/ws": "^7.2.9",
"dotenv": "^8.2.0",
"install": "^0.13.0",
"lodash": "^4.17.20",
"log-symbols": "^4.0.0",
"npm": "^6.14.8",
"terminal-kit": "^1.44.0",
"typescript": "^4.0.5",
"ws": "^7.3.1"
}
}

32
src/cli/cli.ts Normal file
View File

@ -0,0 +1,32 @@
import {
User,
Recipient,
Channels,
Messages,
Author,
Attachment,
} from "../discord_api/types";
import * as _ from "lodash";
class Cli {
constructor() {}
// This is one of the most complex functions... And is a pain in the ass...
print_conversation(ctx: [Messages]) {
if (ctx == undefined) {
console.error("Invalid parameters.");
return;
}
_.forEachRight(ctx, (value, index) => {
console.log(
`[${index}]`,
`${value.author.username} > `,
`${value.content}`
);
});
}
}
export default Cli;

202
src/discord_api/discord.ts Normal file
View File

@ -0,0 +1,202 @@
import {
ClientRequest,
ClientRequestArgs,
IncomingMessage,
OutgoingHttpHeaders,
} from "http";
import http from "https";
import WebSocket from "ws";
import {
User,
Recipient,
Channels,
Messages,
Author,
Attachment,
} from "./types";
import * as _ from "lodash";
import { ifError } from "assert";
class Discord {
cache: any;
constructor() {
this.cache = { s: 1 }; //placeholder
}
set_cache(new_cache: object) {
this.cache = new_cache;
}
set_heartbeat_interval(interval: number) {
setInterval(() => {
const ws = new WebSocket("wss://gateway.discord.gg");
ws.on("open", () => {
ws.send({
op: 1,
d: this.cache.s,
});
});
console.log("Sent heartbeat...");
}, interval);
}
test_connection(): Promise<boolean> {
const promise = new Promise<boolean>((resolve, reject) => {
const options: ClientRequestArgs = {
method: "GET",
hostname: "discord.com",
port: null,
path: "/api/v8/users/@me/channels",
headers: {
authorization: process.env.token?.toString(),
"Content-Length": "0",
},
};
const req: ClientRequest = http.request(
options,
(res: IncomingMessage) => {
const chunks: any = [];
res.on("data", (chunk: any) => {
chunks.push(chunk);
});
req.on("error", (error) => {
console.error(error);
});
res.on("end", () => {
const body = Buffer.concat(chunks);
if (typeof body !== undefined) {
/*
const i = JSON.parse(body.toString());
console.log(i[0].id);
*/
resolve(true);
}
});
}
);
req.end();
});
return promise;
}
req(req: "get", path: string): Promise<string> {
const options: ClientRequestArgs = {
method: "GET",
hostname: "discord.com",
port: null,
path: path,
headers: {
authorization: process.env.token?.toString(),
"Content-Length": "0",
},
};
const promise = new Promise<string>((resolve, reject) => {
const req: ClientRequest = http.request(
options,
(res: IncomingMessage) => {
const chunks: any = [];
res.on("data", (chunk: any) => {
chunks.push(chunk);
});
req.on("error", (error) => {
console.error(error);
});
res.on("end", () => {
const body = Buffer.concat(chunks);
if (typeof body !== undefined) {
resolve(body.toString());
}
});
}
);
req.end();
});
return promise;
}
get(type: "messages", channel_id: string, limit: number): Promise<[Messages]>;
get(type: "channels"): Promise<[Channels]>;
get(type: "dms"): Promise<[User]>;
get(type: any, channel_id?: string): Promise<any> {
const promise = new Promise<any>(async (resolve, reject) => {
if (type == "dms") {
const dms: string = await this.req("get", "/api/v8/users/@me/channels");
const dms_json: object = JSON.parse(dms);
resolve(<[User]>dms_json);
} else if (type == "channels") {
const channels: string = await this.req(
"get",
"/api/v8/users/@me/guilds"
);
const channels_json: object = JSON.parse(channels);
resolve(<[Channels]>channels_json);
} else if (type == "messages") {
const channels: string = await this.req(
"get",
`/api/v8/channels/${channel_id}/messages?limit=${5}`
);
const channels_json: object = JSON.parse(channels);
resolve(<[Messages]>channels_json);
} else {
console.error("Invalid input");
return;
}
});
return promise;
}
listen(type: "setup"): Promise<boolean>;
listen(type: "msg", callback: (msg: [Messages]) => void): void;
async listen(type: any, callback?: (msg: [Messages]) => void): Promise<any> {
if (type == "setup") {
// For future generations!
const _url = await this.req("get", "https://discord.com/api/v8/gateway");
const url = JSON.parse(_url).url;
const ws = new WebSocket(url);
ws.on("open", () => {
const identify: Object = {
op: 2,
d: {
token: process.env.token?.toString(),
intents: 1 << 12,
properties: {
$os: "templeOS",
$browser: "pwrDiscord",
$device: "pwrDicord",
},
},
};
ws.send(JSON.stringify(identify));
});
ws.on("message", (data) => {
this.set_cache(JSON.parse(data.toString()));
if (JSON.parse(data.toString()).d.heartbeat_interval !== undefined) {
this.set_heartbeat_interval(
JSON.parse(data.toString()).d.heartbeat_interval
);
} else {
console.log("Msg recived!");
}
});
}
}
}
export default Discord;

82
src/discord_api/types.ts Normal file
View File

@ -0,0 +1,82 @@
/*
This is a interface for store all the cahce.
Cache will store all the information of the user:
- Channels
- Friends
export interface Cache {
channels: Channel;
friends: Friends;
}
// Honestly I don't know if keep these private but whatever.
export interface User {
id_channel: string;
id_user: string;
name: string;
discriminator?: number; // Just in case
}
*/
// Generated by https://quicktype.io
export interface Messages {
id: string;
type: number;
content: string;
channel_id: string;
author: Author;
attachments: Attachment[];
embeds: any[];
mentions: any[];
mention_roles: any[];
pinned: boolean;
mention_everyone: boolean;
tts: boolean;
timestamp: string;
edited_timestamp: null | string;
flags: number;
}
export interface Attachment {
id: string;
filename: string;
size: number;
url: string;
proxy_url: string;
width: number;
height: number;
}
export interface Author {
id: string;
username: string;
avatar: null | string;
discriminator: string;
public_flags: number;
}
export interface Channels {
id: string;
name: string;
icon: null | string;
owner: boolean;
permissions: string;
features: string[];
}
export interface User {
id: string;
type: number;
last_message_id: string;
recipients: Recipient[];
}
export interface Recipient {
id: string;
username: string;
avatar: string;
discriminator: string;
public_flags: number;
}

32
src/index.ts Normal file
View File

@ -0,0 +1,32 @@
import term from "terminal-kit";
import dotenv from "dotenv";
import log_symbols from "log-symbols";
import Discord from "./discord_api/discord";
import Cli from "./cli/cli";
import { isExternalModuleReference } from "typescript";
dotenv.config();
const iterm = term.terminal;
if (process.env.token === "" || process.env.token === undefined) {
console.log(
log_symbols.error,
'Error! No token provided. Make sure you have the file ".env" in the root directory with the key "token=yourtoken" '
);
} else if (process.env.token === "yourtoken") {
console.log(log_symbols.error, "I mean your real discord token");
}
const discord = new Discord();
////////////////////
(async () => {
if (await discord.test_connection()) {
const cli = new Cli();
const i = await discord.get("messages", "585905156080664586", 5);
//cli.print_conversation(i);
//discord.listen("setup");
}
})();

73
tsconfig.json Normal file
View File

@ -0,0 +1,73 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": "./src", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
"resolveJsonModule": true,
},
"include": ["src"],
"exclude": ["node_modules"]
}