├── .gitignore ├── src ├── handleInteraction.ts ├── env.d.ts ├── DiscordWsClient.ts └── main.ts ├── package.json ├── LICENSE ├── README.md └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | dist 3 | 4 | node_modules 5 | package-lock.json -------------------------------------------------------------------------------- /src/handleInteraction.ts: -------------------------------------------------------------------------------- 1 | export default function handleInteraction() { 2 | 3 | } -------------------------------------------------------------------------------- /src/env.d.ts: -------------------------------------------------------------------------------- 1 | declare namespace NodeJS { 2 | interface ProcessEnv { 3 | DISCORD_TOKEN: string; 4 | SELF_DISCORD_ID: string; 5 | BASE_API_URL: string; 6 | COMMAND_PREFIX: string; 7 | LOG_OP: "true" | "false"; 8 | LOG_DATA: "true" | "false"; 9 | } 10 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "self-commands", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "dev": "nodemon -x \"ts-node --files\" src/main.ts", 8 | "build": "tsc" 9 | }, 10 | "keywords": [], 11 | "author": "", 12 | "license": "ISC", 13 | "dependencies": { 14 | "cross-spawn": "^7.0.3", 15 | "dotenv": "^16.4.5", 16 | "typescript": "^5.6.3", 17 | "ws": "^8.16.0" 18 | }, 19 | "devDependencies": { 20 | "@types/node": "^22.9.0", 21 | "@types/ws": "^8.5.13", 22 | "nodemon": "^3.1.7" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Charles Chrismann 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # discord-self-commands 2 | 3 | **discord-self-commands** is a project that allows you to interact with your machine's terminal through Discord messages. By sending commands via Discord, you can execute them on the machine where the bot is running. 4 | 5 | ## Features 6 | 7 | - Execute terminal commands remotely via Discord. 8 | - Receive command output directly in Discord. 9 | - Lightweight and easy to set up. 10 | 11 | ## Usage 12 | 13 | 1. Install the project on your machine. 14 | 2. Configure your Discord bot token and server/channel. 15 | 3. Send commands to the bot in Discord. 16 | 4. Receive the output of your commands directly in Discord messages. 17 | 18 | ## Security Warning 19 | 20 | - This project allows execution of arbitrary terminal commands. **Use at your own risk.** 21 | - Make sure to run it only on trusted machines and Discord servers. 22 | - Do not expose the bot to untrusted users. 23 | 24 | ## Installation 25 | 26 | ```bash 27 | git clone https://github.com/yourusername/discord-self-commands.git 28 | cd discord-self-commands 29 | npm install 30 | ``` 31 | 32 | # Configuration 33 | 34 | - Set your Discord bot token and target channel in the configuration file or environment variables. 35 | 36 | ## License 37 | 38 | This project is [MIT licensed](LICENSE). 39 | -------------------------------------------------------------------------------- /src/DiscordWsClient.ts: -------------------------------------------------------------------------------- 1 | import { WebSocket } from "ws"; 2 | 3 | export default class DiscordWsClient { 4 | ws!: WebSocket 5 | resume_gateway_url: undefined | string = undefined 6 | session_id: null | string = null 7 | s: null | string = null 8 | hbId: null | NodeJS.Timeout = null 9 | lastSequence: null | number = null 10 | state: 'CONNECTED' | 'DISCONNECTED' | 'RECONNECTING' = 'DISCONNECTED' 11 | 12 | constructor(private handleInteraction: Function) { 13 | this.initWs() 14 | } 15 | 16 | initWs(gateway_url?: string) { 17 | if(this.ws) this.ws.close() 18 | this.state = !!this.resume_gateway_url ? 'RECONNECTING' : 'DISCONNECTED' 19 | this.ws = new WebSocket(gateway_url || 'wss://gateway.discord.gg'); 20 | this.ws.on('error', (err: unknown) => { 21 | console.log('Ws error', err) 22 | this.initWs(this.resume_gateway_url ?? undefined) 23 | }); 24 | this.ws.on('close', (data) => { 25 | console.log('Connexion closed', data) 26 | this.initWs(this.resume_gateway_url ?? undefined) 27 | }); 28 | this.ws.on('open', () => { 29 | console.log(`CONNECTED TO: ${this.ws.url}`) 30 | if(this.state !== 'RECONNECTING') return 31 | this.ws.send(JSON.stringify({ 32 | "op": 6, 33 | "d": { 34 | "token": process.env.DISCORD_TOKEN, 35 | "session_id": this.session_id, 36 | "seq": this.s 37 | } 38 | })) 39 | }) 40 | this.ws.on('message', (raw) => { 41 | const data = JSON.parse(raw as unknown as string) 42 | if(process.env.LOG_OP === "true") console.log(data.op) 43 | if(process.env.LOG_DATA === "true") console.log(data) 44 | 45 | switch (data.op) { 46 | case 0: 47 | this.s = data.s 48 | switch (data.t) { 49 | case 'READY': 50 | this.resume_gateway_url = data.d.resume_gateway_url 51 | this.session_id = data.d.session_id 52 | this.state = 'CONNECTED' 53 | console.log('HANDSHAKE SUCCESSFULL') 54 | break; 55 | case 'MESSAGE_CREATE': 56 | if (data.d.author.id !== process.env.SELF_DISCORD_ID) return 57 | this.handleInteraction(data) 58 | break; 59 | } 60 | break; 61 | case 1: 62 | this.lastSequence = data.d 63 | break; 64 | 65 | case 7: 66 | this.initWs(this.resume_gateway_url ?? undefined) 67 | break; 68 | 69 | case 9: 70 | this.state = 'CONNECTED' 71 | console.log('CONNEXION RESUMED') 72 | break; 73 | 74 | case 10: 75 | if(this.state === 'RECONNECTING') break; 76 | this.ws.send(JSON.stringify({ op: 1, d: this.lastSequence })) 77 | this.connect() 78 | this.heartbeat(data.d.heartbeat_interval) 79 | break; 80 | } 81 | }) 82 | } 83 | 84 | connect() { 85 | this.ws.send(JSON.stringify({ 86 | op: 2, 87 | d: { 88 | token: process.env.DISCORD_TOKEN, 89 | properties: { 90 | "os": "linux", 91 | "browser": "disco", 92 | "device": "disco" 93 | }, 94 | intents: 512 95 | } 96 | })) 97 | } 98 | 99 | heartbeat(time: number) { 100 | if (this.hbId) clearInterval(this.hbId) 101 | console.log('stating heartbeat') 102 | this.hbId = setInterval(() => this.ws.send(JSON.stringify({ op: 1, d: this.lastSequence })), time) 103 | } 104 | } -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import 'dotenv/config' 2 | import WebSocket from 'ws'; 3 | import { ChildProcessWithoutNullStreams, spawn } from 'child_process' 4 | import { EventEmitter } from 'events'; 5 | import DiscordWsClient from './DiscordWsClient'; 6 | 7 | const PREFIX = process.env.COMMAND_PREFIX 8 | 9 | const pathEmitter = new EventEmitter() 10 | pathEmitter.on('path', () => { 11 | child.stdin.write(cmd + '\n') 12 | }) 13 | 14 | // let hbId: NodeJS.Timeout 15 | // let lastSequence: null | number = null 16 | // function heartbeat(time: number) { 17 | // if (hbId) clearInterval(hbId) 18 | // console.log('stating heartbeat') 19 | // hbId = setInterval(() => ws.send(JSON.stringify({ op: 1, d: lastSequence })), time) 20 | // } 21 | 22 | async function postResponse(d: any) { 23 | const log = d.toString() 24 | const content = `\`\`\`sh\n${cmd ? `${currentPWD}$ ${cmd}\n` : ''}${log}\`\`\`` 25 | cmd = null 26 | const headers = new Headers 27 | headers.set("Authorization", process.env.DISCORD_TOKEN) 28 | headers.set("Content-Type", "application/json") 29 | await fetch(`https://discord.com/api/v9/channels/${currentChannelIntercation}/messages`, { 30 | headers, 31 | body: JSON.stringify({ 32 | content 33 | }), 34 | "method": "POST", 35 | }); 36 | } 37 | 38 | async function react() { 39 | const headers = new Headers 40 | headers.set("Authorization", process.env.DISCORD_TOKEN) 41 | const res = await (await fetch(`https://discord.com/api/v9/channels/${currentChannelIntercation}/messages/${lastMsgId}/reactions/✅/@me?location=Message&type=0`, { 42 | headers, 43 | method: "PUT", 44 | })).text() 45 | console.log(res) 46 | } 47 | 48 | // let ws: WebSocket 49 | 50 | // let resume_gateway_url: string 51 | // let session_id: string 52 | // let s: string 53 | 54 | let isGettingPWD: boolean 55 | let currentPWD: string 56 | let sshInteraction: null | boolean = false 57 | let currentChannelIntercation: null | number 58 | let lastMsgId: number 59 | let child: ChildProcessWithoutNullStreams 60 | let cmd: string | null 61 | function handleInteraction(data: any) { 62 | if (data.d.content !== `${PREFIX}ssh` && !sshInteraction) return 63 | if (sshInteraction && data.d.channel_id !== currentChannelIntercation) return 64 | if (data.d.content === `${PREFIX}ssh`) { 65 | currentChannelIntercation = data.d.channel_id 66 | sshInteraction = true 67 | child = spawn('bash', { 68 | shell: true 69 | }); 70 | 71 | child.stdout.on('data', async (data) => { 72 | console.log(`child stdout:\n${data}`); 73 | if (isGettingPWD) { 74 | isGettingPWD = false 75 | currentPWD = data.toString().replace(/\n$/, '') 76 | pathEmitter.emit('path') 77 | return 78 | } 79 | await postResponse(data) 80 | }); 81 | 82 | child.stderr.on('data', (data) => { 83 | console.error(`child stderr:\n${data}`); 84 | }); 85 | 86 | child.on('exit', function (code, signal) { 87 | react() 88 | currentChannelIntercation = null 89 | sshInteraction = null 90 | cmd = null 91 | console.log('child process exited with ' + 92 | `code ${code} and signal ${signal}`); 93 | }); 94 | 95 | child.on('error', function (code: any, signal: any) { 96 | console.log('ya error') 97 | }); 98 | 99 | child.stdin.write('pwd\n') 100 | } else if (data.d.content.startsWith(PREFIX)) { 101 | lastMsgId = data.d.id 102 | cmd = String(data.d.content).replace(/^\$/, '') 103 | console.log('cmd: ' + cmd) 104 | isGettingPWD = true 105 | child.stdin.write('pwd\n') 106 | } 107 | } 108 | 109 | // function connect() { 110 | // ws.send(JSON.stringify({ 111 | // op: 2, 112 | // d: { 113 | // token: process.env.DISCORD_TOKEN, 114 | // properties: { 115 | // "os": "linux", 116 | // "browser": "disco", 117 | // "device": "disco" 118 | // }, 119 | // intents: 512 120 | // } 121 | // })) 122 | // } 123 | 124 | // function setupWs(gateway_url = 'wss://gateway.discord.gg') { 125 | // ws = new WebSocket(gateway_url); 126 | // ws.on('error',(err: unknown) => { 127 | // console.error(err) 128 | // connect() 129 | // }); 130 | // ws.on('close', (data) => { 131 | // console.log('Connexion closed', data) 132 | // connect() 133 | // }); 134 | // ws.on('open', connect) 135 | // ws.on('message', (raw) => { 136 | // const data = JSON.parse(raw as unknown as string) 137 | // console.log(data.op) 138 | // console.log(data) 139 | 140 | // switch (data.op) { 141 | // case 0: 142 | // s = data.s 143 | // switch (data.t) { 144 | // case 'MESSAGE_CREATE': 145 | // resume_gateway_url = data.d.resume_gateway_url 146 | // session_id = data.d.session_id 147 | // break; 148 | // case 'MESSAGE_CREATE': 149 | // if (data.d.author.id !== process.env.SELF_DISCORD_ID) return 150 | // handleInteraction(data) 151 | // break; 152 | // } 153 | // break; 154 | // case 1: 155 | // lastSequence = data.d 156 | // break; 157 | // case 10: 158 | // heartbeat(data.d.heartbeat_interval) 159 | // break; 160 | // } 161 | // }) 162 | // } 163 | 164 | const discordWsClient = new DiscordWsClient(handleInteraction) -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs", /* Specify what module code is generated. */ 29 | "rootDir": "./src", /* Specify the root folder within your source files. */ 30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | "typeRoots": ["./node_modules/@types", "./src"], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ 39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ 40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ 41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ 42 | // "resolveJsonModule": true, /* Enable importing .json files. */ 43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ 44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 45 | 46 | /* JavaScript Support */ 47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 50 | 51 | /* Emit */ 52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 58 | "outDir": "./dist", /* Specify an output folder for all emitted files. */ 59 | // "removeComments": true, /* Disable emitting comments. */ 60 | // "noEmit": true, /* Disable emitting files from a compilation. */ 61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 68 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 75 | 76 | /* Interop Constraints */ 77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ 79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ 81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 83 | 84 | /* Type Checking */ 85 | "strict": true, /* Enable all strict type-checking options. */ 86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 104 | 105 | /* Completeness */ 106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 108 | }, 109 | "include": ["src/**/*", "src/env.d.ts"] 110 | } 111 | --------------------------------------------------------------------------------