├── generated └── .gitkeep ├── config ├── persons.example.json └── gifs.example.json ├── .gitignore ├── src ├── utils │ ├── readJson.ts │ ├── getConvs.ts │ ├── saveConvs.ts │ ├── index.ts │ ├── checkValidity.ts │ └── makeSystemMessage.ts ├── interfaces │ └── index.ts ├── conv.ts ├── conv2.ts └── main.ts ├── package.json ├── LICENSE ├── README.md └── tsconfig.json /generated/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /config/persons.example.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "username": "Someone", 4 | "id": "1234567890", 5 | "channelId": "0987654321" 6 | } 7 | ] -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | 3 | node_modules 4 | dist/ 5 | 6 | generated/* 7 | !generated/.gitkeep 8 | 9 | config/* 10 | !config/*.example.json -------------------------------------------------------------------------------- /src/utils/readJson.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs' 2 | 3 | export default function readJson(path: string) { 4 | return JSON.parse(fs.readFileSync(path).toString()) 5 | } -------------------------------------------------------------------------------- /config/gifs.example.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "expressionOrFeeling": "smart", 4 | "url": "https://tenor.com/view/think-about-it-use-your-brain-use-the-brain-think-brain-gif-7914082" 5 | } 6 | ] -------------------------------------------------------------------------------- /src/utils/getConvs.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs' 2 | import { readJson } from '.' 3 | 4 | export default function getConvs(path: string) { 5 | try { 6 | return readJson(path) 7 | } catch (e) { 8 | return {} 9 | } 10 | } -------------------------------------------------------------------------------- /src/utils/saveConvs.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs' 2 | import { convMsg } from '../interfaces' 3 | 4 | export default function saveConvs(path: string, convs: {[index:string]: convMsg[] }) { 5 | fs.writeFileSync(path, JSON.stringify(convs, null, 2)) 6 | } -------------------------------------------------------------------------------- /src/interfaces/index.ts: -------------------------------------------------------------------------------- 1 | export interface person { username: string, id: string, channelId: string } 2 | export interface convMsg { role: "system" | "user" | "assistant", content: string } 3 | export interface gifs { 4 | expressionOrFeeling: string, 5 | url: string 6 | } -------------------------------------------------------------------------------- /src/utils/index.ts: -------------------------------------------------------------------------------- 1 | export {default as getConvs} from './getConvs' 2 | export {default as saveConvs} from './saveConvs' 3 | export {default as makeSystemMessage} from './makeSystemMessage' 4 | export {default as readJson} from './readJson' 5 | export {default as checkValidity} from './checkValidity' -------------------------------------------------------------------------------- /src/utils/checkValidity.ts: -------------------------------------------------------------------------------- 1 | import { type Message } from "discord.js-selfbot-v13"; 2 | import { person } from "../interfaces" 3 | 4 | export default function checkValidity(message: Message, persons: person[]) { 5 | const person = persons.find(p => p.id === message.author.id) 6 | if(!person) return false 7 | return person.channelId === message.channelId 8 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ollama", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "scripts": { 6 | "build": "tsc", 7 | "start": "node dist/main.js", 8 | "dev": "ts-node src/main.ts" 9 | }, 10 | "keywords": [], 11 | "author": "", 12 | "license": "ISC", 13 | "description": "", 14 | "dependencies": { 15 | "discord.js-selfbot-v13": "^3.4.6", 16 | "dotenv": "^16.4.7", 17 | "ollama": "^0.5.11", 18 | "zod-to-json-schema": "^3.24.1" 19 | }, 20 | "devDependencies": { 21 | "@types/node": "^22.10.5" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/utils/makeSystemMessage.ts: -------------------------------------------------------------------------------- 1 | import { readJson } from "." 2 | import { type gifs } from "../interfaces" 3 | 4 | export default function makeSystemMessage(gif_path: string) { 5 | const gifs: gifs[] = readJson(gif_path) 6 | const gifsStr = `Here is a list of gif urls associated with the feeling or the situation they can represent, you can give the url of the gif in your response, the url will be sent after your messageToSendBack, the following gif urls are the only one you are allowed to return, only use gifs if needed. Here are the gifs: \n\n${gifs.map(g => `${g.expressionOrFeeling}: ${g.url}`).join('\n')}\n` 7 | 8 | return `The user will give you a message send by a friend, it is most likely in french, mimic a response from me, the response will be sent on discord, you can use the discord markdown if needed, dont use @users. The response must be a non-empty string.\n\n${gifsStr}` 9 | } -------------------------------------------------------------------------------- /src/conv.ts: -------------------------------------------------------------------------------- 1 | import ollama from 'ollama'; 2 | 3 | async function main() { 4 | 5 | const output = await ollama.generate({ model: "llama3.2:1b", prompt: "why is the sky blue?", stream: true }) 6 | const context = []; 7 | 8 | for await (const part of output) { 9 | if (part.done === true) { 10 | console.log(`first generate complete`); 11 | context.push(...part.context); 12 | } 13 | } 14 | 15 | const output2 = await ollama.generate({ model: "llama3.2:1b", prompt: "can it be another?", context: context, stream: true }); 16 | // console.log(`output with context\n\n${output2.response}\n\noutput complete\n`); 17 | for await (const part of output2) { 18 | if (part.done === true) { 19 | console.log(`second generate complete`); 20 | context.push(...part.context); 21 | } 22 | } 23 | 24 | // console.log(context) 25 | 26 | const output3 = await ollama.generate({ model: "llama3.2:1b", prompt: "what questions did i ask you ?" , context: context }); 27 | console.log(`output without context\n\n${output3.response}\n\noutput complete`); 28 | } 29 | 30 | main() -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/conv2.ts: -------------------------------------------------------------------------------- 1 | import ollama from 'ollama'; 2 | 3 | async function main() { 4 | 5 | const schema = { 6 | "city": { 7 | "type": "string", 8 | "description": "The city where the user is located." 9 | }, 10 | "industry": { 11 | "type": "string", 12 | "description": "The most popular industry in the city. What the city is known for." 13 | }, 14 | "fun": 15 | { 16 | "type": "string", 17 | "description": "One thing that is fun to do there on a day off" 18 | } 19 | } 20 | const msgs = [ 21 | {"role": "system", "content": `The user will give you a city name. Describe the city including the major industry and a fun thing to do there. Output as JSON using this schema: ${JSON.stringify(schema, null, 2)}`}, 22 | { "role": "user", "content": "Paris" }, 23 | { "role": "assistant", "content": "{\n \"city\": \"Paris\",\n \"industry\": \"Fashion\",\n \"fun\": \"Take a stroll along the Seine River and enjoy the city\'s iconic landmarks while aboard a river cruise.\"\n}" }, 24 | {"role": "user", "content": "Amsterdam"}, 25 | ] 26 | const output = await ollama.chat({ model: "llama3.2:1b", messages: msgs }) 27 | 28 | console.log(output.message.content) 29 | } 30 | 31 | main() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SelfBot Discord with Ollama 2 | 3 | This project is a **selfbot for Discord** built with **Node.js**. It captures incoming Discord messages, sends them to **Ollama**, and generates automatic responses based on Ollama's suggestions. 4 | 5 | ## Features 6 | 7 | - Capture incoming messages on Discord. 8 | - Send messages to Ollama for contextual generation. 9 | - Automatically respond based on Ollama's suggestions. 10 | 11 | ## Requirements 12 | 13 | - **Node.js** >= 16.x 14 | - **NPM** or **Yarn** 15 | - A Discord account with the **user token** *(note: using a selfbot violates Discord's terms of service)* 16 | - A functional Ollama instance 17 | 18 | ## Installation 19 | 20 | ### Step 1: Clone the project 21 | 22 | ```bash 23 | git clone https://github.com/Charles-Chrismann/discord-ia-response-bot.git 24 | cd discord-ia-response-bot 25 | ``` 26 | 27 | ### Step 2: Install dependencies 28 | 29 | ```bash 30 | npm install 31 | ``` 32 | 33 | Step 3: Set environment variables 34 | 35 | Create a .env file at the project root with the following content: 36 | 37 | ```bash 38 | TOKEN= 39 | ``` 40 | 41 | ### Step 4: Run the project 42 | 43 | **In development:** 44 | 45 | ```bash 46 | npm run dev 47 | ``` 48 | 49 | **To build and run in production:** 50 | 51 | ```bash 52 | npm run build 53 | npm run start 54 | ``` 55 | 56 | ## Important Notes 57 | - Using a selfbot violates Discord's rules and may result in your account being suspended. 58 | - This project uses TypeScript for better code maintainability. 59 | 60 | ## Contribution 61 | 62 | Feel free to open an issue or submit a pull request for any improvement! 63 | 64 | ## License 65 | 66 | This project is [MIT licensed](LICENSE). 67 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import 'dotenv/config' 2 | import { Client } from "discord.js-selfbot-v13"; 3 | import ollama, { ChatResponse } from 'ollama'; 4 | import { z } from 'zod'; 5 | import { zodToJsonSchema } from 'zod-to-json-schema'; 6 | import { checkValidity, getConvs, makeSystemMessage, readJson, saveConvs } from './utils'; 7 | import { convMsg, person } from './interfaces'; 8 | 9 | const CONVS_PATH = process.env.CONVS_PATH as string 10 | const PERSONS_PATH = process.env.PERSONS_PATH as string 11 | const GIFS_PATH = process.env.GIFS_PATH as string 12 | 13 | const format = z.object({ 14 | messageToSendBack: z.string(), 15 | gifUrlToSendAfterMessage: z.nullable(z.string()) 16 | }) 17 | 18 | const model = process.env.MODEL as string 19 | const persons: person[] = readJson(PERSONS_PATH) 20 | const client = new Client(); 21 | let convs: {[index:string]: convMsg[] } = getConvs(CONVS_PATH) 22 | const convMap = new Map() 23 | 24 | console.log(makeSystemMessage(GIFS_PATH)) 25 | 26 | client.once('ready', async () => { 27 | console.log(`${client.user!.username} is ready!`); 28 | }); 29 | 30 | client.on("messageCreate", async message => { 31 | if(!checkValidity(message, persons)) return 32 | 33 | console.log(`Message from ${persons.find(p => p.id === message.author.id)?.username}: ${message.content}`) 34 | 35 | const prompt = message.content 36 | const userId = message.author.id 37 | if(!convs[userId]) convs[userId] = [ 38 | { 39 | role: "system", 40 | content: makeSystemMessage(GIFS_PATH) 41 | } 42 | ] 43 | 44 | const userConv = convs[userId] 45 | const interactionId = crypto.randomUUID() 46 | if(convMap.has(userId) && userConv.at(-1) && userConv.at(-1)!.role === "user") userConv.at(-1)!.content += `\n\n${prompt}` 47 | else { 48 | message.channel.sendTyping() 49 | userConv.push({ role: "user", content: prompt }) 50 | } 51 | 52 | convMap.set(userId, interactionId) 53 | 54 | const output = await ollama.chat({ model, messages: [...userConv], format: zodToJsonSchema(format) }) 55 | if(convMap.get(userId) !== interactionId) return 56 | convMap.delete(userId) 57 | let data: {messageToSendBack: string, gifUrlToSendAfterMessage: string} = JSON.parse(output.message.content) 58 | userConv.push(output.message as convMsg) 59 | 60 | saveConvs(CONVS_PATH, convs) 61 | await message.channel.send(data!.messageToSendBack) 62 | if( 63 | data!.gifUrlToSendAfterMessage && 64 | data!.gifUrlToSendAfterMessage !== "" 65 | ) await message.channel.send(data!.gifUrlToSendAfterMessage) 66 | }); 67 | 68 | client.login(process.env.TOKEN); -------------------------------------------------------------------------------- /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": [], /* 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 | // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */ 40 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ 41 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ 42 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ 43 | // "noUncheckedSideEffectImports": true, /* Check side effect imports. */ 44 | // "resolveJsonModule": true, /* Enable importing .json files. */ 45 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ 46 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 47 | 48 | /* JavaScript Support */ 49 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 50 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 51 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 52 | 53 | /* Emit */ 54 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 55 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 56 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 57 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 58 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 59 | // "noEmit": true, /* Disable emitting files from a compilation. */ 60 | // "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. */ 61 | "outDir": "./dist", /* Specify an output folder for all emitted files. */ 62 | // "removeComments": true, /* Disable emitting comments. */ 63 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 64 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 65 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 66 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 67 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 68 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 69 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 70 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 71 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 72 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 73 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 74 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 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 | // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ 80 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 81 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ 82 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 83 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 84 | 85 | /* Type Checking */ 86 | "strict": true, /* Enable all strict type-checking options. */ 87 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 88 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 89 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 90 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 91 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 92 | // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */ 93 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 94 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 95 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 96 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 97 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 98 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 99 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 100 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 101 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 102 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 103 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 104 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 105 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 106 | 107 | /* Completeness */ 108 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 109 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 110 | } 111 | } 112 | --------------------------------------------------------------------------------