├── .all-contributorsrc ├── .dockerignore ├── .editorconfig ├── .env-sample ├── .eslintrc ├── .github ├── FUNDING.yml └── workflows │ ├── codeql.yml │ ├── deploy.yml │ └── test.yml ├── .gitignore ├── .husky ├── .gitignore └── pre-commit ├── .ignore ├── .mocharc.js ├── .nvmrc ├── .prettierrc ├── .vscode └── settings.json ├── LICENSE ├── README.md ├── app.js ├── count-messages.ts ├── docker-compose.yml ├── fly.toml ├── package.json ├── src ├── app.ts ├── commands │ ├── aoc.spec.ts │ ├── aoc.ts │ ├── co.spec.ts │ ├── co.ts │ ├── execute.spec.ts │ ├── execute.ts │ ├── index.spec.ts │ ├── index.ts │ ├── karma.spec.ts │ ├── karma.ts │ ├── kocopoly.ts │ ├── kocopoly │ │ └── kocopolyUtils.ts │ ├── link.ts │ ├── m1.ts │ ├── markdown.ts │ ├── mdn.ts │ ├── mongodb.ts │ ├── mydevil.ts │ ├── npm.ts │ ├── odpowiedz.ts │ ├── praca.spec.ts │ ├── praca.ts │ ├── prs.ts │ ├── prune.spec.ts │ ├── prune.ts │ ├── quiz.ts │ ├── reflink.spec.ts │ ├── reflink.ts │ ├── regulamin.ts │ ├── roll.spec.ts │ ├── roll.ts │ ├── server.ts │ ├── skierowanie.spec.ts │ ├── skierowanie.ts │ ├── spotify.ts │ ├── stackoverflow.spec.ts │ ├── stackoverflow.ts │ ├── stats.ts │ ├── summon.ts │ ├── towarticle.ts │ ├── wiki.spec.ts │ ├── wiki.ts │ ├── xd.ts │ ├── xkcd.cache.json │ ├── xkcd.ts │ ├── yesno.ts │ ├── youtube.spec.ts │ └── youtube.ts ├── config.ts ├── cron │ └── roles │ │ ├── index.ts │ │ ├── karma.ts │ │ └── stats.ts ├── data │ └── karma.ts ├── db.ts ├── grzes.json ├── handle-github-webhook.spec.ts ├── handle-github-webhook.ts ├── http-server.ts ├── index.ts ├── morritz.json ├── thx.spec.ts ├── thx.ts ├── types.ts └── utils.ts ├── ssh-script-deploy.sh ├── test ├── before-each.spec.ts ├── mocks.spec.ts ├── mocks.ts └── setup-env.js ├── tsconfig.json ├── typings ├── dom.d.ts └── monitorss │ └── index.d.ts ├── xkcd.js └── yarn.lock /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "projectName": "typeofweb-discord-bot", 3 | "projectOwner": "typeofweb", 4 | "repoType": "github", 5 | "repoHost": "https://github.com", 6 | "files": [ 7 | "README.md" 8 | ], 9 | "imageSize": 100, 10 | "commit": true, 11 | "commitConvention": "gitmoji", 12 | "contributors": [ 13 | { 14 | "login": "mmiszy", 15 | "name": "Michał Miszczyszyn", 16 | "avatar_url": "https://avatars0.githubusercontent.com/u/1338731?v=4", 17 | "profile": "https://typeofweb.com", 18 | "contributions": [ 19 | "code", 20 | "ideas", 21 | "infra", 22 | "review" 23 | ] 24 | }, 25 | { 26 | "login": "Deeadline", 27 | "name": "Deeadline", 28 | "avatar_url": "https://avatars3.githubusercontent.com/u/26546280?v=4", 29 | "profile": "https://github.com/Deeadline", 30 | "contributions": [ 31 | "code", 32 | "ideas" 33 | ] 34 | }, 35 | { 36 | "login": "przytrzask", 37 | "name": "przytrzask", 38 | "avatar_url": "https://avatars2.githubusercontent.com/u/20127089?v=4", 39 | "profile": "http://trzasq.pl", 40 | "contributions": [ 41 | "code", 42 | "ideas" 43 | ] 44 | }, 45 | { 46 | "login": "nanoDW", 47 | "name": "nanoDW", 48 | "avatar_url": "https://avatars2.githubusercontent.com/u/37413661?v=4", 49 | "profile": "https://github.com/nanoDW", 50 | "contributions": [ 51 | "code", 52 | "ideas" 53 | ] 54 | }, 55 | { 56 | "login": "Secrus", 57 | "name": "Secrus", 58 | "avatar_url": "https://avatars2.githubusercontent.com/u/26322915?v=4", 59 | "profile": "https://github.com/Secrus", 60 | "contributions": [ 61 | "code", 62 | "ideas", 63 | "doc" 64 | ] 65 | }, 66 | { 67 | "login": "larto42", 68 | "name": "larto42", 69 | "avatar_url": "https://avatars3.githubusercontent.com/u/16961273?v=4", 70 | "profile": "https://github.com/larto42", 71 | "contributions": [ 72 | "doc" 73 | ] 74 | }, 75 | { 76 | "login": "Razi91", 77 | "name": "jkonieczny", 78 | "avatar_url": "https://avatars0.githubusercontent.com/u/5995454?v=4", 79 | "profile": "https://github.com/Razi91", 80 | "contributions": [ 81 | "code", 82 | "ideas", 83 | "test", 84 | "security" 85 | ] 86 | }, 87 | { 88 | "login": "D0man", 89 | "name": "Kuba Domański", 90 | "avatar_url": "https://avatars2.githubusercontent.com/u/22179216?v=4", 91 | "profile": "https://github.com/D0man", 92 | "contributions": [ 93 | "code" 94 | ] 95 | }, 96 | { 97 | "login": "Survikrowa", 98 | "name": "Survikrowa", 99 | "avatar_url": "https://avatars2.githubusercontent.com/u/35381167?v=4", 100 | "profile": "https://github.com/Survikrowa", 101 | "contributions": [ 102 | "code", 103 | "ideas" 104 | ] 105 | }, 106 | { 107 | "login": "AdamSiekierski", 108 | "name": "Adam Siekierski", 109 | "avatar_url": "https://avatars0.githubusercontent.com/u/24841038?v=4", 110 | "profile": "http://siekierski.ml", 111 | "contributions": [ 112 | "code", 113 | "ideas" 114 | ] 115 | }, 116 | { 117 | "login": "olafsulich", 118 | "name": "Olaf Sulich", 119 | "avatar_url": "https://avatars1.githubusercontent.com/u/46969484?v=4", 120 | "profile": "http://frontlive.pl", 121 | "contributions": [ 122 | "code" 123 | ] 124 | }, 125 | { 126 | "login": "Eghizio", 127 | "name": "Jakub Wąsik", 128 | "avatar_url": "https://avatars.githubusercontent.com/u/32049761?v=4", 129 | "profile": "https://github.com/Eghizio", 130 | "contributions": [ 131 | "code" 132 | ] 133 | }, 134 | { 135 | "login": "kbkk", 136 | "name": "Jakub Kisielewski", 137 | "avatar_url": "https://avatars.githubusercontent.com/u/6276426?v=4", 138 | "profile": "https://github.com/kbkk", 139 | "contributions": [ 140 | "code" 141 | ] 142 | }, 143 | { 144 | "login": "drillprop", 145 | "name": "Bartosz Dryl", 146 | "avatar_url": "https://avatars.githubusercontent.com/u/51168865?v=4", 147 | "profile": "https://github.com/drillprop", 148 | "contributions": [ 149 | "code" 150 | ] 151 | }, 152 | { 153 | "login": "jundymek", 154 | "name": "Łukasz Dymek", 155 | "avatar_url": "https://avatars.githubusercontent.com/u/24244872?v=4", 156 | "profile": "https://jundymek.com/", 157 | "contributions": [ 158 | "code" 159 | ] 160 | }, 161 | { 162 | "login": "kamiloox", 163 | "name": "kamiloox", 164 | "avatar_url": "https://avatars.githubusercontent.com/u/45523480?v=4", 165 | "profile": "https://github.com/kamiloox", 166 | "contributions": [ 167 | "code" 168 | ] 169 | }, 170 | { 171 | "login": "Bartek532", 172 | "name": "Bartosz Zagrodzki", 173 | "avatar_url": "https://avatars.githubusercontent.com/u/57185551?v=4", 174 | "profile": "http://bartek532.github.io/portfolio", 175 | "contributions": [ 176 | "code", 177 | "doc" 178 | ] 179 | }, 180 | { 181 | "login": "michalczukm", 182 | "name": "Michał Michalczuk", 183 | "avatar_url": "https://avatars.githubusercontent.com/u/6861120?v=4", 184 | "profile": "https://michalczukm.xyz", 185 | "contributions": [ 186 | "code", 187 | "bug" 188 | ] 189 | }, 190 | { 191 | "login": "AdiPol1359", 192 | "name": "Adrian Polak", 193 | "avatar_url": "https://avatars.githubusercontent.com/u/27779154?v=4", 194 | "profile": "https://projectcode.pl", 195 | "contributions": [ 196 | "code" 197 | ] 198 | }, 199 | { 200 | "login": "KrallXZ", 201 | "name": "Karol Syta", 202 | "avatar_url": "https://avatars.githubusercontent.com/u/6277709?v=4", 203 | "profile": "https://github.com/KrallXZ", 204 | "contributions": [ 205 | "code", 206 | "ideas" 207 | ] 208 | } 209 | ], 210 | "contributorsPerLine": 3, 211 | "skipCi": true 212 | } 213 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # flyctl launch added from .gitignore 2 | **/node_modules 3 | **/.tmp 4 | **/.idea 5 | **/.DS_Store 6 | **/.version 7 | **/dist 8 | **/.history 9 | 10 | # Logs 11 | **/logs 12 | **/*.log 13 | **/npm-debug.log* 14 | **/yarn-debug.log* 15 | **/yarn-error.log* 16 | 17 | # Runtime data 18 | **/pids 19 | **/*.pid 20 | **/*.seed 21 | **/*.pid.lock 22 | 23 | **/junit 24 | **/test-results.xml 25 | 26 | # Directory for instrumented libs generated by jscoverage/JSCover 27 | **/lib-cov 28 | 29 | # Coverage directory used by tools like istanbul 30 | **/coverage 31 | 32 | # nyc test coverage 33 | **/.nyc_output 34 | 35 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 36 | **/.grunt 37 | 38 | # Bower dependency directory (https://bower.io/) 39 | **/bower_components 40 | 41 | # node-waf configuration 42 | **/.lock-wscript 43 | 44 | # Compiled binary addons (http://nodejs.org/api/addons.html) 45 | **/build/Release 46 | 47 | # Dependency directories 48 | **/node_modules 49 | **/jspm_packages 50 | 51 | # Optional npm cache directory 52 | **/.npm 53 | 54 | # Optional eslint cache 55 | **/.eslintcache 56 | 57 | # Optional REPL history 58 | **/.node_repl_history 59 | 60 | # Output of 'npm pack' 61 | **/*.tgz 62 | 63 | # Yarn Integrity file 64 | **/.yarn-integrity 65 | 66 | # dotenv environment variables file 67 | **/.env 68 | 69 | **/package-lock.json 70 | **/*.tsbuildinfo 71 | **/grzesiu.js 72 | 73 | # flyctl launch added from .husky/.gitignore 74 | .husky/**/_ 75 | 76 | # flyctl launch added from .husky/_/.gitignore 77 | .husky/_/**/* 78 | fly.toml 79 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | 8 | [*] 9 | 10 | # Change these settings to your own preference 11 | indent_style = space 12 | indent_size = 2 13 | 14 | # We recommend you to keep these unchanged 15 | end_of_line = lf 16 | charset = utf-8 17 | trim_trailing_whitespace = true 18 | insert_final_newline = true 19 | 20 | [*.md] 21 | trim_trailing_whitespace = false 22 | -------------------------------------------------------------------------------- /.env-sample: -------------------------------------------------------------------------------- 1 | DISCORD_BOT_TOKEN= 2 | MONGO_URL=mongodb://localhost:27017/bot 3 | 4 | YOUTUBE_API_KEY= 5 | 6 | SPOTIFY_CLIENT_ID= 7 | SPOTIFY_SECRET= 8 | 9 | GITHUB_WEBHOOK_SECRET= 10 | GITHUB_WEBHOOK_DISCORD_URL= 11 | 12 | ALGOLIA_APP_ID= 13 | ALGOLIA_API_KEY= 14 | ALGOLIA_INDEX_NAME= 15 | 16 | OPENAI_API_KEY= 17 | 18 | ADVENT_OF_CODE_SESSION= 19 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "parserOptions": { 5 | "sourceType": "module", 6 | "project": "tsconfig.json", 7 | "ecmaVersion": 2019 8 | }, 9 | "plugins": ["functional", "@typescript-eslint"], 10 | "extends": [ 11 | "prettier", 12 | "plugin:import/errors", 13 | "plugin:import/typescript", 14 | "plugin:@typescript-eslint/recommended-requiring-type-checking" 15 | ], 16 | "rules": { 17 | "no-const-assign": "error", 18 | "no-param-reassign": "error", 19 | "prefer-const": "error", 20 | "no-var": "error", 21 | "require-await": "error", 22 | "import/no-anonymous-default-export": "error", 23 | "import/no-default-export": "error", 24 | "import/dynamic-import-chunkname": "error", 25 | "import/order": ["error", { "newlines-between": "always", "alphabetize": { "order": "asc" } }], 26 | "import/no-duplicates": "error", 27 | "import/no-cycle": "error", 28 | "@typescript-eslint/no-unused-vars": "off", 29 | "@typescript-eslint/no-unsafe-return": "off", 30 | "@typescript-eslint/consistent-type-imports": "error", 31 | "@typescript-eslint/no-misused-promises": "off", 32 | "@typescript-eslint/restrict-template-expressions": [ 33 | "error", 34 | { "allowNumber": true, "allowBoolean": true } 35 | ], 36 | "functional/no-let": [ 37 | "error", 38 | { 39 | "allowLocalMutation": true, 40 | "ignorePattern": "^mutable" 41 | } 42 | ], 43 | "functional/prefer-readonly-type": "error", 44 | "functional/no-this-expression": "error", 45 | "functional/no-loop-statement": "error", 46 | 47 | "typescript-eslint/no-unsafe-assignment": "off", 48 | "typescript-eslint/no-unsafe-call": "off", 49 | "typescript-eslint/no-unsafe-member-access": "off" 50 | }, 51 | "overrides": [ 52 | { 53 | "files": ["src/commands/**.ts"], 54 | "rules": { 55 | "import/no-default-export": 0 56 | } 57 | }, 58 | { 59 | "files": ["**/*.spec.ts"], 60 | "rules": { 61 | "no-magic-numbers": 0, 62 | "no-implicit-dependencies": 0 63 | } 64 | } 65 | ] 66 | } 67 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [typeofweb] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: typeofweb 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL" 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | schedule: 9 | - cron: "37 12 * * 6" 10 | 11 | jobs: 12 | analyze: 13 | name: Analyze 14 | runs-on: ubuntu-latest 15 | permissions: 16 | actions: read 17 | contents: read 18 | security-events: write 19 | 20 | strategy: 21 | fail-fast: false 22 | matrix: 23 | language: [ javascript ] 24 | 25 | steps: 26 | - name: Checkout 27 | uses: actions/checkout@v3 28 | 29 | - name: Initialize CodeQL 30 | uses: github/codeql-action/init@v2 31 | with: 32 | languages: ${{ matrix.language }} 33 | queries: +security-and-quality 34 | 35 | - name: Autobuild 36 | uses: github/codeql-action/autobuild@v2 37 | 38 | - name: Perform CodeQL Analysis 39 | uses: github/codeql-action/analyze@v2 40 | with: 41 | category: "/language:${{ matrix.language }}" 42 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | 7 | env: 8 | FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }} 9 | 10 | jobs: 11 | deploy: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | - uses: superfly/flyctl-actions/setup-flyctl@master 17 | - run: flyctl deploy --remote-only 18 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | test: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v2 14 | 15 | - name: Get Node.js version 16 | id: nvm 17 | run: echo ::set-output name=NVMRC::$(cat .nvmrc) 18 | 19 | - name: Setup Node.js 20 | uses: actions/setup-node@v2 21 | with: 22 | node-version: ${{ steps.nvm.outputs.NVMRC }} 23 | 24 | - name: Get yarn cache directory path 25 | id: yarn-cache-dir-path 26 | run: echo "::set-output name=dir::$(yarn cache dir)" 27 | 28 | - uses: actions/cache@v2 29 | id: yarn-cache 30 | with: 31 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 32 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 33 | restore-keys: | 34 | ${{ runner.os }}-yarn- 35 | 36 | - name: install, and test 37 | run: | 38 | yarn --frozen-lockfile 39 | yarn test:ci 40 | env: 41 | CI: true 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .tmp 3 | .idea 4 | .DS_Store 5 | .version 6 | dist 7 | .history 8 | 9 | # Logs 10 | logs 11 | *.log 12 | npm-debug.log* 13 | yarn-debug.log* 14 | yarn-error.log* 15 | 16 | # Runtime data 17 | pids 18 | *.pid 19 | *.seed 20 | *.pid.lock 21 | 22 | junit 23 | test-results.xml 24 | 25 | # Directory for instrumented libs generated by jscoverage/JSCover 26 | lib-cov 27 | 28 | # Coverage directory used by tools like istanbul 29 | coverage 30 | 31 | # nyc test coverage 32 | .nyc_output 33 | 34 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 35 | .grunt 36 | 37 | # Bower dependency directory (https://bower.io/) 38 | bower_components 39 | 40 | # node-waf configuration 41 | .lock-wscript 42 | 43 | # Compiled binary addons (http://nodejs.org/api/addons.html) 44 | build/Release 45 | 46 | # Dependency directories 47 | node_modules/ 48 | jspm_packages/ 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Optional REPL history 57 | .node_repl_history 58 | 59 | # Output of 'npm pack' 60 | *.tgz 61 | 62 | # Yarn Integrity file 63 | .yarn-integrity 64 | 65 | # dotenv environment variables file 66 | .env 67 | 68 | package-lock.json 69 | *.tsbuildinfo 70 | grzesiu.js 71 | -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn lint-staged 5 | -------------------------------------------------------------------------------- /.ignore: -------------------------------------------------------------------------------- 1 | grzes.json 2 | -------------------------------------------------------------------------------- /.mocharc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | require: ['test/setup-env.js', 'source-map-support/register'], 3 | timeout: 600000, 4 | bail: true, 5 | exit: true, 6 | }; 7 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 18 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": true, 3 | "singleQuote": true, 4 | "trailingComma": "all", 5 | "printWidth": 100 6 | } 7 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true, 3 | "editor.defaultFormatter": "esbenp.prettier-vscode", 4 | "typescript.tsdk": "node_modules/typescript/lib", 5 | "eslint.packageManager": "yarn", 6 | "eslint.run": "onSave", 7 | "editor.codeActionsOnSave": { 8 | // "source.fixAll": true 9 | }, 10 | "typescript.preferences.importModuleSpecifier": "relative" 11 | } 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | typeofweb-discord-bot – a Discord bot 633 | Copyright © 2020 Type of Web - Michał Miszczyszyn 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Type of Web Discord Bot 2 | 3 | 4 | 5 | [![All Contributors](https://img.shields.io/badge/all_contributors-20-orange.svg?style=flat-square)](#contributors-) 6 | 7 | 8 | 9 | ## Getting Started 10 | 11 | #### Prepare project 12 | 13 | Run `yarn` to install all dependencies 14 | 15 | _[Based on windows system]_ 16 | 17 | If an error with Python occurs open the system console with admin privileges and type: 18 | 19 | ``` 20 | yarn --add-python-to-path='true' --debug install --global windows-build-tools 21 | ``` 22 | 23 | If that was the case run again `yarn` to install dependencies properly. 24 | 25 | #### Setup environmental variables 26 | 27 | Create `.env.dev` file based on `.env.dev-sample` (just copy and rename it). Fill the API keys with `0` if you don't have them. 28 | 29 | #### Connect to development bot 30 | 31 | Create a new discord server where you will be testing your bot. 32 | 33 | [Follow this tutorial to create a new bot.](https://github.com/reactiflux/discord-irc/wiki/Creating-a-discord-bot-&-getting-a-token) Then add it to your server. 34 | 35 | Use the bot token in `.env.dev` file. 36 | 37 | #### Run the server 38 | 39 | Use `yarn dev` to start the server. 40 | 41 | You should get this in your console, which suggests that everything went ok. 42 | 43 | ``` 44 | Server running! 45 | Logged in as [Bot Name]! 46 | ``` 47 | 48 | _You will probably get some errors like "Failed to connect to database" as well. Don't worry about them if you don't need the database._ 49 | 50 | When you log into the discord server you should see that your Bot is active. 51 | You can use one of the existing commands like `!co` to try it out :) 52 | 53 | ## Contributors ✨ 54 | 55 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 |
Michał Miszczyszyn
Michał Miszczyszyn

💻 🤔 🚇 👀
Deeadline
Deeadline

💻 🤔
przytrzask
przytrzask

💻 🤔
nanoDW
nanoDW

💻 🤔
Secrus
Secrus

💻 🤔 📖
larto42
larto42

📖
jkonieczny
jkonieczny

💻 🤔 ⚠️ 🛡️
Kuba Domański
Kuba Domański

💻
Survikrowa
Survikrowa

💻 🤔
Adam Siekierski
Adam Siekierski

💻 🤔
Olaf Sulich
Olaf Sulich

💻
Jakub Wąsik
Jakub Wąsik

💻
Jakub Kisielewski
Jakub Kisielewski

💻
Bartosz Dryl
Bartosz Dryl

💻
Łukasz Dymek
Łukasz Dymek

💻
kamiloox
kamiloox

💻
Bartosz Zagrodzki
Bartosz Zagrodzki

💻 📖
Michał Michalczuk
Michał Michalczuk

💻 🐛
Adrian Polak
Adrian Polak

💻
Karol Syta
Karol Syta

💻 🤔
98 | 99 | 100 | 101 | 102 | 103 | 104 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! 105 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | console.log(process.versions); 2 | require('./dist/src/index.js'); 3 | -------------------------------------------------------------------------------- /count-messages.ts: -------------------------------------------------------------------------------- 1 | import Discord, { GatewayIntentBits } from 'discord.js'; 2 | import fetch from 'node-fetch'; 3 | 4 | import { getConfig } from './src/config'; 5 | import { getStatsCollection, initDb } from './src/db'; 6 | import { getWeekNumber } from './src/utils'; 7 | 8 | /* eslint-disable @typescript-eslint/no-unsafe-call */ 9 | /* eslint-disable @typescript-eslint/no-unsafe-member-access */ 10 | if (process.env.NODE_ENV !== 'test') { 11 | require('dotenv').config(); 12 | } 13 | 14 | const API_URL = `https://discord.com/api/v9`; 15 | const GUILD_ID = `440163731704643589`; 16 | 17 | const personalToken = getConfig('PERSONAL_TOKEN'); 18 | 19 | async function init() { 20 | // Monday 21 | if (new Date().getDay() !== 1) { 22 | console.log('Not Monday – nothing to do here!'); 23 | process.exit(0); 24 | } 25 | 26 | const client = new Discord.Client({ 27 | intents: [ 28 | GatewayIntentBits.Guilds, 29 | GatewayIntentBits.GuildMessages, 30 | GatewayIntentBits.MessageContent, 31 | GatewayIntentBits.GuildMembers, 32 | ], 33 | }); 34 | await client.login(getConfig('DISCORD_BOT_TOKEN')); 35 | 36 | const guild = await client.guilds.fetch(GUILD_ID); 37 | const members = await guild.members.fetch({}); 38 | 39 | const db = await initDb(); 40 | const statsCollection = getStatsCollection(db); 41 | 42 | const [year, week] = getWeekNumber(new Date()); 43 | const yearWeek = `${year}-${week}`; 44 | 45 | await members.reduce(async (acc, member) => { 46 | await acc; 47 | 48 | const existingMember = await statsCollection.findOne({ 49 | memberId: member.id, 50 | }); 51 | if (existingMember && !existingMember.messagesCount) { 52 | // console.log(`Skipping… existing`); 53 | return acc; 54 | } 55 | 56 | const countedThisWeek = await statsCollection.count({ 57 | memberId: member.id, 58 | yearWeek, 59 | }); 60 | if (countedThisWeek) { 61 | // console.log(`Skipping… countedThisWeek`); 62 | return acc; 63 | } 64 | 65 | const messagesCount = await getMemberMessagesCount(member.id); 66 | if (!messagesCount) { 67 | // console.log(`Skipping… !messagesCount`); 68 | return acc; 69 | } 70 | 71 | const result = await statsCollection.updateOne( 72 | { 73 | memberId: member.id, 74 | yearWeek, 75 | }, 76 | { 77 | $set: { 78 | memberId: member.id, 79 | memberName: member.displayName, 80 | messagesCount, 81 | updatedAt: new Date(), 82 | yearWeek, 83 | }, 84 | }, 85 | { upsert: true }, 86 | ); 87 | console.log({ memberId: member.id, memberName: member.displayName, messagesCount, result }); 88 | }, Promise.resolve()); 89 | } 90 | 91 | init() 92 | .then(() => { 93 | process.exit(0); 94 | }) 95 | .catch((err) => { 96 | console.error(err); 97 | process.exit(1); 98 | }); 99 | 100 | type Response = 101 | | { readonly total_results?: number; readonly retry_after?: undefined } 102 | | { readonly total_results?: undefined; readonly retry_after: number }; 103 | 104 | export async function getMemberMessagesCount(memberId: string): Promise { 105 | const res = await fetch(`${API_URL}/guilds/${GUILD_ID}/messages/search?author_id=${memberId}`, { 106 | headers: { 107 | authorization: personalToken, 108 | }, 109 | method: 'GET', 110 | }); 111 | const json = (await res.json()) as Response; 112 | 113 | if (json.retry_after) { 114 | console.log(json); 115 | await wait(json.retry_after * 1000); 116 | return getMemberMessagesCount(memberId); 117 | } 118 | 119 | // try to overcome rate limiting 120 | await wait(1000); 121 | return json.total_results; 122 | } 123 | 124 | function wait(ms: number) { 125 | return new Promise((resolve) => setTimeout(resolve, ms)); 126 | } 127 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | 3 | services: 4 | typeofweb_bot_mongo: 5 | image: mvertes/alpine-mongo 6 | ports: 7 | - '27017:27017' 8 | -------------------------------------------------------------------------------- /fly.toml: -------------------------------------------------------------------------------- 1 | # fly.toml app configuration file generated for typeofweb-discord-bot-fragrant-wind-7657 on 2024-04-13T22:58:23-07:00 2 | # 3 | # See https://fly.io/docs/reference/configuration/ for information about how to use this file. 4 | # 5 | 6 | app = "typeofweb-discord-bot" 7 | primary_region = "waw" 8 | kill_signal = "SIGINT" 9 | kill_timeout = "5s" 10 | 11 | [experimental] 12 | auto_rollback = true 13 | 14 | [build] 15 | builder = "heroku/builder:22" 16 | 17 | [env] 18 | PORT = "8080" 19 | 20 | [[services]] 21 | protocol = "tcp" 22 | internal_port = 8080 23 | processes = ["app"] 24 | 25 | [[services.ports]] 26 | port = 80 27 | handlers = ["http"] 28 | force_https = true 29 | 30 | [[services.ports]] 31 | port = 443 32 | handlers = ["tls", "http"] 33 | 34 | [services.concurrency] 35 | type = "connections" 36 | hard_limit = 25 37 | soft_limit = 20 38 | 39 | [[services.tcp_checks]] 40 | interval = "15s" 41 | timeout = "2s" 42 | grace_period = "1s" 43 | 44 | [[vm]] 45 | memory = "512mb" 46 | cpu_kind = "shared" 47 | cpus = 1 48 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "typeofweb-discord-bot", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "private": true, 7 | "scripts": { 8 | "start": "NODE_ENV=production node app.js", 9 | "dev": "tsc-watch --onSuccess \"node ./dist/src/index.js\"", 10 | "eslint": "eslint --fix --cache", 11 | "tsc": "tsc --noEmit -p tsconfig.json", 12 | "lint": "yarn tsc && yarn eslint", 13 | "test": "cross-env NODE_ENV=test yarn lint && yarn test:unit", 14 | "test:ci": "cross-env NODE_ENV=test yarn lint && yarn coverage", 15 | "test:unit": "cross-env NODE_ENV=test yarn mocha --file test/before-each.spec.ts 'src/**/*.spec.ts'", 16 | "coverage": "nyc yarn test:unit", 17 | "mocha": "mocha", 18 | "clean": "rm -rf dist", 19 | "build": "yarn clean && tsc && rsync -av --exclude='*.ts' src/** dist/src/", 20 | "prepare": "husky install" 21 | }, 22 | "keywords": [], 23 | "author": "Michał Miszczyszyn (https://typeofweb.com/)", 24 | "license": "AGPL", 25 | "dependencies": { 26 | "@types/bluebird": "3.5.36", 27 | "algoliasearch": "4.14.2", 28 | "bluebird": "3.7.2", 29 | "bufferutil": "4.0.6", 30 | "discord.js": "14.3.0", 31 | "dotenv": "16.0.2", 32 | "isolated-vm": "4.4.1", 33 | "mongodb": "4.9.1", 34 | "monitorss": "6.14.11", 35 | "natural": "5.2.3", 36 | "node-cache": "5.1.2", 37 | "node-fetch": "2.6.1", 38 | "openai": "2.0.2", 39 | "polish-plurals": "1.1.0", 40 | "request": "2.88.2", 41 | "request-promise": "4.2.6", 42 | "secure-json-parse": "2.5.0", 43 | "typescript": "4.8.2", 44 | "zlib-sync": "0.1.7" 45 | }, 46 | "devDependencies": { 47 | "@types/chai": "4.3.3", 48 | "@types/chai-as-promised": "7.1.5", 49 | "@types/dotenv": "8.2.0", 50 | "@types/mocha": "9.1.1", 51 | "@types/natural": "5.1.1", 52 | "@types/nock": "11.1.0", 53 | "@types/node": "18.7.14", 54 | "@types/node-fetch": "2.6.2", 55 | "@types/secure-json-parse": "1.0.3", 56 | "@types/sinon": "10.0.13", 57 | "@types/sinon-chai": "3.2.8", 58 | "@typescript-eslint/eslint-plugin": "5.36.1", 59 | "@typescript-eslint/parser": "5.36.1", 60 | "chai": "4.3.6", 61 | "chai-as-promised": "7.1.1", 62 | "cross-env": "7.0.3", 63 | "eslint": "8.23.0", 64 | "eslint-config-prettier": "8.5.0", 65 | "eslint-plugin-functional": "4.2.2", 66 | "eslint-plugin-import": "2.26.0", 67 | "husky": "8.0.1", 68 | "lint-staged": "13.0.3", 69 | "mocha": "10.0.0", 70 | "nock": "13.2.9", 71 | "nyc": "15.1.0", 72 | "prettier": "2.7.1", 73 | "sinon": "14.0.0", 74 | "sinon-chai": "3.7.0", 75 | "source-map-support": "0.5.21", 76 | "ts-node": "10.9.1", 77 | "tsc-watch": "5.0.3" 78 | }, 79 | "lint-staged": { 80 | "**/*.ts": [ 81 | "yarn prettier --write" 82 | ], 83 | "**/*.{md,js,json}": [ 84 | "yarn prettier --write" 85 | ] 86 | }, 87 | "engines": { 88 | "node": "^18.0.0" 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/app.ts: -------------------------------------------------------------------------------- 1 | import Discord, { GatewayIntentBits } from 'discord.js'; 2 | import MonitoRSS from 'monitorss'; 3 | import type { ClientConfig } from 'monitorss'; 4 | import Cache from 'node-cache'; 5 | 6 | import { handleCommand } from './commands'; 7 | import { KARMA_REGEX } from './commands/karma'; 8 | import { messageToReflinks } from './commands/reflink'; 9 | import { getConfig } from './config'; 10 | import { updateKarmaRoles } from './cron/roles/karma'; 11 | import { updateStatsRoles } from './cron/roles/stats'; 12 | import { getStatsCollection, initDb } from './db'; 13 | import { createHttpServer } from './http-server'; 14 | import { thx } from './thx'; 15 | import { InvalidUsageError } from './types'; 16 | import { getWeekNumber, wrapErr } from './utils'; 17 | 18 | const MESSAGE_COLLECTOR_CACHE_S = 60 * 60; 19 | const messageCollectorCache = new Cache({ stdTTL: MESSAGE_COLLECTOR_CACHE_S }); 20 | 21 | const client = new Discord.Client({ 22 | intents: [ 23 | GatewayIntentBits.Guilds, 24 | GatewayIntentBits.GuildMessages, 25 | GatewayIntentBits.MessageContent, 26 | GatewayIntentBits.GuildMembers, 27 | ], 28 | }); 29 | 30 | const settings: { readonly setPresence: boolean; readonly config: ClientConfig } = { 31 | setPresence: true, 32 | config: { 33 | bot: { 34 | token: getConfig('DISCORD_BOT_TOKEN'), 35 | }, 36 | database: { 37 | uri: getConfig('MONGO_URL'), 38 | connection: { 39 | useNewUrlParser: true, 40 | }, 41 | }, 42 | feeds: { 43 | refreshRateMinutes: 10, 44 | timezone: 'Europe/Warsaw', 45 | dateFormat: 'LLL', 46 | dateLanguage: 'pl', 47 | dateLanguageList: ['pl'], 48 | sendFirstCycle: true, 49 | cycleMaxAge: 5, 50 | }, 51 | }, 52 | }; 53 | 54 | client.on('ready', () => { 55 | console.log(`Logged in as ${client.user?.tag!}!`); 56 | }); 57 | 58 | // eslint-disable-next-line functional/prefer-readonly-type 59 | const errors: Error[] = []; 60 | client.on('error', (error) => { 61 | errors.push(error); 62 | }); 63 | 64 | // eslint-disable-next-line functional/prefer-readonly-type 65 | const warnings: string[] = []; 66 | client.on('warn', (warning) => { 67 | warnings.push(warning); 68 | }); 69 | 70 | // eslint-disable-next-line functional/prefer-readonly-type 71 | const debugs: string[] = []; 72 | const MAX_DEBUG_LENGTH = 100; 73 | client.on('debug', (debug) => { 74 | debugs.push(debug.replace(getConfig('DISCORD_BOT_TOKEN'), 'DISCORD_BOT_TOKEN')); 75 | if (debugs.length > MAX_DEBUG_LENGTH) { 76 | debugs.shift(); 77 | } 78 | }); 79 | 80 | function isCommand(msg: Discord.Message) { 81 | return msg.content.startsWith(getConfig('PREFIX')) || KARMA_REGEX.test(msg.content); 82 | } 83 | 84 | // const ROLE_MUTED_NAME = 'muted' as const; 85 | // const MAX_MENTIONS_PER_MESSAGE = 10; 86 | 87 | client.on('messageCreate', async (msg) => { 88 | if (msg.author.bot) { 89 | return; 90 | } 91 | 92 | // if ((msg.mentions.members?.size ?? 0) > MAX_MENTIONS_PER_MESSAGE) { 93 | // const roleManager = await msg.guild?.roles.fetch(); 94 | // const roleMuted = roleManager?.cache.find((v) => v.name === ROLE_MUTED_NAME); 95 | // console.log(roleMuted); 96 | // // if (roleMuted) { 97 | // // msg.member?.roles.add(roleMuted); 98 | // // } 99 | // } 100 | 101 | if (msg.content === `(╯°□°)╯︵ ┻━┻`) { 102 | await msg.channel.send(`┬─┬ノ( ◕◡◕ ノ)`); 103 | return; 104 | } 105 | 106 | if (isCommand(msg)) { 107 | try { 108 | const collector = msg.channel.createMessageCollector({ 109 | filter: (m: Discord.Message) => m.author.id === client.user?.id, 110 | }); 111 | await handleCommand(msg); 112 | const ids = collector.collected.map((m) => m.id); 113 | messageCollectorCache.set(msg.id, ids); 114 | collector.stop(); 115 | } catch (err) { 116 | if (err instanceof InvalidUsageError) { 117 | void msg.reply(err.message); 118 | } else { 119 | console.error(err); 120 | void msg.reply('przepraszam, ale coś poszło nie tak…'); 121 | } 122 | } 123 | } 124 | 125 | void updateMessagesCount(msg.member?.id, msg.member?.displayName).catch(console.error); 126 | 127 | const maybeReflinks = messageToReflinks(msg.content); 128 | if (maybeReflinks.length > 0) { 129 | await msg.reply(maybeReflinks.join('\n')); 130 | return; 131 | } 132 | 133 | await thx(msg); 134 | 135 | return; 136 | }); 137 | 138 | async function updateMessagesCount( 139 | memberId: Discord.GuildMember['id'] | undefined, 140 | displayName: Discord.GuildMember['displayName'] | undefined, 141 | ) { 142 | const db = await initDb(); 143 | const statsCollection = getStatsCollection(db); 144 | const [year, week] = getWeekNumber(new Date()); 145 | const yearWeek = `${year}-${week}`; 146 | 147 | await statsCollection.updateOne( 148 | { 149 | memberId, 150 | yearWeek, 151 | }, 152 | { 153 | $set: { 154 | memberId, 155 | memberName: displayName, 156 | updatedAt: new Date(), 157 | yearWeek, 158 | }, 159 | $inc: { messagesCount: 1 }, 160 | }, 161 | { upsert: true }, 162 | ); 163 | } 164 | 165 | function revertCommand(msg: Discord.Message) { 166 | if (!messageCollectorCache.has(msg.id) || msg.channel.type === Discord.ChannelType.DM) { 167 | return undefined; 168 | } 169 | // eslint-disable-next-line functional/prefer-readonly-type 170 | const messagesToDelete = messageCollectorCache.get(msg.id)!; 171 | return msg.channel.bulkDelete(messagesToDelete); 172 | } 173 | 174 | client.on('messageDelete', async (msg) => { 175 | if (msg.author?.bot || !msg.content) { 176 | return; 177 | } 178 | 179 | const message = msg as Discord.Message; 180 | 181 | if (isCommand(message)) { 182 | try { 183 | await revertCommand(message); 184 | } catch (err) { 185 | errors.push(wrapErr(err)); 186 | } 187 | } 188 | 189 | return; 190 | }); 191 | 192 | async function init() { 193 | await client.login(getConfig('DISCORD_BOT_TOKEN')); 194 | 195 | // Auto assign roles 196 | { 197 | const TYPE_OF_WEB_GUILD_ID = '440163731704643589'; 198 | const guild = await client.guilds.fetch(TYPE_OF_WEB_GUILD_ID); 199 | void updateRoles(guild); 200 | setInterval(() => { 201 | void updateRoles(guild); 202 | }, 1000 * 60 * 60 * 24 * 1); 203 | } 204 | 205 | if (process.env.NODE_ENV === 'production') { 206 | const rssClient = new MonitoRSS.ClientManager(settings); 207 | await new Promise((resolve) => rssClient.start(() => resolve(undefined))); 208 | console.log('MonitoRSS started!'); 209 | } 210 | } 211 | 212 | init().catch((err) => errors.push(wrapErr(err))); 213 | 214 | const httpServer = createHttpServer(client, errors, warnings, debugs); 215 | 216 | const updateRoles = async (guild: Discord.Guild) => { 217 | try { 218 | await updateStatsRoles(guild); 219 | await updateKarmaRoles(guild); 220 | console.log(`Updated roles`); 221 | } catch (err) { 222 | errors.push(wrapErr(err)); 223 | } 224 | }; 225 | 226 | httpServer.listen(getConfig('PORT'), () => { 227 | console.log(`Server running!`); 228 | }); 229 | -------------------------------------------------------------------------------- /src/commands/aoc.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import type * as Discord from 'discord.js'; 3 | import nock from 'nock'; 4 | import Sinon from 'sinon'; 5 | 6 | import { getMessageMock } from '../../test/mocks'; 7 | import * as Config from '../config'; 8 | 9 | import aoc from './aoc'; 10 | 11 | describe('aoc', () => { 12 | beforeEach(() => { 13 | void Sinon.stub(Config, 'getConfig').callsFake((name) => { 14 | if (name === 'ADVENT_OF_CODE_SESSION') { 15 | return 'FAKE_SESSION'; 16 | } 17 | throw new Error(`Unexpected config: ${name}`); 18 | }); 19 | }); 20 | it('it should send one message', async () => { 21 | nock('https://adventofcode.com') 22 | .get('/2022/leaderboard/private/view/756840.json') 23 | .reply(200, { 24 | members: { 25 | '0': { 26 | stars: 10, 27 | local_score: 10, 28 | name: '0', 29 | global_score: 0, 30 | id: 1, 31 | }, 32 | }, 33 | }); 34 | 35 | const msg = getMessageMock('msg', {}); 36 | 37 | await aoc.execute(msg as unknown as Discord.Message, []); 38 | 39 | expect(msg.channel.send).to.have.been.calledOnce; 40 | }); 41 | }); 42 | -------------------------------------------------------------------------------- /src/commands/aoc.ts: -------------------------------------------------------------------------------- 1 | import Cache from 'node-cache'; 2 | import fetch from 'node-fetch'; 3 | 4 | import { getConfig } from '../config'; 5 | import type { Command } from '../types'; 6 | 7 | const LEADERBOARD_JOIN_CODE = `756840-8c3f18ad`; 8 | const LEADERBOARD_URL = 'https://adventofcode.com/2022/leaderboard/private/view/756840'; 9 | 10 | const CACHE_TTL = 15 * 60; 11 | const CACHE_KEY = 'leaderboard'; 12 | const aocCache = new Cache({ stdTTL: CACHE_TTL, deleteOnExpire: true }); 13 | 14 | const aoc: Command = { 15 | name: 'aoc', 16 | description: 'Wyświetla ranking Advent of Code serwera Type of Web', 17 | args: 'prohibited', 18 | cooldown: 60, 19 | async execute(msg) { 20 | const AOC_SESSION = getConfig('ADVENT_OF_CODE_SESSION'); 21 | 22 | if (!aocCache.has('leaderboard')) { 23 | const res = await fetch(`${LEADERBOARD_URL}.json`, { 24 | headers: { 25 | Cookie: `session=${AOC_SESSION}`, 26 | }, 27 | }); 28 | const data = (await res.json()) as LeaderboardResponse; 29 | const leaderboard = Object.values(data.members) 30 | .sort((a, b) => b.local_score - a.local_score) 31 | .slice(0, 10); 32 | 33 | aocCache.set(CACHE_KEY, leaderboard); 34 | } 35 | 36 | const leaderboard = aocCache.get(CACHE_KEY); 37 | const lastUpdateDate = new Date(aocCache.getTtl(CACHE_KEY)! - CACHE_TTL * 1000); 38 | 39 | const formattedLastUpdateHour = new Intl.DateTimeFormat('pl-PL', { 40 | hour: 'numeric', 41 | minute: 'numeric', 42 | timeZone: 'Europe/Warsaw', 43 | }).format(lastUpdateDate); 44 | 45 | const messages = [ 46 | `**TOP 10 leaderboard AOC** (stan na ${formattedLastUpdateHour}):`, 47 | ...leaderboard!.map( 48 | ({ name, local_score, stars }, index) => 49 | `\`${(index + 1).toString().padStart(2, ' ')}\`. ${name} – ${local_score} - ${stars} ⭐️`, 50 | ), 51 | `Dołącz do nas na https://adventofcode.com/2022/leaderboard/private z kodem \`${LEADERBOARD_JOIN_CODE}\` :)`, 52 | ]; 53 | 54 | return msg.channel.send(messages.join('\n')); 55 | }, 56 | }; 57 | 58 | export default aoc; 59 | 60 | interface LeaderboardEntry { 61 | readonly id: number; 62 | readonly name: string; 63 | readonly local_score: number; 64 | readonly global_score: number; 65 | readonly stars: number; 66 | } 67 | 68 | interface LeaderboardResponse { 69 | readonly members: { 70 | readonly [key: string]: LeaderboardEntry; 71 | }; 72 | } 73 | -------------------------------------------------------------------------------- /src/commands/co.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import type * as Discord from 'discord.js'; 3 | 4 | import { getMessageMock } from '../../test/mocks'; 5 | 6 | import co from './co'; 7 | 8 | describe('co', () => { 9 | it('it should send a file', async () => { 10 | const msg = getMessageMock('msg', {}); 11 | 12 | await co.execute(msg as unknown as Discord.Message, []); 13 | 14 | expect(msg.channel.send).to.have.been.calledOnce; 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/commands/co.ts: -------------------------------------------------------------------------------- 1 | import type { Command } from '../types'; 2 | 3 | const co: Command = { 4 | name: 'co', 5 | description: 'co?', 6 | args: 'prohibited', 7 | cooldown: 60, 8 | execute(msg) { 9 | return msg.channel.send({ 10 | files: [ 11 | { 12 | attachment: 'https://i.pinimg.com/564x/bc/c1/5a/bcc15ab1b66968db9d09ffffd5b98323.jpg', 13 | }, 14 | ], 15 | }); 16 | }, 17 | }; 18 | 19 | export default co; 20 | -------------------------------------------------------------------------------- /src/commands/execute.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | 3 | import 'mocha'; 4 | import * as execute from './execute'; 5 | 6 | const Template = (language: string, code: string) => `!execute \`\`\`${language} 7 | ${code} 8 | \`\`\``; 9 | 10 | const tsCode = 'function foo(a: number) {return a * 2}; foo(2)'; 11 | 12 | describe('Command: execute', () => { 13 | it('parses valid message', () => { 14 | const code = '2 + 2'; 15 | const message = Template('js', code); 16 | const parseResult = execute.parseMessage(message); 17 | expect(parseResult.language).to.equal('js'); 18 | expect(parseResult.source.trim()).to.equal(code); 19 | }); 20 | 21 | it('throws on invalid message', () => { 22 | const messages = [ 23 | '!execute ``js\n5\n```', 24 | '!execute ```js\n5\n', 25 | '!execute ```js\n5\n`', 26 | '!execute ```js5\n`', 27 | '!execute js\n5', 28 | ]; 29 | messages.forEach((message) => { 30 | expect(() => execute.parseMessage(message)).to.throw(); 31 | }); 32 | }); 33 | 34 | it('sets javascript as default', () => { 35 | const code = '2 + 2'; 36 | const message = Template('', code); 37 | const parseResult = execute.parseMessage(message); 38 | expect(parseResult.language).to.equal('js'); 39 | }); 40 | 41 | it('throws when language is not known', async () => { 42 | await expect(execute.executeCode('2 + 2', 'prolog')).to.eventually.be.rejected; 43 | // try { 44 | // await execute.executeCode('2 + 2', 'prolog'); 45 | // assert.fail('Expected to throw'); 46 | // } catch(error) { 47 | // expect(error).to.not.be.equal(null); 48 | // } 49 | }); 50 | 51 | it('executes simple program', async () => { 52 | const executeResult = await execute.executeCode('2 + 2', 'js'); 53 | expect(executeResult.stdout.length).to.equal(0); 54 | expect(executeResult.result).to.equal(4); 55 | }); 56 | 57 | it('receives json as result', async () => { 58 | const executeResult = await execute.executeCode( 59 | 'const foo = () => ({foo: "bar"}); foo()', 60 | 'js', 61 | ); 62 | expect(executeResult.stdout.length).to.equal(0); 63 | expect(JSON.stringify(executeResult.result)).to.equal('{"foo":"bar"}'); 64 | }); 65 | 66 | it('executes typescript', async () => { 67 | const executeResult = await execute.executeCode(tsCode, 'ts'); 68 | expect(executeResult).to.be.not.an('undefined'); 69 | expect(executeResult.stdout.length).to.equal(0); 70 | expect(executeResult.result).to.equal(4); 71 | }); 72 | 73 | it('displays objects as jsons', async () => { 74 | const code = 'console.log({foo: "bar"})'; 75 | const executeResult = await execute.executeCode(code, 'js'); 76 | expect(executeResult.stdout.length).to.be.equal(1); 77 | expect(executeResult.stdout[0]).to.be.equal('{"foo":"bar"}'); 78 | }); 79 | 80 | it('grabs console.log', async () => { 81 | const executeResult = await execute.executeCode( 82 | 'console.log(1, null, void 0);console.info(3, 4);', 83 | 'js', 84 | ); 85 | expect(executeResult.stdout.length).to.equal(2); 86 | expect(executeResult.stdout[0]).to.be.equal('1, null, undefined'); 87 | expect(executeResult.stdout[1]).to.be.equal('[i], 3, 4'); 88 | }); 89 | 90 | it('omitts long output log', async () => { 91 | const iters = 2000; 92 | const executeResult = await execute.executeCode( 93 | `for(let i=0; i<${iters}; i++) console.log(1)`, 94 | 'js', 95 | ); 96 | const stdout = execute.prepareOutput(executeResult); 97 | expect(stdout.text.length).is.not.greaterThan(execute.MAX_OUTPUT_CHARACTERS); 98 | expect(executeResult.stdout.length).to.equal(iters); 99 | expect(stdout.text.split('\n').length).is.not.greaterThan(execute.MAX_OUTPUT_LINES); 100 | }); 101 | 102 | it('result is written', () => { 103 | const result = { 104 | stdout: ['hello', 'world'], 105 | result: void 0, 106 | time: 10, 107 | }; 108 | const expected = [ 109 | 'Wyjście (2 linie): ```', 110 | 'hello', 111 | 'world', 112 | '```', 113 | 'Wynik (10 ms): ```json', 114 | 'undefined', 115 | '```', 116 | ].join('\n'); 117 | const response = execute.writeResponse(result); 118 | expect(response).to.be.equal(expected); 119 | }); 120 | 121 | it('"output" is omitted when none', () => { 122 | const result = { 123 | stdout: [], 124 | result: 5, 125 | time: 10, 126 | }; 127 | const expected = ['Wynik (10 ms): ```json', '5', '```'].join('\n'); 128 | const response = execute.writeResponse(result); 129 | expect(response).to.be.equal(expected); 130 | }); 131 | 132 | it('throws when code executes dangerous code', async () => { 133 | const dangerous = [ 134 | 'while(1){}', 135 | 'let fs = require("fs")', 136 | 'let fs = require("child_process")', 137 | 'process.exit(0)', 138 | 'eval("require("fs"))', 139 | 'new Function(""))', 140 | `const storage = []; 141 | const twoMegabytes = 1024 * 1024 * 2; 142 | while (true) { 143 | const array = new Uint8Array(twoMegabytes); 144 | for (let ii = 0; ii < twoMegabytes; ii += 4096) { 145 | array[ii] = 1; 146 | } 147 | storage.push(array); 148 | } 149 | `, 150 | ]; 151 | 152 | // eslint-disable-next-line functional/no-loop-statement 153 | for (const code of dangerous) { 154 | await expect(execute.executeCode(code, 'js')).to.eventually.be.rejected; 155 | } 156 | }); 157 | }); 158 | -------------------------------------------------------------------------------- /src/commands/execute.ts: -------------------------------------------------------------------------------- 1 | import type { Message } from 'discord.js'; 2 | import ivm from 'isolated-vm'; 3 | import { polishPlurals } from 'polish-plurals'; 4 | import * as ts from 'typescript'; 5 | 6 | import type { Command } from '../types'; 7 | import { wrapErr } from '../utils'; 8 | 9 | const pluralize = (count: number) => polishPlurals('linia', 'linie', 'linii', count); 10 | 11 | export const MAX_OUTPUT_LINES = 20; 12 | export const MAX_OUTPUT_CHARACTERS = 1200; 13 | export const MAX_RESULT_CHARACTERS = 700; 14 | const MAX_ARRAY_ITEMS = 100; 15 | const TIMEOUT = 10; 16 | const MEMORY_LIMIT = 32; 17 | const COOLDOWN = 60; 18 | 19 | const javascript = (code: string) => { 20 | return code; 21 | }; 22 | const typescript = (code: string) => { 23 | const out = ts.transpileModule(code, { 24 | compilerOptions: { 25 | module: ts.ModuleKind.CommonJS, 26 | alwaysStrict: true, 27 | }, 28 | }); 29 | return out.outputText; 30 | }; 31 | 32 | const jsTranspilers: { readonly [key: string]: (code: string) => string | Promise } = { 33 | javascript, 34 | typescript, 35 | js: javascript, 36 | ts: typescript, 37 | }; 38 | 39 | type ResultType = number | string | object | null | undefined; 40 | 41 | export interface ExecutionResult { 42 | readonly stdout: readonly string[]; 43 | readonly result: ResultType; 44 | readonly time?: number; 45 | } 46 | 47 | export interface Stdout { 48 | readonly text: string; 49 | readonly lines: number; 50 | } 51 | 52 | export function parseArg(arg: ResultType) { 53 | if (Array.isArray(arg)) { 54 | return JSON.stringify(arg.slice(0, MAX_ARRAY_ITEMS)); 55 | } else if (ArrayBuffer.isView(arg)) { 56 | return JSON.stringify(Array.from((arg as Uint8Array).slice(0, MAX_ARRAY_ITEMS))); 57 | } else if (typeof arg === 'object') { 58 | return JSON.stringify(arg); 59 | } else if (typeof arg !== 'undefined' && arg !== null) { 60 | return arg.toString(); 61 | } 62 | return 'undefined'; 63 | } 64 | 65 | export function parseMessage(msg: string) { 66 | const DELIMITER = '```'; 67 | const opening = msg.indexOf(DELIMITER); 68 | const closing = msg.lastIndexOf(DELIMITER); 69 | const newline = msg.indexOf('\n', opening + DELIMITER.length); 70 | if (opening === -1 || newline === -1 || closing === opening) { 71 | throw new Error('Nieprawidłowa składnia'); 72 | } 73 | const source = msg.substring(newline + 1, closing); 74 | const language = msg.substring(opening + DELIMITER.length, newline).toLowerCase(); 75 | return { 76 | source, 77 | language: language.length > 0 ? language : 'js', 78 | }; 79 | } 80 | 81 | const consoleWrapCode = /*javascript*/ ` 82 | __logs = []; 83 | eval = void 0; 84 | console = { 85 | log (...args) { 86 | __logs.push(args) 87 | }, 88 | info (...args) { 89 | __logs.push(['[i]'].concat(args)) 90 | }, 91 | debug (...args) { 92 | __logs.push(['[d]'].concat(args)) 93 | }, 94 | error (...args) { 95 | __logs.push(['[e]'].concat(args)) 96 | } 97 | }`; 98 | 99 | export async function executeCode(source: string, language: string): Promise { 100 | if (!jsTranspilers[language]) { 101 | throw new Error(`Nieobsługiwany język ${language}`); 102 | } 103 | const code = await jsTranspilers[language](source); 104 | const vm = new ivm.Isolate({ 105 | memoryLimit: MEMORY_LIMIT, 106 | }); 107 | const context = await vm.createContext(); 108 | await context.eval(consoleWrapCode); 109 | 110 | const config = { 111 | timeout: TIMEOUT, 112 | promise: false, 113 | externalCopy: true, 114 | } as const; 115 | 116 | try { 117 | const begin = new Date().getTime(); 118 | const exeResult = await context.eval(code, config); 119 | const result = exeResult.copy({ transferIn: true }) as ResultType; 120 | const rawLogs = (await context.eval('__logs', config)) as ivm.ExternalCopy< 121 | ReadonlyArray> 122 | >; 123 | const rawStdout = rawLogs.copy({ 124 | transferIn: true, 125 | }); 126 | const end = new Date().getTime(); 127 | const stdout = rawStdout.map((row) => row.map(parseArg).join(', ')); 128 | return { 129 | stdout, 130 | result, 131 | time: end - begin, 132 | }; 133 | } catch (error) { 134 | throw error; 135 | } finally { 136 | context.release(); 137 | vm.dispose(); 138 | } 139 | } 140 | 141 | function wrapText(text: string, lang = '') { 142 | return `\`\`\`${lang}\n${text}\n\`\`\``; 143 | } 144 | 145 | export function prepareOutput(result: ExecutionResult) { 146 | return { 147 | text: result.stdout.slice(0, MAX_OUTPUT_LINES).join('\n').slice(0, MAX_OUTPUT_CHARACTERS), 148 | lines: result.stdout.length, 149 | }; 150 | } 151 | 152 | export function writeResponse(result: ExecutionResult): string { 153 | const stdout = prepareOutput(result); 154 | const isCut = stdout.text.length !== result.stdout.join('\n').length; 155 | const stdoutText = 156 | stdout.lines === 0 157 | ? '' 158 | : `Wyjście (${stdout.lines} ${pluralize(stdout.lines)}): ${wrapText( 159 | stdout.text + (isCut ? '\n...' : ''), 160 | )}\n`; 161 | const codeResult = 162 | `Wynik (${result.time ?? 0} ms): ` + 163 | wrapText(parseArg(result.result).substr(0, MAX_RESULT_CHARACTERS), 'json'); 164 | return stdoutText + codeResult; 165 | } 166 | 167 | const errorMessage = (error: Error | string) => 168 | `Błąd: ${String(error)}\n` + 169 | 'Poprawna składnia to:\n ' + 170 | '> !execute \\`\\`\\`js\n' + 171 | '> // kod\n' + 172 | '> \\`\\`\\`\n' + 173 | `Obsługiwane języki: ${Object.keys(jsTranspilers).join(', ')}`; 174 | 175 | const execute: Command = { 176 | name: 'execute', 177 | description: 'Wykonuje kod JS/TS', 178 | args: 'required', 179 | cooldown: COOLDOWN, 180 | async execute(msg: Message) { 181 | try { 182 | const { source, language } = parseMessage(msg.content); 183 | try { 184 | const result = await executeCode(source, language); 185 | const response = writeResponse(result); 186 | return msg.channel.send(response); 187 | } catch (error) { 188 | return msg.channel.send(`Błąd wykonania: \`\`\`\n${String(error)}\n\`\`\``); 189 | } 190 | } catch (error) { 191 | return msg.channel.send(errorMessage(wrapErr(error))); 192 | } 193 | }, 194 | }; 195 | 196 | export default execute; 197 | -------------------------------------------------------------------------------- /src/commands/index.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import type * as Discord from 'discord.js'; 3 | import Sinon from 'sinon'; 4 | 5 | import { getMessageMock } from '../../test/mocks'; 6 | 7 | import { handleCommand } from '.'; 8 | 9 | describe('index', () => { 10 | describe('handleCommand', () => { 11 | it('should show help message', async () => { 12 | const msg = getMessageMock('msg', { content: '!help' }); 13 | const memberMock = { 14 | permissions: { 15 | has: Sinon.spy(), 16 | }, 17 | }; 18 | msg.guild.members.cache.get.returns(memberMock); 19 | msg.author.send.resolves(); 20 | await handleCommand(msg as unknown as Discord.Message); 21 | expect(msg.reply).to.have.been.calledOnceWith('Wysłałam Ci DM ze wszystkimi komendami! 🎉'); 22 | }); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /src/commands/index.ts: -------------------------------------------------------------------------------- 1 | import Discord from 'discord.js'; 2 | import type { PermissionsString } from 'discord.js'; 3 | 4 | import { getConfig } from '../config'; 5 | import type { Command } from '../types'; 6 | import { InvalidUsageError } from '../types'; 7 | 8 | import aoc from './aoc'; 9 | import co from './co'; 10 | import execute from './execute'; 11 | import { addKarma, karma, KARMA_REGEX } from './karma'; 12 | // import { grzesiu, morritz } from './kocopoly'; 13 | import link from './link'; 14 | import m1 from './m1'; 15 | import markdown from './markdown'; 16 | import mdn from './mdn'; 17 | import mongodb from './mongodb'; 18 | import mydevil from './mydevil'; 19 | import npm from './npm'; 20 | import odpowiedz from './odpowiedz'; 21 | import praca from './praca'; 22 | import prs from './prs'; 23 | import prune from './prune'; 24 | import quiz from './quiz'; 25 | import regulamin from './regulamin'; 26 | import roll from './roll'; 27 | import server from './server'; 28 | import skierowanie from './skierowanie'; 29 | import spotify from './spotify'; 30 | import stackoverflow from './stackoverflow'; 31 | import stats from './stats'; 32 | import summon from './summon'; 33 | import typeofweb from './towarticle'; 34 | import wiki from './wiki'; 35 | import xd from './xd'; 36 | import xkcd from './xkcd'; 37 | import yesno from './yesno'; 38 | import youtube from './youtube'; 39 | 40 | export const COMMAND_PATTERN = new RegExp(getConfig('PREFIX') + '([a-z1-9]+)(?: (.*))?'); 41 | 42 | const allCommands = [ 43 | aoc, 44 | co, 45 | execute, 46 | // grzesiu, 47 | karma, 48 | link, 49 | m1, 50 | markdown, 51 | mdn, 52 | mongodb, 53 | // morritz, 54 | mydevil, 55 | npm, 56 | odpowiedz, 57 | prs, 58 | prune, 59 | quiz, 60 | regulamin, 61 | roll, 62 | server, 63 | skierowanie, 64 | spotify, 65 | stats, 66 | summon, 67 | typeofweb, 68 | wiki, 69 | xd, 70 | xkcd, 71 | yesno, 72 | youtube, 73 | stackoverflow, 74 | praca, 75 | ]; 76 | 77 | const cooldowns = new Discord.Collection>(); 78 | const PERMISSION_TO_OVERRIDE_COOLDOWN: PermissionsString = 'Administrator'; 79 | 80 | function verifyCooldown(msg: Discord.Message, command: Command) { 81 | if (typeof command.cooldown !== 'number') { 82 | return; 83 | } 84 | 85 | if (!cooldowns.has(command.name)) { 86 | cooldowns.set(command.name, new Discord.Collection()); 87 | } 88 | 89 | const now = Date.now(); 90 | const timestamps = cooldowns.get(command.name)!; 91 | // tslint:disable-next-line:no-magic-numbers 92 | const cooldownAmount = command.cooldown * 1000; 93 | const id = msg.author.id; 94 | 95 | if (timestamps.has(msg.author.id) && msg.guild) { 96 | const expirationTime = timestamps.get(msg.author.id)! + cooldownAmount; 97 | 98 | if (now < expirationTime) { 99 | const member = msg.guild.members.cache.get(msg.author.id); 100 | if (member?.permissions.has(PERMISSION_TO_OVERRIDE_COOLDOWN)) { 101 | return; 102 | } 103 | 104 | const timeLeft = Math.ceil((expirationTime - now) / 1000); 105 | throw new InvalidUsageError( 106 | `musisz poczekać jeszcze ${timeLeft}s, żeby znowu użyć \`${command.name}\`!.`, 107 | ); 108 | } 109 | } else { 110 | timestamps.set(id, now); 111 | setTimeout(() => timestamps.delete(id), cooldownAmount); 112 | } 113 | } 114 | 115 | function printHelp(msg: Discord.Message, member: Discord.GuildMember) { 116 | const commands = allCommands 117 | .sort((a, b) => { 118 | return a.name.localeCompare(b.name); 119 | }) 120 | .filter((command) => { 121 | if (command.permissions && !member.permissions.has(command.permissions)) { 122 | return false; 123 | } 124 | return true; 125 | }); 126 | 127 | const data = [ 128 | `**Oto lista wszystkich komend:**`, 129 | ...commands.map((command) => { 130 | return `**\`${getConfig('PREFIX')}${command.name}\`** — ${command.description}`; 131 | }), 132 | ]; 133 | 134 | return msg.author 135 | .send(data.join('\n')) 136 | .then(() => { 137 | if (msg.channel.type === Discord.ChannelType.DM) { 138 | return undefined; 139 | } 140 | return msg.reply('Wysłałam Ci DM ze wszystkimi komendami! 🎉'); 141 | }) 142 | .catch((error) => { 143 | console.error(`Could not send help DM to ${msg.author.tag}.\n`, error); 144 | return msg.reply( 145 | 'Niestety nie mogłam Ci wysłać wiadomości prywatnej 😢 Może masz wyłączone DM?', 146 | ); 147 | }); 148 | } 149 | 150 | export function handleCommand(msg: Discord.Message) { 151 | if (!msg.guild) { 152 | return undefined; 153 | } 154 | 155 | if (KARMA_REGEX.test(msg.content)) { 156 | return processCommand(msg, addKarma, null); 157 | } 158 | 159 | const [, maybeCommand, rest] = COMMAND_PATTERN.exec(msg.content) || [null, null, null]; 160 | 161 | if (maybeCommand === 'help') { 162 | const member = msg.guild.members.cache.get(msg.author.id); 163 | if (member) { 164 | return printHelp(msg, member); 165 | } 166 | } 167 | 168 | const command = allCommands.find((c) => maybeCommand === c.name); 169 | 170 | if (!command || !maybeCommand) { 171 | return undefined; 172 | } 173 | 174 | return processCommand(msg, command, rest); 175 | } 176 | 177 | async function processCommand(msg: Discord.Message, command: Command, rest: string | null) { 178 | const member = msg.guild?.members.cache.get(msg.author.id); 179 | 180 | if (!member || (command.permissions && !member.permissions.has(command.permissions))) { 181 | return undefined; // silence is golden 182 | } 183 | 184 | await msg.channel.sendTyping(); 185 | 186 | if (command.guildOnly && msg.channel.type !== Discord.ChannelType.GuildText) { 187 | throw new InvalidUsageError(`to polecenie można wywołać tylko na kanałach.`); 188 | } 189 | 190 | verifyCooldown(msg, command); 191 | const args = rest ? rest.split(/\s+/g) : []; 192 | 193 | if (command.args === 'optional') { 194 | return command.execute(msg, args); 195 | } 196 | if (!args.length && command.args === 'required') { 197 | throw new InvalidUsageError(`nie podano argumentów!`); 198 | } 199 | if (args.length && command.args === 'prohibited') { 200 | throw new InvalidUsageError(`argumenty niedozwolone!`); 201 | } 202 | 203 | return command.execute(msg, args); 204 | } 205 | -------------------------------------------------------------------------------- /src/commands/karma.spec.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-unsafe-member-access */ 2 | /* eslint-disable @typescript-eslint/no-unsafe-assignment */ 3 | /* eslint-disable functional/no-this-expression */ 4 | import { expect } from 'chai'; 5 | import type * as Discord from 'discord.js'; 6 | import Sinon from 'sinon'; 7 | 8 | import { getMessageMock, getMemberMock } from '../../test/mocks'; 9 | import * as Db from '../db'; 10 | 11 | import { addKarma, KARMA_REGEX } from './karma'; 12 | 13 | type MemberMock = ReturnType; 14 | 15 | const getAddKarmaMsgMock = (from: MemberMock, membersToReward: ReadonlyArray) => { 16 | const msg = getMessageMock('msg', { 17 | mentions: { 18 | members: { 19 | size: membersToReward.length, 20 | values: () => [ 21 | ...[from, ...membersToReward].map(({ id, mention }) => ({ 22 | fetch: () => ({ id, toString: () => mention }), 23 | })), 24 | ], 25 | }, 26 | }, 27 | author: { id: from.id, toString: () => from.mention }, 28 | }); 29 | 30 | return msg; 31 | }; 32 | 33 | type DB = ReturnType; 34 | 35 | describe('add karma', () => { 36 | const AggregateMock = { 37 | sort() { 38 | return this; 39 | }, 40 | limit() { 41 | return this; 42 | }, 43 | toArray() { 44 | return []; 45 | }, 46 | }; 47 | 48 | const CollectionMock = { 49 | insertMany: Sinon.stub(), 50 | aggregate: Sinon.stub().returns(AggregateMock), 51 | }; 52 | 53 | const DbMock = { 54 | collection: Sinon.stub().returns(CollectionMock), 55 | } as unknown as DB; 56 | 57 | beforeEach(() => { 58 | Sinon.stub(Db, 'initDb').returns(Promise.resolve(DbMock)); 59 | }); 60 | afterEach(() => { 61 | Sinon.reset(); 62 | Sinon.restore(); 63 | }); 64 | 65 | describe('checks regex', () => { 66 | it('checks if one user should be given a karma', () => { 67 | const memberToReward = getMemberMock(); 68 | 69 | const msg = getMessageMock('msg', { content: `${memberToReward.mention} ++` }); 70 | expect(KARMA_REGEX.test(msg.content)).to.have.be.true; 71 | }); 72 | 73 | it('checks if two users should be given a karma', () => { 74 | const firstMemberToReward = getMemberMock(); 75 | const secondMemberToReward = getMemberMock(); 76 | 77 | const firstMsg = getMessageMock('msg', { 78 | content: `${firstMemberToReward.mention} ${secondMemberToReward.mention} ++`, 79 | }); 80 | expect(KARMA_REGEX.test(firstMsg.content)).to.have.be.true; 81 | 82 | const secondMsg = getMessageMock('msg', { 83 | content: `${firstMemberToReward.mention} ++ ${secondMemberToReward.mention}`, 84 | }); 85 | expect(KARMA_REGEX.test(secondMsg.content)).to.have.be.true; 86 | 87 | const thirdMsg = getMessageMock('msg', { 88 | content: `${firstMemberToReward.mention} ++ ${secondMemberToReward.mention} ++`, 89 | }); 90 | expect(KARMA_REGEX.test(thirdMsg.content)).to.have.be.true; 91 | }); 92 | 93 | it('checks if one user should not be given a karma', () => { 94 | const memberToReward = getMemberMock(); 95 | 96 | const msg = getMessageMock('msg', { content: `random message ${memberToReward.mention} ++` }); 97 | expect(KARMA_REGEX.test(msg.content)).to.have.be.false; 98 | }); 99 | }); 100 | 101 | it('should add karma for one user', async () => { 102 | const from = getMemberMock(); 103 | const memberToReward = getMemberMock(); 104 | 105 | const msg = getAddKarmaMsgMock(from, [memberToReward]); 106 | 107 | await addKarma.execute(msg as unknown as Discord.Message, []); 108 | 109 | const arg = CollectionMock.insertMany.lastCall.firstArg[0]; 110 | expect(arg.from).to.eql(from.id); 111 | expect(arg.to).to.eql(memberToReward.id); 112 | expect(arg.value).to.eql(1); 113 | }); 114 | 115 | it('should add karma for two users', async () => { 116 | const from = getMemberMock(); 117 | 118 | const firstMemberToReward = getMemberMock(); 119 | const secondMemberToReward = getMemberMock(); 120 | 121 | const msg = getAddKarmaMsgMock(from, [firstMemberToReward, secondMemberToReward]); 122 | 123 | await addKarma.execute(msg as unknown as Discord.Message, []); 124 | 125 | { 126 | const arg = CollectionMock.insertMany.lastCall.firstArg[0]; 127 | expect(arg.from).to.eql(from.id); 128 | expect(arg.to).to.eql(firstMemberToReward.id); 129 | expect(arg.value).to.eql(1); 130 | } 131 | { 132 | const arg = CollectionMock.insertMany.lastCall.firstArg[1]; 133 | expect(arg.from).to.eql(from.id); 134 | expect(arg.to).to.eql(secondMemberToReward.id); 135 | expect(arg.value).to.eql(1); 136 | } 137 | }); 138 | }); 139 | -------------------------------------------------------------------------------- /src/commands/karma.ts: -------------------------------------------------------------------------------- 1 | import Bluebird from 'bluebird'; 2 | import Discord from 'discord.js'; 3 | 4 | import type { KarmaAgg } from '../data/karma'; 5 | import { 6 | getKarmaForMember, 7 | getKarmaForAllMembers, 8 | getKarmaForMembers, 9 | getKarmaDescription, 10 | } from '../data/karma'; 11 | import { getKarmaCollection, initDb } from '../db'; 12 | import type { Command } from '../types'; 13 | 14 | export const KARMA_REGEX = new RegExp( 15 | `^(${Discord.MessageMentions.UsersPattern.source}).*\\+\\+\\s*`, 16 | ); 17 | 18 | const addKarma: Command = { 19 | name: '++', 20 | description: 'Podziękuj użytkownikom wpisując `@nazwa ++`', 21 | args: 'optional', 22 | cooldown: 5, 23 | async execute(msg) { 24 | if (!msg.mentions.members?.size) { 25 | return null; 26 | } 27 | 28 | const db = await initDb(); 29 | const karmaCollection = getKarmaCollection(db); 30 | 31 | const from = msg.author.id; 32 | 33 | const membersToReward = await Bluebird.resolve(Array.from(msg.mentions.members.values())) 34 | .map((m) => m.fetch()) 35 | .filter((m) => m && m.id !== from); 36 | 37 | if (membersToReward.length === 0) { 38 | return null; 39 | } 40 | 41 | await karmaCollection.insertMany( 42 | membersToReward.map((m) => { 43 | return { 44 | from, 45 | to: m.id, 46 | createdAt: new Date(), 47 | value: 1, 48 | }; 49 | }), 50 | ); 51 | 52 | const membersKarma = await getKarmaForMembers( 53 | db, 54 | membersToReward.map((m) => m.id), 55 | ); 56 | 57 | const messages = membersKarma.map(({ value, _id }) => { 58 | const member = membersToReward.find((m) => m.id === _id); 59 | return `${msg.author.toString()} podziękował(a) ${member?.toString()!}! ${member?.toString()!} ma ${getKarmaDescription( 60 | value, 61 | )}`; 62 | }); 63 | 64 | return msg.channel.send(messages.join('\n')); 65 | }, 66 | }; 67 | 68 | const karma: Command = { 69 | name: 'karma', 70 | description: 'Sprawdź ile kto ma pkt. karmy.', 71 | args: 'optional', 72 | async execute(msg) { 73 | const member = await msg.mentions.members?.first()?.fetch(); 74 | 75 | const db = await initDb(); 76 | 77 | if (member) { 78 | const agg = await getKarmaForMember(member.id, db); 79 | const value = agg?.value ?? 0; 80 | 81 | return msg.channel.send(`${member.displayName} ma ${getKarmaDescription(value)}`); 82 | } else { 83 | const agg = await getKarmaForAllMembers(db); 84 | const data = agg.filter((el): el is KarmaAgg => !!el); 85 | await Promise.allSettled(data.map(({ _id: memberId }) => msg.guild?.members.fetch(memberId))); 86 | 87 | const messages = [ 88 | `**TOP 10 karma**`, 89 | ...data.map(({ _id: memberId, value }, index) => { 90 | const name = msg.guild?.members.cache.get(memberId)?.displayName ?? ''; 91 | return `\`${(index + 1).toString().padStart(2, ' ')}\`. ${name}\ 92 | – ${getKarmaDescription(value)}`; 93 | }), 94 | ]; 95 | 96 | return msg.channel.send(messages.join('\n')); 97 | } 98 | }, 99 | }; 100 | 101 | export { addKarma, karma }; 102 | -------------------------------------------------------------------------------- /src/commands/kocopoly.ts: -------------------------------------------------------------------------------- 1 | import Fsp from 'fs/promises'; 2 | import Path from 'path'; 3 | 4 | import type { Command, CommandWithArgs } from '../types'; 5 | import { capitalizeFirst, wait } from '../utils'; 6 | 7 | import { getRandomKocopolyAnswers } from './kocopoly/kocopolyUtils'; 8 | 9 | const COOLDOWN = 20; 10 | const KOCOPOLY_DELAY = 1500; 11 | 12 | const kocopolyExecute = 13 | (kocopolyFilename: string, kocopolyName: string): CommandWithArgs['execute'] => 14 | async (msg, args) => { 15 | const username = (msg.member?.displayName || msg.author.username).trim().split(/\s/)[0]; 16 | const question = args.join(' '); 17 | 18 | const kocopolyJson = JSON.parse( 19 | await Fsp.readFile(Path.join(__dirname, '..', kocopolyFilename), 'utf-8'), 20 | ) as readonly string[]; 21 | 22 | const messages = await getRandomKocopolyAnswers(username, question, kocopolyJson, kocopolyName); 23 | 24 | if (!messages.length) { 25 | return msg.channel.send( 26 | `Niestety, ${capitalizeFirst(kocopolyName)} nie miał nic do powiedzenia!`, 27 | ); 28 | } 29 | 30 | return messages.reduce(async (acc, message) => { 31 | await acc; 32 | await msg.channel.send(`_${message}_`); 33 | await wait(200 + Math.random() * KOCOPOLY_DELAY); 34 | return null; 35 | }, Promise.resolve(null)); 36 | }; 37 | 38 | export const grzesiu: Command = { 39 | name: 'grzesiu', 40 | description: 'Użyj tego, gdy tęsknisz za Grzesiem', 41 | args: 'optional', 42 | cooldown: COOLDOWN, 43 | execute: kocopolyExecute('grzes.json', 'grzegorz'), 44 | }; 45 | 46 | export const morritz: Command = { 47 | name: 'morritz', 48 | description: 'Użyj tego, gdy tęsknisz za Morritzem', 49 | args: 'optional', 50 | cooldown: COOLDOWN, 51 | execute: kocopolyExecute('morritz.json', 'morritz'), 52 | }; 53 | -------------------------------------------------------------------------------- /src/commands/kocopoly/kocopolyUtils.ts: -------------------------------------------------------------------------------- 1 | import Natural from 'natural'; 2 | import { Configuration, OpenAIApi } from 'openai'; 3 | 4 | const configuration = new Configuration({ 5 | apiKey: process.env.OPENAI_API_KEY, 6 | }); 7 | const openai = new OpenAIApi(configuration); 8 | 9 | const MAX_TOKENS = 2049; 10 | const RESPONSE_TOKENS = 64; 11 | 12 | const MAX_GENERATED_CONTENT_LEN = Math.floor((MAX_TOKENS - RESPONSE_TOKENS) / 2); // make it cheaper 13 | const BANNED_PATTERNS = /[`\[\]{}\(\)]|http/g; 14 | 15 | const getRandomInt = (len: number) => Math.floor(Math.random() * len); 16 | 17 | interface KocopolyGenerator { 18 | (username: string, question: string, kocopolyJson: readonly string[], kocopolyName: string): 19 | | readonly string[] 20 | | Promise; 21 | } 22 | 23 | // random 24 | export const getRandomKocopolyAnswers: KocopolyGenerator = ( 25 | _username, 26 | question, 27 | kocopolyJson, 28 | _kocopolyName, 29 | ) => { 30 | const g = kocopolyJson 31 | .map((l) => l.trim()) 32 | .filter((line) => !BANNED_PATTERNS.test(line) && line.length > 0); 33 | 34 | const potentialItems = 35 | question.trim().length > 0 ? g.filter((l) => Natural.DiceCoefficient(question, l) > 0.35) : []; 36 | 37 | const initialIndex = 38 | potentialItems.length > 0 ? g.indexOf(potentialItems[getRandomInt(potentialItems.length)]) : -1; 39 | 40 | const MAX_LINES = 5; 41 | const numberOfLines = 5 - Math.floor(Math.log2(Math.floor(Math.random() * 2 ** MAX_LINES) + 1)); 42 | 43 | const lines = []; 44 | let idx = initialIndex === -1 ? getRandomInt(g.length) : initialIndex; 45 | 46 | // eslint-disable-next-line functional/no-loop-statement 47 | for (let i = 0; i < numberOfLines; ++i) { 48 | lines.push(g[idx]); 49 | 50 | if (Math.random() < 0.9 && idx < g.length) { 51 | ++idx; 52 | } else { 53 | idx = getRandomInt(g.length); 54 | } 55 | } 56 | 57 | return lines; 58 | }; 59 | 60 | // openAI 61 | export const getKocopolyAnswerFromOpenAI: KocopolyGenerator = async ( 62 | username, 63 | question, 64 | kocopolyJson, 65 | kocopolyName, 66 | ) => { 67 | const prompt = generateKocopolyPrompt(username, question, kocopolyJson, kocopolyName); 68 | 69 | const engine = 'text-davinci-001'; 70 | // const engine = 'text-babbage-001'; 71 | const response = await openai.createCompletion(engine, { 72 | prompt, 73 | temperature: 1, 74 | max_tokens: RESPONSE_TOKENS, 75 | top_p: 1, 76 | frequency_penalty: 0, 77 | presence_penalty: 2, 78 | best_of: 4, 79 | }); 80 | 81 | console.log(response); 82 | 83 | if (!response.data.choices?.[0]?.text) { 84 | return []; 85 | } 86 | 87 | const messages = response.data.choices[0].text 88 | .split('\n') 89 | .map((l) => l.trim()) 90 | .filter((l) => l.startsWith(`${kocopolyName}:`)) 91 | .flatMap((l) => l.split(`${kocopolyName}:`)) 92 | .filter((l) => l.trim().length > 0); 93 | return messages; 94 | }; 95 | 96 | const getRandomIndices = (num: number, max: number) => { 97 | const set = new Set(); 98 | // eslint-disable-next-line functional/no-loop-statement 99 | while (set.size < num) set.add(getRandomInt(max)); 100 | return [...set]; 101 | }; 102 | 103 | const generateKocopolyPrompt = ( 104 | username: string, 105 | question: string, 106 | kocopolyJson: readonly string[], 107 | kocopolyName: string, 108 | ) => { 109 | const indices = getRandomIndices(100, kocopolyJson.length); 110 | const uniqueLines = [...new Set(indices.map((idx) => kocopolyJson[idx].trim()))].filter( 111 | (line) => !BANNED_PATTERNS.test(line) && line.length > 0, 112 | ); 113 | 114 | const getFullConvo = (txt: string, username: string, question: string) => { 115 | if (question) { 116 | return `${txt.trim()}\n${username}: ${question}\n${kocopolyName}:`; 117 | } 118 | return `${txt.trim()}\n${kocopolyName}:`; 119 | }; 120 | 121 | const txt = uniqueLines.reduce((txt, line) => { 122 | const newTxt = txt + `${kocopolyName}: ` + line + '\n'; 123 | const fullConvo = getFullConvo(newTxt, username, question); 124 | return fullConvo.length <= MAX_GENERATED_CONTENT_LEN ? newTxt : txt; 125 | }, ''); 126 | return getFullConvo(txt, username, question); 127 | }; 128 | -------------------------------------------------------------------------------- /src/commands/link.ts: -------------------------------------------------------------------------------- 1 | import type Discord from 'discord.js'; 2 | 3 | import type { Command } from '../types'; 4 | 5 | const link: Command = { 6 | name: 'link', 7 | description: 'Wyświetla link do zapraszania.', 8 | args: 'prohibited', 9 | execute(msg: Discord.Message) { 10 | return msg.channel.send(`Link do zapraszania: https://discord.typeofweb.com/`); 11 | }, 12 | }; 13 | 14 | export default link; 15 | -------------------------------------------------------------------------------- /src/commands/m1.ts: -------------------------------------------------------------------------------- 1 | import type { Command } from '../types'; 2 | 3 | const m1: Command = { 4 | name: 'm1', 5 | description: 'Apple silicon m1', 6 | args: 'prohibited', 7 | cooldown: 10, 8 | execute(msg) { 9 | return msg.channel.send( 10 | [ 11 | `👨‍💻 ***Czy Apple Silicon m1 jest gotowe dla developerów?*** 👩‍💻 \n`, 12 | `https://isapplesiliconready.com/for/developer`, 13 | `https://www.apple.com/mac/m1/`, 14 | ].join('\n'), 15 | ); 16 | }, 17 | }; 18 | 19 | export default m1; 20 | -------------------------------------------------------------------------------- /src/commands/markdown.ts: -------------------------------------------------------------------------------- 1 | import type Discord from 'discord.js'; 2 | 3 | import type { Command } from '../types'; 4 | 5 | const markdownCodes = [ 6 | '*tekst*', 7 | '_tekst_', 8 | '__*tekst*__', 9 | '**tekst**', 10 | '__**tekst**__', 11 | '***tekst***', 12 | '__***tekst***__', 13 | '__tekst__', 14 | '~~tekst~~', 15 | ]; 16 | 17 | const sourceExample = ['\\`\\`\\`js (html, css, json, cp, md, py, xml etc.)', 'kod', '\\`\\`\\`']; 18 | 19 | function codesToInstruction(codes: readonly string[]) { 20 | const maxLength = Math.max(...codes.map((x) => x.length)); 21 | 22 | return codes.map((code) => { 23 | return '`' + code.padEnd(maxLength) + ' 👉` ' + code; 24 | }); 25 | } 26 | 27 | const formattedMarkdownManual = [...codesToInstruction(markdownCodes), '', ...sourceExample].join( 28 | '\n', 29 | ); 30 | 31 | const markdown: Command = { 32 | name: 'markdown', 33 | description: 'Wyświetla przykłady formatowania tekstu w Markdown.', 34 | args: 'prohibited', 35 | execute(msg: Discord.Message) { 36 | return msg.channel.send(formattedMarkdownManual); 37 | }, 38 | }; 39 | 40 | export default markdown; 41 | -------------------------------------------------------------------------------- /src/commands/mdn.ts: -------------------------------------------------------------------------------- 1 | import fetch from 'node-fetch'; 2 | 3 | import type { Command } from '../types'; 4 | 5 | const mdn: Command = { 6 | name: 'mdn', 7 | description: 'Wyszukuje podane wyrażenia na MDN', 8 | args: 'required', 9 | async execute(msg, args) { 10 | const query = encodeURIComponent(args.join(' ')); 11 | const res = await fetch( 12 | `https://developer.mozilla.org/en-US/search.json?locale=en-US&highlight=false&q=${query}`, 13 | ); 14 | const data = (await res.json()) as MDNResponse; 15 | if (!data.documents.length) { 16 | return msg.channel.send(`Niestety nic nie znalazłam 😭`); 17 | } 18 | 19 | const firstDocument = data.documents[0]; 20 | return msg.channel.send( 21 | [ 22 | firstDocument.excerpt, 23 | `https://developer.mozilla.org/en-US/docs/${firstDocument.slug}`, 24 | ].join('\n'), 25 | ); 26 | }, 27 | }; 28 | 29 | export default mdn; 30 | 31 | interface MDNResponse { 32 | readonly query: string; 33 | readonly locale: string; 34 | readonly page: number; 35 | readonly pages: number; 36 | readonly start: number; 37 | readonly end: number; 38 | readonly next: string | null; 39 | readonly previous: string | null; 40 | readonly count: number; 41 | readonly filters: readonly Filter[]; 42 | readonly documents: readonly Document[]; 43 | } 44 | 45 | interface Document { 46 | readonly id: number; 47 | readonly title: string; 48 | readonly slug: string; 49 | readonly locale: string; 50 | readonly url: string; 51 | readonly edit_url: string; 52 | readonly excerpt: string; 53 | readonly tags: readonly string[]; 54 | readonly score: number; 55 | readonly parent: {}; 56 | } 57 | 58 | interface Filter { 59 | readonly name: string; 60 | readonly slug: string; 61 | readonly options: readonly Option[]; 62 | } 63 | 64 | interface Option { 65 | readonly name: string; 66 | readonly slug: string; 67 | readonly count: number; 68 | readonly active: boolean; 69 | readonly urls: Urls; 70 | } 71 | 72 | interface Urls { 73 | readonly active: string; 74 | readonly inactive: string; 75 | } 76 | -------------------------------------------------------------------------------- /src/commands/mongodb.ts: -------------------------------------------------------------------------------- 1 | import type { Command } from '../types'; 2 | 3 | const mongodb: Command = { 4 | name: 'mongodb', 5 | description: 'Mongo is webscale!', 6 | args: 'prohibited', 7 | cooldown: 300, 8 | execute(msg) { 9 | return msg.channel.send('https://youtu.be/b2F-DItXtZs'); 10 | }, 11 | }; 12 | 13 | export default mongodb; 14 | -------------------------------------------------------------------------------- /src/commands/mydevil.ts: -------------------------------------------------------------------------------- 1 | import type Discord from 'discord.js'; 2 | 3 | import type { Command } from '../types'; 4 | 5 | const mydevil: Command = { 6 | name: 'mydevil', 7 | description: 'Wyświetla link do MyDevil.', 8 | args: 'prohibited', 9 | execute(msg: Discord.Message) { 10 | return msg.channel.send(`https://www.mydevil.net/pp/9UVOSJRZIV`); 11 | }, 12 | }; 13 | 14 | export default mydevil; 15 | -------------------------------------------------------------------------------- /src/commands/npm.ts: -------------------------------------------------------------------------------- 1 | import fetch from 'node-fetch'; 2 | import { polishPlurals } from 'polish-plurals'; 3 | 4 | import type { Command } from '../types'; 5 | 6 | const MAX_RESULTS_NUMBER = 3; 7 | 8 | const pluralize = (count: number) => polishPlurals('paczkę', 'paczki', 'paczek', count); 9 | 10 | const npm: Command = { 11 | name: 'npm', 12 | description: 'Wyszukuje podane wyrażenia w NPM', 13 | args: 'required', 14 | async execute(msg, args) { 15 | const query = encodeURIComponent(args.join(' ')); 16 | const res = await fetch(`http://registry.npmjs.com/-/v1/search?text=${query}`); 17 | 18 | const { objects, total } = (await res.json()) as NpmResponse; 19 | if (!objects.length) { 20 | return msg.channel.send(`Niestety nic nie znalazłam 😭`); 21 | } 22 | const message = 23 | `Znalazłam ${total} ${pluralize(total)}` + 24 | (total > MAX_RESULTS_NUMBER ? `. Pokazuję pierwsze ${MAX_RESULTS_NUMBER}` : '') + 25 | ':'; 26 | 27 | const topDocuments = objects.slice(0, MAX_RESULTS_NUMBER); 28 | return msg.channel.send( 29 | [message, ...topDocuments.map((doc) => doc.package.links.npm)].join('\n'), 30 | ); 31 | }, 32 | }; 33 | 34 | export default npm; 35 | 36 | interface NpmResponse { 37 | readonly objects: readonly NpmObject[]; 38 | readonly time: string; 39 | readonly total: number; 40 | } 41 | 42 | interface NpmObject { 43 | readonly package: Package; 44 | readonly score: Score; 45 | readonly searchScore: number; 46 | readonly flags?: Flags; 47 | } 48 | 49 | interface Flags { 50 | readonly unstable: boolean; 51 | } 52 | 53 | interface Score { 54 | readonly final: number; 55 | readonly detail: Detail; 56 | } 57 | 58 | interface Detail { 59 | readonly quality: number; 60 | readonly popularity: number; 61 | readonly maintenance: number; 62 | } 63 | 64 | interface Package { 65 | readonly name: string; 66 | readonly scope: string; 67 | readonly version: string; 68 | readonly description: string; 69 | readonly date: string; 70 | readonly links: Links; 71 | readonly publisher: Publisher; 72 | readonly maintainers: readonly Publisher[]; 73 | readonly keywords?: readonly string[]; 74 | readonly author?: Author; 75 | } 76 | 77 | interface Author { 78 | readonly name: string; 79 | readonly email?: string; 80 | readonly username?: string; 81 | readonly url?: string; 82 | } 83 | 84 | interface Publisher { 85 | readonly username: string; 86 | readonly email: string; 87 | } 88 | 89 | interface Links { 90 | readonly npm: string; 91 | readonly homepage: string; 92 | readonly repository: string; 93 | readonly bugs: string; 94 | } 95 | -------------------------------------------------------------------------------- /src/commands/odpowiedz.ts: -------------------------------------------------------------------------------- 1 | import type { Command } from '../types'; 2 | import { randomizeArray } from '../utils'; 3 | const ANSWERS = [ 4 | 'Mój wywiad donosi: NIE', 5 | 'Wygląda dobrze', 6 | 'Kto wie?', 7 | 'Zapomnij o tym', 8 | 'Tak - w swoim czasie', 9 | 'Prawie jak tak', 10 | 'Nie teraz', 11 | 'YES, YES, YES', 12 | 'To musi poczekać', 13 | 'Mam pewne wątpliwości', 14 | 'Możesz na to liczyć', 15 | 'Zbyt wcześnie aby powiedzieć', 16 | 'Daj spokój', 17 | 'Absolutnie', 18 | 'Chyba żatrujesz?', 19 | 'Na pewno nie', 20 | 'Zrób to', 21 | 'Prawdopodobnie', 22 | 'Dla mnie rewelacja', 23 | 'Na pewno tak', 24 | ]; 25 | 26 | const odpowiedz: Command = { 27 | name: 'odpowiedz', 28 | description: 'Pomoże ci wybrać odpowiedź', 29 | args: 'prohibited', 30 | execute(msg) { 31 | const randomAnswer = randomizeArray(ANSWERS)[0]; 32 | return msg.channel.send(randomAnswer); 33 | }, 34 | }; 35 | 36 | export default odpowiedz; 37 | -------------------------------------------------------------------------------- /src/commands/praca.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import type Discord from 'discord.js'; 3 | 4 | import { getMessageMock } from '../../test/mocks'; 5 | 6 | import praca from './praca'; 7 | 8 | describe('praca', () => { 9 | it('should send links to websites', async () => { 10 | const mockLinks = [ 11 | 'https://justjoin.it/', 12 | 'https://nofluffjobs.com/', 13 | 'https://bulldogjob.pl/', 14 | 'https://www.pracuj.pl/', 15 | ]; 16 | const msg = getMessageMock('msg', {}); 17 | 18 | await praca.execute(msg as unknown as Discord.Message, []); 19 | 20 | const embedData = ( 21 | msg.channel.send.args[0][0] as { readonly embeds: readonly Discord.EmbedBuilder[] } 22 | ).embeds[0].data; 23 | 24 | expect(embedData.title).to.equal('Najlepsze portale z ofertami pracy'); 25 | expect(mockLinks.every((link) => embedData.description?.includes(link))).to.equal(true); 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /src/commands/praca.ts: -------------------------------------------------------------------------------- 1 | import { EmbedBuilder } from 'discord.js'; 2 | 3 | import type { Command } from '../types'; 4 | 5 | const links = [ 6 | 'https://justjoin.it/', 7 | 'https://nofluffjobs.com/', 8 | 'https://bulldogjob.pl/', 9 | 'https://www.pracuj.pl/', 10 | ]; 11 | 12 | const praca: Command = { 13 | name: 'praca', 14 | args: 'prohibited', 15 | description: 'Lista najlepszych portali z ofertami pracy', 16 | execute(msg) { 17 | const embed = new EmbedBuilder() 18 | .setTitle('Najlepsze portale z ofertami pracy') 19 | .setDescription(links.map((link, i) => `${i + 1}. ${link}`).join('\n')) 20 | .setColor('#5ab783') 21 | .setFooter({ 22 | text: 'Type of Web, Discord, Polska', 23 | iconURL: 24 | 'https://cdn.discordapp.com/avatars/574682557988470825/8071299007c2d575c0912255baa19509.png?size=64', 25 | }) 26 | .setTimestamp(); 27 | 28 | return msg.channel.send({ embeds: [embed] }); 29 | }, 30 | }; 31 | 32 | export default praca; 33 | -------------------------------------------------------------------------------- /src/commands/prs.ts: -------------------------------------------------------------------------------- 1 | import type { Command } from '../types'; 2 | 3 | const formatter = new Intl.ListFormat('pl', { style: 'long', type: 'conjunction' }); 4 | 5 | const prs: Command = { 6 | name: 'prs', 7 | description: 'PRs are welcome', 8 | args: 'required', 9 | async execute(msg) { 10 | if (!msg.mentions.members?.size) { 11 | return null; 12 | } 13 | 14 | const mentions = formatter.format(msg.mentions.members.map((m) => m.toString())); 15 | 16 | await msg.delete(); 17 | await msg.channel.send(`PRs are welcome ${mentions}`); 18 | return null; 19 | }, 20 | }; 21 | 22 | export default prs; 23 | -------------------------------------------------------------------------------- /src/commands/prune.spec.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-unsafe-assignment */ 2 | import { expect } from 'chai'; 3 | import type * as Discord from 'discord.js'; 4 | import Sinon from 'sinon'; 5 | 6 | import { getMessageMock } from '../../test/mocks'; 7 | 8 | import prune from './prune'; 9 | 10 | describe('prune', () => { 11 | it('should show an error when you try to delete less than 1 message', () => { 12 | const msg = getMessageMock('msg', {}); 13 | 14 | return expect( 15 | prune.execute(msg as unknown as Discord.Message, ['0']), 16 | ).to.be.eventually.rejectedWith('Musisz podać przynajmniej 1.'); 17 | }); 18 | 19 | it('should show an error when you try to delete more than 10 messages', () => { 20 | const msg = getMessageMock('msg', {}); 21 | 22 | return expect( 23 | prune.execute(msg as unknown as Discord.Message, ['11']), 24 | ).to.be.eventually.rejectedWith( 25 | 'Ze względów bezpieczeństwa, możesz usunąć tylko 10 wiadomości na raz.', 26 | ); 27 | }); 28 | 29 | it('should show an error when you try to delete adsads messages', () => { 30 | const msg = getMessageMock('msg', {}); 31 | 32 | return expect( 33 | prune.execute(msg as unknown as Discord.Message, ['adsads']), 34 | ).to.be.eventually.rejectedWith('Parametr musi być liczbą wiadomości.'); 35 | }); 36 | 37 | it('should fetch messages and delete them', async () => { 38 | const msg = getMessageMock('msg', {}); 39 | const memberMock = { 40 | hasPermission: Sinon.spy(), 41 | }; 42 | // tslint:disable-next-line: no-any 43 | const messagesCollectionMock = { clear: Sinon.spy() }; 44 | msg.channel.messages.fetch.resolves(messagesCollectionMock); 45 | msg.guild.members.cache.get.returns(memberMock); 46 | 47 | await expect(prune.execute(msg as unknown as Discord.Message, ['2'])).to.be.fulfilled; 48 | expect(msg.channel.messages.fetch).to.have.been.calledOnceWithExactly({ limit: 2 }); 49 | expect(msg.channel.bulkDelete).to.have.been.calledOnceWithExactly(messagesCollectionMock); 50 | }); 51 | 52 | it('should delete itself', async () => { 53 | const msg = getMessageMock('msg', {}); 54 | const messagesCollectionMock = { clear: Sinon.spy() } as any; 55 | msg.channel.messages.fetch.resolves(messagesCollectionMock); 56 | 57 | await prune.execute(msg as unknown as Discord.Message, ['2']); 58 | 59 | expect(msg.delete).to.have.been.calledOnce; 60 | }); 61 | }); 62 | -------------------------------------------------------------------------------- /src/commands/prune.ts: -------------------------------------------------------------------------------- 1 | import Discord from 'discord.js'; 2 | 3 | import type { Command } from '../types'; 4 | import { InvalidUsageError } from '../types'; 5 | 6 | const MIN_MESSAGES = 1; 7 | const MAX_MESSAGES = 10; 8 | 9 | const prune: Command = { 10 | name: 'prune', 11 | description: 'prune?', 12 | permissions: 'Administrator', 13 | args: 'required', 14 | async execute(msg, [howMany]) { 15 | // tslint:disable-next-line:no-magic-numbers 16 | const num = Number.parseInt(howMany, 10); 17 | 18 | if (!Number.isFinite(num)) { 19 | throw new InvalidUsageError('Parametr musi być liczbą wiadomości.'); 20 | } 21 | if (num < MIN_MESSAGES) { 22 | throw new InvalidUsageError(`Musisz podać przynajmniej ${MIN_MESSAGES}.`); 23 | } 24 | if (num > MAX_MESSAGES) { 25 | throw new InvalidUsageError( 26 | `Ze względów bezpieczeństwa, możesz usunąć tylko ${MAX_MESSAGES} wiadomości na raz.`, 27 | ); 28 | } 29 | 30 | await msg.delete(); 31 | if (msg.channel.type !== Discord.ChannelType.DM) { 32 | const messages = await msg.channel.messages.fetch({ limit: num }); 33 | await msg.channel.bulkDelete(messages); 34 | } 35 | return null; 36 | }, 37 | }; 38 | 39 | export default prune; 40 | -------------------------------------------------------------------------------- /src/commands/quiz.ts: -------------------------------------------------------------------------------- 1 | import fetch from 'node-fetch'; 2 | 3 | import type { Command } from '../types'; 4 | import { randomizeArray } from '../utils'; 5 | 6 | const MAX_QUESTIONS = 10; 7 | const USAGE_MESSAGE = `Format: !quiz kategoria poziom(opcjonalny) ilość(opcjonalny). 8 | Dostępne wartości: 9 | * kategoria: html, css, js, angular, react, git, other 10 | * poziom: junior, mid, senior 11 | * liczba: [1 - ${MAX_QUESTIONS}] - ile pytań wylosować 12 | `; 13 | const LEVELS = ['junior', 'mid', 'senior']; 14 | const CATEGORIES = ['html', 'css', 'js', 'angular', 'react', 'git', 'other']; 15 | 16 | const quiz: Command = { 17 | name: 'quiz', 18 | description: 'Odpowiedz na pytanie', 19 | args: 'required', 20 | async execute(msg, args) { 21 | const [category, level, amount = '1'] = args; 22 | 23 | const errorMsg = validateParams(category, level, amount); 24 | if (errorMsg) { 25 | return msg.channel.send(`${errorMsg} \`\`\`${USAGE_MESSAGE}\`\`\``); 26 | } 27 | 28 | const url = prepareUrl(category, level); 29 | const result = await fetch(url); 30 | const { 31 | data: questions, 32 | meta: { total }, 33 | } = (await result.json()) as DevFAQResponse; 34 | 35 | if (total === 0) { 36 | return msg.channel.send(`Niestety nie znalazłam pytań 😭`); 37 | } 38 | 39 | const shuffled = randomizeArray(questions); 40 | const selected = shuffled.slice(0, Number(amount)); 41 | const resQuestions = selected.map( 42 | (item, index) => `**Pytanie ${index + 1}:** ${item.question}`, 43 | ); 44 | 45 | return msg.channel.send(resQuestions.join('\n')); 46 | }, 47 | }; 48 | 49 | const validateParams = (category: string, level: string, amount: string) => { 50 | if (!category || !CATEGORIES.includes(category)) { 51 | return `Nie znalazłam takiej kategorii 😭`; 52 | } 53 | if (level && !LEVELS.includes(level)) { 54 | return `Nie znalazłam takiego poziomu 😭`; 55 | } 56 | if (amount && (Number(amount) <= 0 || Number(amount) > MAX_QUESTIONS)) { 57 | return `Maksymalnie możesz poprosić o ${MAX_QUESTIONS} pytań.`; 58 | } 59 | 60 | return ''; 61 | }; 62 | 63 | const prepareUrl = (category: string, level: string) => { 64 | const encodedCategory = encodeURIComponent(category); 65 | const urlBase: string = `https://api.devfaq.pl/questions?category=${encodedCategory}`; 66 | if (level) { 67 | const encodedLevel = encodeURIComponent(level); 68 | return `${urlBase}&level=${encodedLevel}`; 69 | } 70 | 71 | return urlBase; 72 | }; 73 | 74 | export default quiz; 75 | 76 | interface DevFAQResponse { 77 | readonly data: readonly DevFAQ[]; 78 | readonly meta: { 79 | readonly total: number; 80 | }; 81 | } 82 | 83 | interface DevFAQ { 84 | readonly id: number; 85 | readonly question: string; 86 | readonly _categoryId: string; 87 | readonly _levelId: string; 88 | readonly _statusId: string; 89 | readonly acceptedAt: string; 90 | readonly currentUserVotedOn: boolean; 91 | } 92 | -------------------------------------------------------------------------------- /src/commands/reflink.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | 3 | import { helionReflink, xKomReflink } from './reflink'; 4 | 5 | describe('reflink', () => { 6 | describe('x-kom', () => { 7 | [ 8 | [ 9 | 'https://www.x-kom.pl/p/690347-notebook-laptop-140-apple-macbook-pro-m1-pro-16gb-512-mac-os-space-gray.html', 10 | 'https://www.x-kom.pl/p/690347-notebook-laptop-140-apple-macbook-pro-m1-pro-16gb-512-mac-os-space-gray.html?partnerid=100162370&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd&106', 11 | ], 12 | [ 13 | 'https://www.x-kom.pl/p/590802-klawiatura-bezprzewodowa-logitech-mx-keys-for-mac-space-gray.html', 14 | 'https://www.x-kom.pl/p/590802-klawiatura-bezprzewodowa-logitech-mx-keys-for-mac-space-gray.html?partnerid=100162370&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd&95', 15 | ], 16 | [ 17 | 'https://www.x-kom.pl/p/523891-monitor-led-27-lg-27ul850-w-4k-hdr.html', 18 | 'https://www.x-kom.pl/p/523891-monitor-led-27-lg-27ul850-w-4k-hdr.html?partnerid=100162370&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd&69', 19 | ], 20 | [ 21 | 'https://www.x-kom.pl/p/617252-mikrofon-novox-nc-1-game-box.html', 22 | 'https://www.x-kom.pl/p/617252-mikrofon-novox-nc-1-game-box.html?partnerid=100162370&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd&63', 23 | ], 24 | [ 25 | 'https://www.x-kom.pl/p/78034-kamera-internetowa-logitech-c920-pro-full-hd.html', 26 | 'https://www.x-kom.pl/p/78034-kamera-internetowa-logitech-c920-pro-full-hd.html?partnerid=100162370&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd&78', 27 | ], 28 | [ 29 | 'https://www.x-kom.pl/p/297064-dysk-sieciowy-nas-macierz-synology-ds216j-2xhdd-2x1ghz-512mb-2xusb-1xlan.html', 30 | 'https://www.x-kom.pl/p/297064-dysk-sieciowy-nas-macierz-synology-ds216j-2xhdd-2x1ghz-512mb-2xusb-1xlan.html?partnerid=100162370&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd&107', 31 | ], 32 | [ 33 | 'https://www.x-kom.pl/p/690347-notebook-laptop-140-apple-macbook-pro-m1-pro-16gb-512-mac-os-space-gray.html', 34 | 'https://www.x-kom.pl/p/690347-notebook-laptop-140-apple-macbook-pro-m1-pro-16gb-512-mac-os-space-gray.html?partnerid=100162370&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd&106', 35 | ], 36 | [ 37 | 'https://www.x-kom.pl/p/590802-klawiatura-bezprzewodowa-logitech-mx-keys-for-mac-space-gray.html', 38 | 'https://www.x-kom.pl/p/590802-klawiatura-bezprzewodowa-logitech-mx-keys-for-mac-space-gray.html?partnerid=100162370&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd&95', 39 | ], 40 | [ 41 | 'https://www.x-kom.pl/p/523891-monitor-led-27-lg-27ul850-w-4k-hdr.html', 42 | 'https://www.x-kom.pl/p/523891-monitor-led-27-lg-27ul850-w-4k-hdr.html?partnerid=100162370&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd&69', 43 | ], 44 | [ 45 | 'https://www.x-kom.pl/p/617252-mikrofon-novox-nc-1-game-box.html', 46 | 'https://www.x-kom.pl/p/617252-mikrofon-novox-nc-1-game-box.html?partnerid=100162370&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd&63', 47 | ], 48 | [ 49 | 'https://www.x-kom.pl/p/78034-kamera-internetowa-logitech-c920-pro-full-hd.html', 50 | 'https://www.x-kom.pl/p/78034-kamera-internetowa-logitech-c920-pro-full-hd.html?partnerid=100162370&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd&78', 51 | ], 52 | [ 53 | 'https://www.x-kom.pl/p/297064-dysk-sieciowy-nas-macierz-synology-ds216j-2xhdd-2x1ghz-512mb-2xusb-1xlan.html', 54 | 'https://www.x-kom.pl/p/297064-dysk-sieciowy-nas-macierz-synology-ds216j-2xhdd-2x1ghz-512mb-2xusb-1xlan.html?partnerid=100162370&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd&107', 55 | ], 56 | ].forEach(([input, expected]) => 57 | it(`should generate link for ${input}`, () => { 58 | expect(xKomReflink(input)).to.eql(expected); 59 | }), 60 | ); 61 | }); 62 | 63 | describe('helion', () => { 64 | [ 65 | [ 66 | `https://helion.pl/ksiazki/jezyk-c-i-przetwarzanie-wspolbiezne-w-akcji-wydanie-ii-anthony-williams,jcppw2.htm#format/d`, 67 | `https://helion.pl/view/117666/jcppw2.htm`, 68 | ], 69 | 70 | [ 71 | `https://helion.pl/ksiazki/jak-zarabiac-na-kryptowalutach-wydanie-ii-tomasz-waryszak,jakzk2.htm#format/d`, 72 | `https://helion.pl/view/117666/jakzk2.htm`, 73 | ], 74 | [ 75 | `https://onepress.pl/ksiazki/sir-ernest-shackleton-i-wyprawa-endurance-sekrety-przywodztwa-odpornego-na-kryzys-adam-staniszewski,sirern.htm#format/d`, 76 | `https://onepress.pl/view/117666/sirern.htm`, 77 | ], 78 | [ 79 | `https://septem.pl/ksiazki/pietno-morfeusza-k-n-haner,piemor.htm`, 80 | `https://septem.pl/view/117666/piemor.htm`, 81 | ], 82 | [ 83 | `https://sensus.pl/ksiazki/skutecznosc-gora-mechanizmy-inspiracje-techniki-wplywajace-na-twoje-decyzje-marek-skala,trzyfi.htm#format/d`, 84 | `https://sensus.pl/view/117666/trzyfi.htm`, 85 | ], 86 | [ 87 | `https://dlabystrzakow.pl/ksiazki/dieta-keto-dla-bystrzakow-rami-abrams-vicky-abrams,dikeby.htm#format/d`, 88 | `https://dlabystrzakow.pl/view/117666/dikeby.htm`, 89 | ], 90 | [ 91 | `https://bezdroza.pl/ksiazki/szlaki-polski-30-najpiekniejszych-tras-dlugodystansowych-lukasz-supergan,beszpo.htm#format/d`, 92 | `https://bezdroza.pl/view/117666/beszpo.htm`, 93 | ], 94 | [ 95 | `https://ebookpoint.pl/ksiazki/wojna-w-kosmosie-przewrot-w-geopolityce-jacek-bartosiak-george-friedman,e_25zw.htm#format/e`, 96 | `https://ebookpoint.pl/view/117666/e_25zw.htm`, 97 | ], 98 | [ 99 | `https://videopoint.pl/kurs/machine-learning-i-jezyk-python-kurs-video-praktyczne-wykorzystanie-popularnych-bibliotek-piotr-szajowski,vprwyp.htm#format/w`, 100 | `https://videopoint.pl/view/117666/vprwyp.htm`, 101 | ], 102 | ].forEach(([input, expected]) => 103 | it(`should generate link for ${input}`, () => { 104 | expect(helionReflink(input)).to.eql(expected); 105 | }), 106 | ); 107 | }); 108 | }); 109 | -------------------------------------------------------------------------------- /src/commands/reflink.ts: -------------------------------------------------------------------------------- 1 | const X_KOM_PATTERN = /^https?:\/\/([^.]+\.)?x-kom.pl/; 2 | const X_KOM_PARTNER_ID = `100162370`; 3 | 4 | const HELION_PARTNER_ID = '117666'; 5 | const HELION_ID_PATTERN = /^https?:\/\/([^.]+).*,(.*?)\.htm/; 6 | const HELION_DOMAINS = [ 7 | `helion`, 8 | `onepress`, 9 | `septem`, 10 | `sensus`, 11 | `dlabystrzakow`, 12 | `bezdroza`, 13 | `ebookpoint`, 14 | `videopoint`, 15 | ]; 16 | 17 | export const isXKomReflink = (url: string) => X_KOM_PATTERN.test(url); 18 | 19 | export const xKomReflink = (url: string) => { 20 | if (!isXKomReflink(url)) { 21 | return null; 22 | } 23 | 24 | const suffix = `?partnerid=${X_KOM_PARTNER_ID}&sm12=NDY=&ts=1641758054&token=6ab7b9cde43c838f9e76042a3b8bfdcd`; 25 | const mainLink = url.split('#')[0]; 26 | return mainLink + suffix + '&' + mainLink.length.toString(); 27 | }; 28 | 29 | export const isHelionReflink = (url: string) => { 30 | const maybeMatch = url.match(HELION_ID_PATTERN); 31 | if (!maybeMatch) { 32 | return false; 33 | } 34 | 35 | const [_, domain, productId] = maybeMatch; 36 | 37 | if (!HELION_DOMAINS.includes(domain) || !productId) { 38 | return false; 39 | } 40 | 41 | return true; 42 | }; 43 | 44 | export const helionReflink = (url: string) => { 45 | if (!isHelionReflink(url)) { 46 | return null; 47 | } 48 | 49 | const [_, domain, productId] = url.match(HELION_ID_PATTERN)!; 50 | 51 | return `https://${domain}.pl/view/${HELION_PARTNER_ID}/${productId}.htm`; 52 | }; 53 | 54 | export const myDevilReflink = () => { 55 | return `https://www.mydevil.net/pp/9UVOSJRZIV`; 56 | }; 57 | 58 | export const messageToReflinks = (message: string): readonly string[] => { 59 | const maybeLinks = message.match(/https?:\/\/[^\s]+/g); 60 | if (!maybeLinks) { 61 | return []; 62 | } 63 | 64 | return maybeLinks 65 | .map((maybeLink) => { 66 | if (isXKomReflink(maybeLink)) { 67 | return xKomReflink(maybeLink); 68 | } 69 | if (isHelionReflink(maybeLink)) { 70 | return helionReflink(maybeLink); 71 | } 72 | return null; 73 | }) 74 | .filter((x): x is Exclude => !!x); 75 | }; 76 | -------------------------------------------------------------------------------- /src/commands/regulamin.ts: -------------------------------------------------------------------------------- 1 | import type Discord from 'discord.js'; 2 | 3 | import type { Command } from '../types'; 4 | 5 | const regulamin: Command = { 6 | name: 'regulamin', 7 | description: 'Wyświetla regulamin.', 8 | args: 'prohibited', 9 | execute(msg: Discord.Message) { 10 | return msg.channel.send(`Regulamin: https://typeofweb.com/polski-frontend-discord/`); 11 | }, 12 | }; 13 | 14 | export default regulamin; 15 | -------------------------------------------------------------------------------- /src/commands/roll.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import 'mocha'; 3 | import type * as Discord from 'discord.js'; 4 | 5 | import { getMessageMock } from '../../test/mocks'; 6 | 7 | import roll, { parseDice, rollDices, instruction } from './roll'; 8 | 9 | describe('roll', () => { 10 | describe('parser', () => { 11 | it('parses valid simple roll', () => { 12 | const res = parseDice('4d6'); 13 | expect(res.count).to.be.equal(4); 14 | expect(res.dice).to.be.equal(6); 15 | }); 16 | it('throws on invalid input', () => { 17 | expect(() => parseDice('4ds6')).to.throw(); 18 | }); 19 | it('parses valid roll with modifier', () => { 20 | const res = parseDice('4d6+5'); 21 | expect(res.count).to.be.equal(4); 22 | expect(res.dice).to.be.equal(6); 23 | expect(res.modifier).to.be.equal(5); 24 | }); 25 | it('parses valid roll with negative modifier', () => { 26 | const res = parseDice('4d6-3'); 27 | expect(res.count).to.be.equal(4); 28 | expect(res.dice).to.be.equal(6); 29 | expect(res.modifier).to.be.equal(-3); 30 | }); 31 | }); 32 | describe('roll', () => { 33 | it('allows valid response', () => { 34 | const count = 4; 35 | const dice = 6; 36 | const modifier = 1; 37 | const notation = `${count}d${dice}+${modifier}`; 38 | const res = rollDices(notation); 39 | expect(res.notation).to.be.equal(notation); 40 | expect(res.value).to.be.lessThan(count * dice * modifier + 1); 41 | }); 42 | it('does not allow invalid response', () => { 43 | const count = 400; 44 | const dice = 6; 45 | const modifier = 1; 46 | const notation = `${count}d${dice}+${modifier}`; 47 | expect(() => rollDices(notation)).to.throw(); 48 | }); 49 | }); 50 | describe('handleCommand', () => { 51 | it('should reply', async () => { 52 | const msg = getMessageMock('msg', {}); 53 | await roll.execute(msg as unknown as Discord.Message, ['4d6']); 54 | expect(msg.channel.send).to.have.been.calledOnce; 55 | }); 56 | it('reply instruction on fail', async () => { 57 | const msg = getMessageMock('msg', {}); 58 | await roll.execute(msg as unknown as Discord.Message, ['3k5']); 59 | expect(msg.channel.send).to.have.been.calledOnceWith(instruction); 60 | }); 61 | }); 62 | }); 63 | -------------------------------------------------------------------------------- /src/commands/roll.ts: -------------------------------------------------------------------------------- 1 | import type { Command } from '../types'; 2 | 3 | const MAX_COUNT = 20; 4 | const MAX_DICE = 100; 5 | const REGEX = /([0-9]{1,4})d([0-9]{1,4})([+-][0-9]{1,10})?/; 6 | 7 | export function parseDice(arg: string) { 8 | const res = arg.match(REGEX); 9 | if (res == null) { 10 | throw new Error('Invalid argument'); 11 | } 12 | const [notation, count, dice, modifier] = res; 13 | return { 14 | notation, 15 | count: parseInt(count, 10), 16 | dice: parseInt(dice, 10), 17 | modifier: parseInt(modifier ?? 0, 10), 18 | }; 19 | } 20 | 21 | export function rollDices(content: string) { 22 | const parsed = parseDice(content); 23 | if (parsed.count <= 0 || parsed.count > MAX_COUNT || parsed.dice <= 0 || parsed.dice > MAX_DICE) { 24 | throw new Error('Invalid argument values'); 25 | } 26 | const rolls = Array.from({ length: parsed.count }) 27 | .map(() => Math.random() * parsed.dice + 1) 28 | .map(Math.floor); 29 | return { 30 | notation: parsed.notation, 31 | value: rolls.reduce((acc, val) => acc + val, parsed.modifier), 32 | rolls, 33 | }; 34 | } 35 | 36 | export const instruction = 37 | 'Wpisz `!roll [liczba kości]d[liczba ścian]`, aby rzucić kośćmi, np `!roll 2d6+1`'; 38 | 39 | const roll: Command = { 40 | name: 'roll', 41 | description: 'Rzuca kośćmi.', 42 | args: 'required', 43 | execute(msg, args) { 44 | try { 45 | const result = rollDices(args[0]); 46 | const rollsResult = `${result.rolls.join('+')}`; 47 | const response = `:game_die: [${result.notation}] **${result.value}** = ${rollsResult}`; 48 | return msg.channel.send(response); 49 | } catch (error) { 50 | return msg.channel.send(instruction); 51 | } 52 | }, 53 | }; 54 | 55 | export default roll; 56 | -------------------------------------------------------------------------------- /src/commands/server.ts: -------------------------------------------------------------------------------- 1 | import type Discord from 'discord.js'; 2 | 3 | import type { Command } from '../types'; 4 | 5 | const server: Command = { 6 | name: 'server', 7 | description: 'Zwraca nazwę serwera.', 8 | args: 'prohibited', 9 | execute(msg: Discord.Message) { 10 | return msg.channel.send(`Nazwa tego serwera to: ${String(msg.guild?.name)}`); 11 | }, 12 | }; 13 | 14 | export default server; 15 | -------------------------------------------------------------------------------- /src/commands/skierowanie.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import type * as Discord from 'discord.js'; 3 | 4 | import { getMessageMock } from '../../test/mocks'; 5 | 6 | import skierowanie from './skierowanie'; 7 | 8 | describe('skierowanie', () => { 9 | const mockAuthor = { username: 'user', avatarURL: () => 'http://url.com' }; 10 | 11 | it('it should send two messages', async () => { 12 | const msg = getMessageMock('msg', { author: mockAuthor }); 13 | 14 | await skierowanie.execute(msg as unknown as Discord.Message, ['user']); 15 | 16 | return expect(msg.channel.send).to.have.been.calledOnce; 17 | }); 18 | 19 | it('it should send the links for the passed category', async () => { 20 | const msg = getMessageMock('msg', { author: mockAuthor }); 21 | 22 | await skierowanie.execute(msg as unknown as Discord.Message, ['user', 'react']); 23 | 24 | const linksMessageMock = [ 25 | 'https://reactjs.org/docs', 26 | 'https://developer.mozilla.org/en-US/docs/Learn', 27 | 'https://typeofweb.com', 28 | 'https://frontlive.pl', 29 | ]; 30 | 31 | const argsEmbedsData = ( 32 | msg.channel.send.args[0][0] as { readonly embeds: readonly Discord.EmbedBuilder[] } 33 | ).embeds 34 | .flatMap((e) => e.data.fields) 35 | .map((e) => e?.value); 36 | 37 | expect(argsEmbedsData).to.include( 38 | `Z powyższym skierowaniem należy udać się na poniższe strony internetowe:`, 39 | ); 40 | expect( 41 | linksMessageMock.every((link) => argsEmbedsData.some((e) => e?.includes(link))), 42 | ).to.equal(true); 43 | }); 44 | }); 45 | -------------------------------------------------------------------------------- /src/commands/skierowanie.ts: -------------------------------------------------------------------------------- 1 | import Discord from 'discord.js'; 2 | 3 | import type { Command } from '../types'; 4 | 5 | const links = [ 6 | { url: 'https://kursjs.pl', category: 'js' }, 7 | { url: 'https://javascript.info', category: 'js' }, 8 | { url: 'https://javascript30.com/', category: 'js' }, 9 | { url: 'https://developer.mozilla.org/en-US/docs/Learn/JavaScript', category: 'js' }, 10 | { url: 'https://reactjs.org/docs', category: 'react' }, 11 | { url: 'https://tutorials.comandeer.pl/html5-blog.html', category: 'html' }, 12 | { url: 'https://blog.comandeer.pl/o-naglowkach-slow-kilka.html', category: 'html' }, 13 | { url: 'https://blog.comandeer.pl/o-ikonkach-slow-kilka.html', category: 'html' }, 14 | { url: 'https://blog.comandeer.pl/o-semantyce-slow-kilka.html', category: 'html' }, 15 | { url: 'https://www.smashingmagazine.com/guides/css-layout/', category: 'css' }, 16 | { url: 'https://css-tricks.com/', category: 'css' }, 17 | { url: 'https://en.bem.info/methodology/quick-start/', category: 'css' }, 18 | { url: 'https://blog.comandeer.pl/bem-jako-architektura.html', category: 'css' }, 19 | { url: 'https://ishadeed.com/articles/', category: 'a11y' }, 20 | { url: 'https://frontlive.pl/kategorie/dostepnosc', category: 'a11y' }, 21 | { url: 'https://www.a11yproject.com/', category: 'a11y' }, 22 | { url: 'https://blog.comandeer.pl/a11y/', category: 'a11y' }, 23 | { url: 'https://www.smashingmagazine.com/guides/accessibility/', category: 'a11y' }, 24 | { url: 'https://www.scottohara.me/writing/', category: 'a11y' }, 25 | { url: 'https://webaim.org/', category: 'a11y' }, 26 | { url: 'https://typescriptnapowaznie.pl/', category: 'ts' }, 27 | { url: 'https://www.typescriptlang.org/docs/', category: 'ts' }, 28 | { url: 'https://github.com/typescript-cheatsheets', category: 'ts' }, 29 | { url: 'https://developer.mozilla.org/en-US/docs/Learn' }, 30 | { url: 'https://typeofweb.com' }, 31 | { url: 'https://frontlive.pl' }, 32 | ]; 33 | 34 | const skierowanie: Command = { 35 | name: 'skierowanie', 36 | description: 37 | 'Skierowanie na naukę podstaw (+ dobre materiały do nauki). Składnia: `!skierowanie `', 38 | args: 'required', 39 | cooldown: 10, 40 | execute(msg, av) { 41 | // Filter out the empty args (whitespaces, etc) 42 | const args = av.filter((val) => val); 43 | 44 | const skierowanieEmbed = new Discord.EmbedBuilder() 45 | .setColor('#5ab783') 46 | .setAuthor({ 47 | name: `Type of Web oraz ${msg.author.username}`, 48 | iconURL: msg.author.avatarURL() ?? undefined, 49 | url: 'https://typeofweb.com', 50 | }) 51 | .setTitle('Skierowanie na naukę podstaw 🚑') 52 | .setThumbnail('https://typeofweb.com/wp-content/uploads/2020/04/logo_kwadrat11.png') 53 | .addFields([ 54 | { 55 | name: '1', 56 | value: 57 | 'Działając na podstawie mojej intuicji oraz wiadomości wysłanych przez osobę skierowaną, kieruję użytkownika/użytkowniczkę', 58 | }, 59 | { 60 | name: '2', 61 | value: args[0], 62 | }, 63 | { 64 | name: '3', 65 | value: `na naukę podstaw wybranej przez siebie technologii,`, 66 | }, 67 | { 68 | name: '4', 69 | value: `w celu lepszego zrozumienia fundamentów jej działania oraz poznania informacji niezbędnych do rozszerzania swojej wiedzy o bardziej zaawansowane zagadnienia`, 70 | }, 71 | ]) 72 | .setTimestamp() 73 | .setFooter({ 74 | text: 'Type of Web, Discord, Polska', 75 | iconURL: 76 | 'https://cdn.discordapp.com/avatars/574682557988470825/6b0fab28093e6020f497fda41bdd3219.png?size=64', 77 | }); 78 | 79 | const categoryFilter = args[1]?.toLowerCase(); 80 | const linksFiltered = categoryFilter 81 | ? links.filter(({ category }) => !category || category === categoryFilter) 82 | : links.filter(({ category }) => !category); 83 | 84 | const linksMessage = 'Z powyższym skierowaniem należy udać się na poniższe strony internetowe:'; 85 | 86 | const linksEmbed = new Discord.EmbedBuilder().addFields([ 87 | { name: '1', value: linksMessage }, 88 | { name: '2', value: linksFiltered.map((l) => l.url).join('\n') }, 89 | ]); 90 | 91 | return msg.channel.send({ embeds: [skierowanieEmbed, linksEmbed] }); 92 | }, 93 | }; 94 | 95 | export default skierowanie; 96 | -------------------------------------------------------------------------------- /src/commands/spotify.ts: -------------------------------------------------------------------------------- 1 | import { URLSearchParams } from 'url'; 2 | 3 | import type Discord from 'discord.js'; 4 | import fetch from 'node-fetch'; 5 | 6 | import { getConfig } from '../config'; 7 | import type { Command } from '../types'; 8 | 9 | const spotify: Command = { 10 | name: 'spotify', 11 | description: 'Pjosenkę gra.', 12 | args: 'required', 13 | async execute(msg: Discord.Message, args: readonly string[]) { 14 | const secret = Buffer.from( 15 | `${getConfig('SPOTIFY_CLIENT_ID')}:${getConfig('SPOTIFY_SECRET')}`, 16 | ).toString('base64'); 17 | 18 | const query = encodeURIComponent(args.join(' ')); 19 | const searchParams = new URLSearchParams(); 20 | searchParams.set('grant_type', 'client_credentials'); 21 | 22 | const res = await fetch('https://accounts.spotify.com/api/token', { 23 | method: 'POST', 24 | body: searchParams, 25 | headers: { 26 | Authorization: `Basic ${secret}`, 27 | 'Content-Type': 'application/x-www-form-urlencoded', 28 | }, 29 | }); 30 | const { access_token } = (await res.json()) as TokenResponse; 31 | const results = await fetch( 32 | `https://api.spotify.com/v1/search/?q=${query}&type=track&limit=1`, 33 | { 34 | headers: { 35 | Authorization: `Bearer ${access_token}`, 36 | }, 37 | }, 38 | ); 39 | 40 | const { 41 | tracks: { items }, 42 | } = (await results.json()) as QueryResponse; 43 | 44 | return items[0] 45 | ? msg.channel.send(items[0].external_urls.spotify) 46 | : msg.channel.send('Niestety nic nie znalazłam 🎷'); 47 | }, 48 | }; 49 | 50 | export default spotify; 51 | 52 | interface TokenResponse { 53 | readonly access_token: string; 54 | readonly token_type: string; 55 | readonly expires_in: number; 56 | } 57 | 58 | interface QueryResponse { 59 | readonly tracks: Tracks; 60 | } 61 | 62 | interface Tracks { 63 | readonly href: string; 64 | readonly items: readonly Item[]; 65 | readonly limit: number; 66 | readonly next: string; 67 | readonly offset: number; 68 | readonly total: number; 69 | } 70 | 71 | interface Item { 72 | readonly album: Album; 73 | readonly artists: readonly Artist[]; 74 | readonly available_markets: readonly string[]; 75 | readonly disc_number: number; 76 | readonly duration_ms: number; 77 | readonly explicit: boolean; 78 | readonly external_ids: ExternalIds; 79 | readonly external_urls: ExternalURLs; 80 | readonly href: string; 81 | readonly id: string; 82 | readonly is_local: boolean; 83 | readonly name: string; 84 | readonly popularity: number; 85 | readonly preview_url: string; 86 | readonly track_number: number; 87 | readonly type: string; 88 | readonly uri: string; 89 | } 90 | 91 | interface ExternalIds { 92 | readonly isrc: string; 93 | } 94 | 95 | interface Album { 96 | readonly album_type: string; 97 | readonly artists: readonly Artist[]; 98 | readonly available_markets: readonly string[]; 99 | readonly external_urls: ExternalURLs; 100 | readonly href: string; 101 | readonly id: string; 102 | readonly images: readonly Image[]; 103 | readonly name: string; 104 | readonly release_date: string; 105 | readonly release_date_precision: string; 106 | readonly total_tracks: number; 107 | readonly type: string; 108 | readonly uri: string; 109 | } 110 | 111 | interface Image { 112 | readonly height: number; 113 | readonly url: string; 114 | readonly width: number; 115 | } 116 | 117 | interface Artist { 118 | readonly external_urls: ExternalURLs; 119 | readonly href: string; 120 | readonly id: string; 121 | readonly name: string; 122 | readonly type: string; 123 | readonly uri: string; 124 | } 125 | 126 | interface ExternalURLs { 127 | readonly spotify: string; 128 | } 129 | -------------------------------------------------------------------------------- /src/commands/stackoverflow.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import * as Discord from 'discord.js'; 3 | import nock from 'nock'; 4 | 5 | import { getMessageMock } from '../../test/mocks'; 6 | 7 | import stackoverflow from './stackoverflow'; 8 | 9 | describe('stackoverflow', () => { 10 | const mockItem = { 11 | link: 'Jak pisać testy', 12 | title: 'https://stackoverflow.com/questions/0/how-to-write-tests', 13 | } as const; 14 | 15 | const mockLinksEmbed = () => 16 | new Discord.EmbedBuilder() 17 | .setAuthor({ 18 | name: 'Stack Overflow', 19 | iconURL: 20 | 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Stack_Overflow_icon.svg/768px-Stack_Overflow_icon.svg.png', 21 | url: 'https://stackoverflow.com/', 22 | }) 23 | .setTitle('1 najlepsza odpowiedź:') 24 | .setColor('#f4811e') 25 | .addFields([{ name: mockItem.title, value: mockItem.link }]); 26 | 27 | it('should show error message when nothing found on stackoverflow', async () => { 28 | nock('https://api.stackexchange.com') 29 | .get( 30 | '/2.3/search/advanced?pagesize=5&order=desc&sort=activity&q=jak%20pisac%20testy&site=stackoverflow', 31 | ) 32 | .reply(200, { items: [] }); 33 | 34 | const msg = getMessageMock('msg', {}); 35 | 36 | await stackoverflow.execute(msg as unknown as Discord.Message, ['jak', 'pisac', 'testy']); 37 | 38 | return expect(msg.channel.send).to.have.been.calledOnce.and.calledWithMatch( 39 | 'Niestety nic nie znalazłem', 40 | ); 41 | }); 42 | 43 | it('should show links when found on stackoverflow', async () => { 44 | nock('https://api.stackexchange.com') 45 | .get( 46 | '/2.3/search/advanced?pagesize=5&order=desc&sort=activity&q=jak%20pisac%20testy&site=stackoverflow', 47 | ) 48 | .reply(200, { 49 | items: [mockItem], 50 | }); 51 | 52 | const msg = getMessageMock('msg', {}); 53 | 54 | await stackoverflow.execute(msg as unknown as Discord.Message, ['jak', 'pisac', 'testy']); 55 | 56 | return expect( 57 | ( 58 | msg.channel.send.args[0][0] as { readonly embeds: readonly Discord.EmbedBuilder[] } 59 | ).embeds.map((e) => e.data)[0], 60 | ).to.eql(mockLinksEmbed().data); 61 | }); 62 | }); 63 | -------------------------------------------------------------------------------- /src/commands/stackoverflow.ts: -------------------------------------------------------------------------------- 1 | import Discord from 'discord.js'; 2 | import fetch from 'node-fetch'; 3 | 4 | import type { Command } from '../types'; 5 | 6 | const ICON_URL = 7 | 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Stack_Overflow_icon.svg/768px-Stack_Overflow_icon.svg.png'; 8 | 9 | const isApiError = (data: ApiResponse): data is ApiResponseError => 'error_id' in data; 10 | 11 | const formatTitle = (length: number) => 12 | length === 1 13 | ? 'najlepsza odpowiedź' 14 | : length < 5 15 | ? 'najlepsze odpowiedzi' 16 | : 'najlepszych odpowiedzi'; 17 | 18 | const stackoverflow: Command = { 19 | name: 'stackoverflow', 20 | description: 'Wyszukaj swój problem na stackoverflow', 21 | args: 'required', 22 | async execute(msg, args) { 23 | const query = encodeURIComponent(args.join(' ').toLocaleLowerCase()); 24 | const result = await fetch( 25 | `https://api.stackexchange.com/2.3/search/advanced?pagesize=5&order=desc&sort=activity&q=${query}&site=stackoverflow`, 26 | ); 27 | const response = (await result.json()) as ApiResponse; 28 | 29 | if (!result.ok || isApiError(response)) { 30 | return msg.channel.send('Przepraszam, ale coś poszło nie tak 😭'); 31 | } 32 | 33 | const fields = response.items.map(({ title, link }) => ({ 34 | name: title, 35 | value: link, 36 | })); 37 | 38 | if (fields.length === 0) { 39 | return msg.channel.send('Niestety nic nie znalazłem 😭'); 40 | } 41 | 42 | const embed = new Discord.EmbedBuilder() 43 | .setAuthor({ 44 | name: 'Stack Overflow', 45 | iconURL: ICON_URL, 46 | url: 'https://stackoverflow.com/', 47 | }) 48 | .setTitle(`${fields.length} ${formatTitle(fields.length)}:`) 49 | .addFields(fields) 50 | .setColor('#f4811e'); 51 | 52 | return msg.channel.send({ embeds: [embed] }); 53 | }, 54 | }; 55 | 56 | export default stackoverflow; 57 | 58 | interface ApiOwner { 59 | readonly account_id: number; 60 | readonly reputation: number; 61 | readonly user_id: number; 62 | readonly user_type: string; 63 | readonly profile_image: string; 64 | readonly display_name: string; 65 | readonly link: string; 66 | } 67 | 68 | interface ApiItem { 69 | readonly tags: ReadonlyArray; 70 | readonly owner: ApiOwner; 71 | readonly is_answered: boolean; 72 | readonly view_count: number; 73 | readonly answer_count: number; 74 | readonly score: number; 75 | readonly last_activity_date: number; 76 | readonly creation_date: number; 77 | readonly question_id: number; 78 | readonly content_license: string; 79 | readonly link: string; 80 | readonly title: string; 81 | } 82 | 83 | interface ApiResponseSuccess { 84 | readonly items: ReadonlyArray; 85 | readonly has_more: boolean; 86 | readonly quota_max: number; 87 | readonly quota_remaining: number; 88 | } 89 | 90 | interface ApiResponseError { 91 | readonly error_id: number; 92 | readonly error_message: string; 93 | readonly error_name: string; 94 | } 95 | 96 | type ApiResponse = ApiResponseSuccess | ApiResponseError; 97 | -------------------------------------------------------------------------------- /src/commands/stats.ts: -------------------------------------------------------------------------------- 1 | import type { Db } from 'mongodb'; 2 | 3 | import { getStatsCollection, initDb } from '../db'; 4 | import type { Command } from '../types'; 5 | import { getDateForWeekNumber, getWeekNumber } from '../utils'; 6 | 7 | const formatDate = (d: Date) => 8 | String(d.getFullYear()) + 9 | '-' + 10 | String(d.getMonth() + 1).padStart(2, '0') + 11 | '-' + 12 | String(d.getDate()).padStart(2, '0'); 13 | 14 | const stats: Command = { 15 | name: 'stats', 16 | description: 'Stats', 17 | args: 'prohibited', 18 | permissions: 'Administrator', 19 | async execute(msg) { 20 | const db = await initDb(); 21 | 22 | const { totalStats, statsThisWeek, year1, week1 } = await getStatsChangeThisWeek(db); 23 | 24 | // Monday 25 | const d1 = getDateForWeekNumber(year1, week1); 26 | d1.setUTCDate(d1.getUTCDate() - (d1.getUTCDay() || 7)); 27 | 28 | // Sunday 29 | const d2 = new Date(d1); 30 | d2.setUTCDate(d2.getUTCDate() + 6); 31 | 32 | return msg.channel.send( 33 | [ 34 | format( 35 | `Najbardziej aktywne osoby w tym tygodniu (${formatDate(d1)} – ${formatDate(d2)}):`, 36 | statsThisWeek, 37 | ), 38 | '\n', 39 | format('Najbardziej aktywne osoby od początku istnienia serwera:', totalStats), 40 | ].join('\n'), 41 | ); 42 | }, 43 | }; 44 | 45 | export default stats; 46 | 47 | function format( 48 | title: string, 49 | stats: readonly { readonly messagesCount?: number | null; readonly memberName?: string | null }[], 50 | ) { 51 | const messages = [ 52 | `**${title}**`, 53 | ...stats 54 | .filter((d) => d.messagesCount) 55 | .map( 56 | ({ messagesCount, memberName }, index) => 57 | `\`${(index + 1).toString().padStart(2, ' ')}\`. ${memberName ?? ''} – ${ 58 | messagesCount ?? 0 59 | }`, 60 | ), 61 | ]; 62 | return messages.join('\n'); 63 | } 64 | 65 | async function getStatsChangeThisWeek(db: Db) { 66 | const statsCollection = getStatsCollection(db); 67 | 68 | const now = new Date(); 69 | const [year1, week1] = getWeekNumber(now); 70 | const thisWeek = `${year1}-${week1}`; 71 | 72 | now.setDate(now.getDate() - 7); 73 | const [year2, week2] = getWeekNumber(now); 74 | 75 | const statsThisWeekPromise = statsCollection 76 | .find({ yearWeek: thisWeek }) 77 | .sort({ messagesCount: -1 }) 78 | .limit(10) 79 | .toArray(); 80 | 81 | // @todo should aggregate and sum 82 | const totalStatsPromise = getStats(db); 83 | 84 | const [statsThisWeek, totalStats] = await Promise.all([statsThisWeekPromise, totalStatsPromise]); 85 | 86 | return { 87 | statsThisWeek, 88 | totalStats, 89 | year1, 90 | year2, 91 | week1, 92 | week2, 93 | }; 94 | } 95 | 96 | export type StatsAgg = { 97 | readonly _id: string; 98 | readonly messagesCount: number; 99 | readonly memberName: string; 100 | }; 101 | 102 | const statsAggregation = [ 103 | { 104 | $group: { 105 | _id: '$memberId', 106 | messagesCount: { $sum: '$messagesCount' }, 107 | memberName: { $push: '$memberName' }, 108 | }, 109 | }, 110 | { $sort: { messagesCount: -1 } }, 111 | { $limit: 10 }, 112 | { $addFields: { memberName: { $arrayElemAt: [{ $reverseArray: '$memberName' }, 0] } } }, 113 | ]; 114 | 115 | export const getStats = async (db: Db) => { 116 | const statsCollection = getStatsCollection(db); 117 | 118 | const agg = await statsCollection.aggregate(statsAggregation).toArray(); 119 | return agg; 120 | }; 121 | -------------------------------------------------------------------------------- /src/commands/summon.ts: -------------------------------------------------------------------------------- 1 | import type { Command } from '../types'; 2 | 3 | const summon: Command = { 4 | name: 'summon', 5 | description: '_Wake up, Michał, someone is wrong on the Internet…_', 6 | args: 'prohibited', 7 | cooldown: 60, 8 | execute(msg) { 9 | return msg.channel.send({ 10 | files: [ 11 | { 12 | attachment: 'https://i.imgur.com/Sl42AMi.png', 13 | }, 14 | ], 15 | }); 16 | }, 17 | }; 18 | 19 | export default summon; 20 | -------------------------------------------------------------------------------- /src/commands/towarticle.ts: -------------------------------------------------------------------------------- 1 | import Algoliasearch from 'algoliasearch'; 2 | import Discord from 'discord.js'; 3 | import { polishPlurals } from 'polish-plurals'; 4 | 5 | import { getConfig } from '../config'; 6 | import type { Command } from '../types'; 7 | 8 | const pluralize = (count: number) => polishPlurals('artykuł', 'artykuły', 'artykułów', count); 9 | 10 | const PER_PAGE = 3; 11 | 12 | const typeofweb: Command = { 13 | name: 'typeofweb', 14 | description: 'Wyszukuje artykuły z Type of Web', 15 | args: 'required', 16 | async execute(msg, args) { 17 | const ALGOLIA_APP_ID = getConfig('ALGOLIA_APP_ID'); 18 | const ALGOLIA_API_KEY = getConfig('ALGOLIA_API_KEY'); 19 | const ALGOLIA_INDEX_NAME = getConfig('ALGOLIA_INDEX_NAME'); 20 | 21 | const client = Algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY); 22 | const index = client.initIndex(ALGOLIA_INDEX_NAME); 23 | 24 | const query = args.join(' '); 25 | const res = await index.search(query, { 26 | hitsPerPage: PER_PAGE, 27 | }); 28 | const total = res.hits.length; 29 | 30 | if (!total) { 31 | return msg.channel.send(`Niestety nic nie znalazłam 😭`); 32 | } 33 | 34 | console.log(res.hits.map((h) => h.authors)); 35 | 36 | const results = res.hits.map((h) => 37 | new Discord.EmbedBuilder() 38 | .setTitle(h.title) 39 | .setURL(`https://typeofweb.com/${h.permalink}`) 40 | .setThumbnail(`https://typeofweb.com/${h.img.url.replace(/^\/public\//, '')}`) 41 | .setFooter({ 42 | text: '', 43 | iconURL: `https://typeofweb.com/${h.permalink}`, 44 | }) 45 | .setColor([28, 160, 86]) 46 | .setAuthor({ 47 | name: h.authors 48 | .map((a) => a.replace(/(?:^|-)(\w)/g, (_, m: string) => ' ' + m.toUpperCase()).trim()) 49 | .join('\n'), 50 | }) 51 | .setDescription(h.excerpt), 52 | ); 53 | 54 | return msg.channel.send({ 55 | content: `Pokazuję pierwsze ${total} ${pluralize(total)}:`, 56 | embeds: results, 57 | }); 58 | }, 59 | }; 60 | 61 | export default typeofweb; 62 | 63 | interface TypeOfWebAlgoliaResult { 64 | readonly title: string; 65 | readonly date: Date; 66 | readonly type: string; 67 | readonly permalink: string; 68 | readonly authors: readonly string[]; 69 | readonly excerpt: string; 70 | readonly content: string; 71 | readonly img: Img; 72 | readonly category: Category; 73 | } 74 | 75 | interface Category { 76 | readonly slug: string; 77 | readonly name: string; 78 | } 79 | 80 | interface Img { 81 | readonly url: string; 82 | readonly width: number; 83 | readonly height: number; 84 | } 85 | -------------------------------------------------------------------------------- /src/commands/wiki.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import type * as Discord from 'discord.js'; 3 | import nock from 'nock'; 4 | 5 | import { getMessageMock } from '../../test/mocks'; 6 | 7 | import wiki from './wiki'; 8 | 9 | describe('wiki', () => { 10 | it('should show error message when nothing found on wikipedia', async () => { 11 | nock('https://pl.wikipedia.org/w') 12 | .get(`/api.php?action=opensearch&search=moja%20ulubiona%20piosenka&limit=1&format=json`) 13 | .reply(200, ['moja ulubiona piosenka', [], [], []]); 14 | 15 | const msg = getMessageMock('msg', {}); 16 | 17 | await wiki.execute(msg as unknown as Discord.Message, ['moja', 'ulubiona', 'piosenka']); 18 | 19 | expect(msg.channel.send).to.have.been.calledOnce.and.calledWithMatch('Nic nie znalazłam'); 20 | }); 21 | 22 | it('should show search result when found on wikipedia', async () => { 23 | nock('https://pl.wikipedia.org/w') 24 | .get(`/api.php?action=opensearch&search=moja%20ulubiona%20piosenka&limit=1&format=json`) 25 | .reply(200, [ 26 | 'moja ulubiona piosenka', 27 | ['Moja ulubiona piosenka'], 28 | [], 29 | ['https://pl.wikipedia.org/wiki/Moja_ulubiona_piosenka'], 30 | ]); 31 | 32 | const msg = getMessageMock('msg', {}); 33 | 34 | await wiki.execute(msg as unknown as Discord.Message, ['moja', 'ulubiona', 'piosenka']); 35 | 36 | expect(msg.channel.send).to.have.been.calledOnceWith( 37 | 'Pod hasłem: moja ulubiona piosenka\nZnalazłam artykuł: Moja ulubiona piosenka\nDostępny tutaj: https://pl.wikipedia.org/wiki/Moja_ulubiona_piosenka', 38 | ); 39 | }); 40 | }); 41 | -------------------------------------------------------------------------------- /src/commands/wiki.ts: -------------------------------------------------------------------------------- 1 | import type Discord from 'discord.js'; 2 | import fetch from 'node-fetch'; 3 | 4 | import type { Command } from '../types'; 5 | 6 | const wiki: Command = { 7 | name: 'wiki', 8 | description: 'Zwraca pierwszy wynik wyszukiwania w wikipedii', 9 | args: 'required', 10 | async execute(msg: Discord.Message, args: readonly string[]) { 11 | if (!args.length) { 12 | return msg.channel.send('Nie wiem czego mam szukać 🤔 \n`!wiki `'); 13 | } 14 | const API_URL = 'https://pl.wikipedia.org/w/api.php'; 15 | const params = { 16 | action: 'opensearch', 17 | search: encodeURIComponent(args.join(' ')), 18 | limit: '1', // Limits to first search hit, add as argument in future? 19 | format: 'json', 20 | }; 21 | const query = Object.entries(params) 22 | .map(([key, value]) => `${key}=${value}`) 23 | .join('&'); 24 | const res = await fetch(`${API_URL}?${query}`); 25 | const resp = (await res.json()) as WikipediaResponse; 26 | const [queryString, [articleTitle], [], [link]] = resp; 27 | 28 | if (!articleTitle && !link) { 29 | return msg.channel.send(`Nic nie znalazłam pod hasłem ${queryString}`); 30 | } 31 | const message = `Pod hasłem: ${queryString}\nZnalazłam artykuł: ${articleTitle}\nDostępny tutaj: ${link}`; 32 | 33 | return msg.channel.send(message); 34 | }, 35 | }; 36 | export default wiki; 37 | 38 | type WikipediaResponse = readonly [string, readonly string[], readonly string[], readonly string[]]; 39 | -------------------------------------------------------------------------------- /src/commands/xd.ts: -------------------------------------------------------------------------------- 1 | import type { Command } from '../types'; 2 | 3 | const xd: Command = { 4 | name: 'xd', 5 | description: 'XD', 6 | args: 'prohibited', 7 | cooldown: 60, 8 | execute(msg) { 9 | return msg.channel.send({ 10 | files: [ 11 | { 12 | attachment: 'https://i.imgur.com/vbyc7yL.gif', 13 | }, 14 | ], 15 | }); 16 | }, 17 | }; 18 | 19 | export default xd; 20 | -------------------------------------------------------------------------------- /src/commands/xkcd.ts: -------------------------------------------------------------------------------- 1 | import Fsp from 'fs/promises'; 2 | import Path from 'path'; 3 | 4 | import Natural from 'natural'; 5 | import fetch from 'node-fetch'; 6 | 7 | import type { Command } from '../types'; 8 | 9 | const xkcd: Command = { 10 | name: 'xkcd', 11 | description: 'Wyszukuje video z xkcd', 12 | args: 'required', 13 | async execute(msg, args) { 14 | const parsedArgs = parseXkcdArgs(args); 15 | 16 | if (parsedArgs.type === 'id') { 17 | const res = await fetch(`https://xkcd.com/${parsedArgs.id}/info.0.json`); 18 | if (res.status === 404) { 19 | return msg.channel.send(`Niestety nic nie znalazłam 😭`); 20 | } 21 | return msg.channel.send(`https://xkcd.com/${parsedArgs.id}/`); 22 | } 23 | 24 | const xkcdCache = JSON.parse( 25 | await Fsp.readFile(Path.join(__dirname, 'xkcd.cache.json'), 'utf-8'), 26 | ) as { readonly lastUpdatedAt: string; readonly data: Record }; 27 | 28 | const foundXkcd = Object.entries(xkcdCache.data) 29 | .map(([id, response]) => { 30 | const titleCoeff = Natural.DiceCoefficient(response.safe_title, parsedArgs.query); 31 | if (titleCoeff === 1) { 32 | return [id, Number.MAX_SAFE_INTEGER] as const; 33 | } 34 | 35 | const altCoeff = Natural.DiceCoefficient(response.alt, parsedArgs.query); 36 | const transcriptCoeff = Natural.DiceCoefficient(response.transcript, parsedArgs.query); 37 | // if (['386', '195', '80'].includes(id)) { 38 | // console.log({ 39 | // id, 40 | // titleCoeff, 41 | // altCoeff, 42 | // transcriptCoeff, 43 | // sum: 0.05 * titleCoeff + 0.05 * altCoeff + 0.9 * transcriptCoeff, 44 | // }); 45 | // } 46 | const weightedCoeff = 0.05 * titleCoeff + 0.05 * altCoeff + 0.9 * transcriptCoeff; 47 | return [id, weightedCoeff] as const; 48 | }) 49 | .sort(([, a], [, b]) => b - a)[0]; 50 | 51 | // const result = await fetch(); 52 | // const response = await result.json(); 53 | 54 | if (!foundXkcd) { 55 | return msg.channel.send(`Niestety nic nie znalazłam 😭`); 56 | } 57 | 58 | return msg.channel.send(`https://xkcd.com/${foundXkcd[0]}/`); 59 | }, 60 | }; 61 | 62 | export default xkcd; 63 | 64 | function parseXkcdArgs(args: readonly string[]) { 65 | const trimmedArgs = args.map((el) => el.trim()).filter((el) => el.length > 0); 66 | 67 | if (trimmedArgs.length === 1 && /^\d+$/.test(trimmedArgs[0])) { 68 | return { type: 'id', id: trimmedArgs[0] } as const; 69 | } 70 | 71 | return { type: 'search', query: trimmedArgs.join(' ') } as const; 72 | } 73 | 74 | interface XkcdResponse { 75 | readonly month: string; 76 | readonly num: number; 77 | readonly link: string; 78 | readonly year: string; 79 | readonly news: string; 80 | readonly safe_title: string; 81 | readonly transcript: string; 82 | readonly alt: string; 83 | readonly img: string; 84 | readonly title: string; 85 | readonly day: string; 86 | } 87 | -------------------------------------------------------------------------------- /src/commands/yesno.ts: -------------------------------------------------------------------------------- 1 | import Discord from 'discord.js'; 2 | import fetch from 'node-fetch'; 3 | 4 | import type { Command } from '../types'; 5 | import { capitalizeFirst } from '../utils'; 6 | 7 | const answerToColor = { 8 | yes: '#5ab783', 9 | no: '#e91e63', 10 | maybe: '#eb8921', 11 | } as const; 12 | 13 | const yesno: Command = { 14 | name: 'yesno', 15 | description: 'Podejmie decyzję za ciebie', 16 | args: 'optional', 17 | async execute(msg, [force]) { 18 | const url = ['yes', 'no', 'maybe'].includes(force) 19 | ? `https://yesno.wtf/api?force=${force}` 20 | : 'https://yesno.wtf/api'; 21 | 22 | const res = await fetch(url); 23 | const { answer, image } = (await res.json()) as YesNoApiResponse; 24 | 25 | const answerEmbed = new Discord.EmbedBuilder() 26 | .setTitle(capitalizeFirst(answer)) 27 | .setImage(image) 28 | .setColor(answerToColor[answer]); 29 | 30 | return msg.channel.send({ embeds: [answerEmbed] }); 31 | }, 32 | }; 33 | 34 | export default yesno; 35 | 36 | interface YesNoApiResponse { 37 | readonly answer: 'yes' | 'no' | 'maybe'; 38 | readonly forced: boolean; 39 | readonly image: string; 40 | } 41 | -------------------------------------------------------------------------------- /src/commands/youtube.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import type * as Discord from 'discord.js'; 3 | import nock from 'nock'; 4 | import Sinon from 'sinon'; 5 | 6 | import { getMessageMock } from '../../test/mocks'; 7 | import * as Config from '../config'; 8 | 9 | import youtube from './youtube'; 10 | 11 | describe('youtube', () => { 12 | beforeEach(() => { 13 | void Sinon.stub(Config, 'getConfig').callsFake((name) => { 14 | if (name === 'YOUTUBE_API_KEY') { 15 | return 'FAKE_YOUTUBE_KEY'; 16 | } 17 | throw new Error(`Unexpected config: ${name}`); 18 | }); 19 | }); 20 | 21 | it('should show error message when nothing found on youtube', async () => { 22 | nock('https://www.googleapis.com') 23 | .get( 24 | `/youtube/v3/search?part=id&type=video&key=FAKE_YOUTUBE_KEY&q=moja%20ulubiona%20piosenka`, 25 | ) 26 | .reply(200, { items: [] }); 27 | 28 | const msg = getMessageMock('msg', {}); 29 | 30 | await youtube.execute(msg as unknown as Discord.Message, ['moja', 'ulubiona', 'piosenka']); 31 | 32 | expect(msg.channel.send).to.have.been.calledOnce.and.calledWithMatch('Niestety nic'); 33 | }); 34 | 35 | it('should show link when found on youtube', async () => { 36 | nock('https://www.googleapis.com') 37 | .get( 38 | `/youtube/v3/search?part=id&type=video&key=FAKE_YOUTUBE_KEY&q=moja%20ulubiona%20piosenka`, 39 | ) 40 | .reply(200, { items: [{ id: { videoId: 'aaa123' } }] }); 41 | 42 | const msg = getMessageMock('msg', {}); 43 | 44 | await youtube.execute(msg as unknown as Discord.Message, ['moja', 'ulubiona', 'piosenka']); 45 | 46 | expect(msg.channel.send).to.have.been.calledOnceWith('https://www.youtube.com/watch?v=aaa123'); 47 | }); 48 | }); 49 | -------------------------------------------------------------------------------- /src/commands/youtube.ts: -------------------------------------------------------------------------------- 1 | import fetch from 'node-fetch'; 2 | 3 | import { getConfig } from '../config'; 4 | import type { Command } from '../types'; 5 | 6 | const isErrorResponse = (response: YoutubeResponse): response is YoutubeResponseError => 7 | 'error' in response; 8 | 9 | const youtube: Command = { 10 | name: 'youtube', 11 | description: 'Wyszukuje video z youtube', 12 | args: 'required', 13 | async execute(msg, args) { 14 | const query = encodeURIComponent(args.join(' ')); 15 | const YOUTUBE_API_KEY = getConfig('YOUTUBE_API_KEY'); 16 | const result = await fetch( 17 | `https://www.googleapis.com/youtube/v3/search?part=id&type=video&key=${YOUTUBE_API_KEY}&q=${query}`, 18 | ); 19 | const response = (await result.json()) as YoutubeResponse; 20 | 21 | if (isErrorResponse(response)) { 22 | console.error(response); 23 | return msg.channel.send(`Uh, integracja z API YT nie zadziałała 😭`); 24 | } 25 | 26 | if (!response.items.length) { 27 | return msg.channel.send(`Niestety nic nie znalazłam 😭`); 28 | } 29 | 30 | const [ 31 | { 32 | id: { videoId }, 33 | }, 34 | ] = response.items; 35 | return msg.channel.send(`https://www.youtube.com/watch?v=${videoId}`); 36 | }, 37 | }; 38 | 39 | export default youtube; 40 | 41 | interface YoutubeResponseError { 42 | readonly error: unknown; 43 | } 44 | 45 | interface YoutubeResponseSuccess { 46 | readonly kind: string; 47 | readonly etag: string; 48 | readonly nextPageToken: string; 49 | readonly regionCode: string; 50 | readonly pageInfo: PageInfo; 51 | readonly items: ReadonlyArray; 52 | } 53 | 54 | interface PageInfo { 55 | readonly totalResults: number; 56 | readonly resultsPerPage: number; 57 | } 58 | 59 | interface YoutubeItem { 60 | readonly kind: string; 61 | readonly etag: string; 62 | readonly id: YoutubeItemId; 63 | } 64 | interface YoutubeItemId { 65 | readonly kind: string; 66 | readonly videoId: string; 67 | } 68 | 69 | type YoutubeResponse = YoutubeResponseSuccess | YoutubeResponseError; 70 | -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-unsafe-call */ 2 | /* eslint-disable @typescript-eslint/no-unsafe-member-access */ 3 | require('dotenv').config({ path: '.env' }); 4 | 5 | export function getConfig(name: 'ENV'): 'production' | 'staging' | 'development' | 'test'; 6 | export function getConfig(name: 'NODE_ENV'): 'production' | 'development'; 7 | export function getConfig(name: string): string; 8 | export function getConfig(name: string): string { 9 | const val = process.env[name]; 10 | 11 | switch (name) { 12 | case 'NODE_ENV': 13 | return val || 'development'; 14 | case 'ENV': 15 | return val || 'development'; 16 | case 'PORT': 17 | return val || '3000'; 18 | case 'PREFIX': 19 | return '!'; 20 | } 21 | 22 | if (!val) { 23 | throw new Error(`Cannot find environmental variable: ${name}`); 24 | } 25 | 26 | return val; 27 | } 28 | 29 | export const isProd = () => getConfig('ENV') === 'production'; 30 | -------------------------------------------------------------------------------- /src/cron/roles/index.ts: -------------------------------------------------------------------------------- 1 | import type Discord from 'discord.js'; 2 | 3 | const fetchRole = async (guild: Discord.Guild, roleName: string) => { 4 | const roles = await guild.roles.fetch(undefined, { cache: false }); 5 | return roles.find((role) => role.name === roleName); 6 | }; 7 | 8 | export const fetchOrCreateRole = async ( 9 | guild: Discord.Guild, 10 | roleName: string, 11 | createRole: (guild: Discord.Guild) => Promise, 12 | ) => { 13 | const role = await fetchRole(guild, roleName); 14 | if (!role) { 15 | return createRole(guild); 16 | } 17 | return role; 18 | }; 19 | 20 | const giveRole = (member: Discord.GuildMember, role: Discord.Role) => { 21 | console.debug(`Adding role ${role.name} to member ${member.displayName}!`); 22 | return member.roles.add(role); 23 | }; 24 | 25 | const removeRole = (member: Discord.GuildMember, role: Discord.Role) => { 26 | console.debug(`Removing role ${role.name} from member ${member.displayName}!`); 27 | return member.roles.remove(role.id); 28 | }; 29 | 30 | const assignMembersRoles = (members: readonly Discord.GuildMember[], role: Discord.Role) => { 31 | return Promise.all(members.map((member) => giveRole(member, role))); 32 | }; 33 | 34 | const removeMembersRoles = ( 35 | members: Discord.Collection, 36 | role: Discord.Role, 37 | ) => { 38 | return Promise.all(members.map((member) => removeRole(member, role))); 39 | }; 40 | 41 | export const updateRoles = async ( 42 | role: Discord.Role, 43 | futureRoleMembers: readonly Discord.GuildMember[], 44 | ) => { 45 | const currentRoleMembers = role.members; 46 | 47 | const membersToRemove = currentRoleMembers.filter( 48 | (m) => !futureRoleMembers.find((bm) => bm.id === m.id), 49 | ); 50 | const membersToAdd = futureRoleMembers.filter( 51 | (bm) => !currentRoleMembers.find((m) => m.id === bm.id), 52 | ); 53 | 54 | await removeMembersRoles(membersToRemove, role); 55 | await assignMembersRoles(membersToAdd, role); 56 | }; 57 | -------------------------------------------------------------------------------- /src/cron/roles/karma.ts: -------------------------------------------------------------------------------- 1 | import type Discord from 'discord.js'; 2 | 3 | import { initDb, getKarmaCollection } from '../../db'; 4 | import { offsetDateByWeeks } from '../../utils'; 5 | 6 | import { fetchOrCreateRole, updateRoles } from '.'; 7 | 8 | const TOP_KARMA_ROLE_NAME = '🙏 POMOCNI'; 9 | 10 | interface MemberTotalKarma { 11 | readonly _id: string; 12 | readonly total: number; 13 | } 14 | 15 | const createKarmaRole = (guild: Discord.Guild) => { 16 | return guild.roles.create({ 17 | name: TOP_KARMA_ROLE_NAME, 18 | color: 'Blue', 19 | mentionable: false, 20 | hoist: true, 21 | reason: 'Najbardziej pomocny/a', 22 | }); 23 | }; 24 | 25 | const getBestKarmaMemberIds = async ( 26 | fromDate = offsetDateByWeeks(new Date(), 2), 27 | toDate = new Date(), 28 | ) => { 29 | const db = await initDb(); 30 | const karmaCollection = getKarmaCollection(db); 31 | 32 | const agg = await karmaCollection 33 | .aggregate([ 34 | { $match: { createdAt: { $gte: fromDate, $lte: toDate } } }, 35 | { $group: { _id: '$to', total: { $sum: '$value' } } }, 36 | { $sort: { total: -1 } }, 37 | { $limit: 10 }, 38 | { $match: { total: { $gt: 0 } } }, 39 | ]) 40 | .toArray(); 41 | 42 | return agg; 43 | }; 44 | 45 | const getTopKarmaMembers = async (guild: Discord.Guild) => { 46 | const ids = await getBestKarmaMemberIds(); 47 | 48 | return Promise.all(ids.map(({ _id }) => guild.members.fetch(_id))); 49 | }; 50 | 51 | export const updateKarmaRoles = async (guild: Discord.Guild) => { 52 | const [karmaRole, bestKarmaMembers] = await Promise.all([ 53 | fetchOrCreateRole(guild, TOP_KARMA_ROLE_NAME, createKarmaRole), 54 | getTopKarmaMembers(guild), 55 | ]); 56 | 57 | await updateRoles(karmaRole, bestKarmaMembers); 58 | }; 59 | -------------------------------------------------------------------------------- /src/cron/roles/stats.ts: -------------------------------------------------------------------------------- 1 | import type Discord from 'discord.js'; 2 | 3 | import { initDb, getStatsCollection } from '../../db'; 4 | import { offsetDateByWeeks } from '../../utils'; 5 | 6 | import { fetchOrCreateRole, updateRoles } from '.'; 7 | 8 | const TOP_STATS_ROLE_NAME = `🏎 AKTYWNI`; 9 | 10 | const createStatsRole = (guild: Discord.Guild) => { 11 | return guild.roles.create({ 12 | name: TOP_STATS_ROLE_NAME, 13 | color: 'DarkVividPink', 14 | mentionable: false, 15 | hoist: true, 16 | reason: 'Najbardziej aktywna/y', 17 | }); 18 | }; 19 | 20 | interface MemberTotalStats { 21 | readonly _id: string; 22 | readonly messagesCount: number; 23 | readonly memberName: string; 24 | } 25 | 26 | const getBestStatsMemberIds = async ( 27 | fromDate = offsetDateByWeeks(new Date(), 2), 28 | toDate = new Date(), 29 | ) => { 30 | const db = await initDb(); 31 | const statsCollection = getStatsCollection(db); 32 | 33 | const agg = statsCollection 34 | .aggregate([ 35 | { $match: { updatedAt: { $gte: fromDate, $lte: toDate } } }, 36 | { 37 | $group: { 38 | _id: '$memberId', 39 | messagesCount: { $sum: '$messagesCount' }, 40 | memberName: { $push: '$memberName' }, 41 | }, 42 | }, 43 | { $sort: { messagesCount: -1 } }, 44 | { $limit: 10 }, 45 | { $match: { messagesCount: { $gt: 0 } } }, 46 | { $addFields: { memberName: { $arrayElemAt: [{ $reverseArray: '$memberName' }, 0] } } }, 47 | ]) 48 | .toArray(); 49 | 50 | return agg; 51 | }; 52 | 53 | const getTopStatsMembers = async (guild: Discord.Guild) => { 54 | const ids = await getBestStatsMemberIds(); 55 | 56 | return Promise.all(ids.map(({ _id }) => guild.members.fetch(_id))); 57 | }; 58 | 59 | export const updateStatsRoles = async (guild: Discord.Guild) => { 60 | const [statsRole, bestStatsMembers] = await Promise.all([ 61 | fetchOrCreateRole(guild, TOP_STATS_ROLE_NAME, createStatsRole), 62 | getTopStatsMembers(guild), 63 | ]); 64 | 65 | await updateRoles(statsRole, bestStatsMembers); 66 | }; 67 | -------------------------------------------------------------------------------- /src/data/karma.ts: -------------------------------------------------------------------------------- 1 | import type { Db } from 'mongodb'; 2 | 3 | import { getKarmaCollection } from '../db'; 4 | 5 | export type KarmaAgg = { 6 | readonly _id: string; 7 | readonly from: readonly string[]; 8 | readonly value: number; 9 | }; 10 | 11 | // const RATE_OF_DECAY = 1000 * 60 * 60 * 24 * (365 / 6); // half every two months 12 | 13 | const karmaAggregateGroup = [ 14 | // { 15 | // $project: { 16 | // to: '$to', 17 | // from: '$from', 18 | // value: { 19 | // $multiply: [ 20 | // '$value', 21 | // { $exp: { $divide: [{ $subtract: ['$createdAt', new Date()] }, RATE_OF_DECAY] } }, 22 | // ], 23 | // }, 24 | // }, 25 | // }, 26 | { $group: { _id: '$to', from: { $push: '$from' }, value: { $sum: '$value' } } }, 27 | ] as const; 28 | 29 | export const getKarmaForMember = async (memberId: string, db: Db) => { 30 | const karmaCollection = getKarmaCollection(db); 31 | 32 | const [agg] = await karmaCollection 33 | .aggregate([{ $match: { to: memberId } }, ...karmaAggregateGroup]) 34 | .toArray(); 35 | return agg; 36 | }; 37 | 38 | export const getKarmaForMembers = async (db: Db, memberIds: readonly string[]) => { 39 | const karmaCollection = getKarmaCollection(db); 40 | 41 | const agg = await karmaCollection 42 | .aggregate([{ $match: { to: { $in: memberIds } } }, ...karmaAggregateGroup]) 43 | .sort({ value: -1 }) 44 | .limit(10) 45 | .toArray(); 46 | return agg; 47 | }; 48 | 49 | export const getKarmaForAllMembers = async (db: Db) => { 50 | const karmaCollection = getKarmaCollection(db); 51 | 52 | const agg = await karmaCollection 53 | .aggregate([...karmaAggregateGroup]) 54 | .sort({ value: -1 }) 55 | .limit(10) 56 | .toArray(); 57 | return agg; 58 | }; 59 | 60 | export const getKarmaLevel = (value: number) => Math.floor(Math.log(value + 1)); 61 | 62 | export const getEmojiForKarmaValue = (value: number) => { 63 | const level = getKarmaLevel(value); 64 | const idx = Math.min(karmaEmojis.length - 1, level); 65 | return karmaEmojis[idx]; 66 | }; 67 | 68 | export const getKarmaDescription = (value: number) => 69 | `${Math.floor(value)} XP (lvl ${getKarmaLevel(value)}) ${getEmojiForKarmaValue(value)}`; 70 | 71 | const karmaEmojis = [ 72 | '👋', 73 | '👍', 74 | '👌', 75 | '💪', 76 | '🎖', 77 | '🥉', 78 | '🥈', 79 | '🥇', 80 | '🏅', 81 | '🙌', 82 | '🥰', 83 | '😍', 84 | ] as const; 85 | -------------------------------------------------------------------------------- /src/db.ts: -------------------------------------------------------------------------------- 1 | import type { Db } from 'mongodb'; 2 | import { MongoClient } from 'mongodb'; 3 | 4 | import { getConfig } from './config'; 5 | 6 | export const initDb = (() => { 7 | let mongoClient: MongoClient | undefined = undefined; 8 | 9 | return async () => { 10 | const mongoUrl = getConfig('MONGO_URL'); 11 | const dbName = mongoUrl.split('/').pop(); 12 | if (!mongoClient) { 13 | const m = new MongoClient(mongoUrl, { keepAlive: true }); 14 | mongoClient = await m.connect(); 15 | } 16 | 17 | const db = mongoClient.db(dbName); 18 | return db; 19 | }; 20 | })(); 21 | 22 | export type StatsCollection = { 23 | readonly memberId: string; 24 | readonly memberName: string; 25 | readonly messagesCount: number | undefined | null; 26 | readonly updatedAt: Date; 27 | readonly yearWeek?: string | null; 28 | }; 29 | 30 | export const getStatsCollection = (db: Db) => { 31 | return db.collection('stats'); 32 | }; 33 | 34 | export type KarmaCollection = { 35 | readonly from: string; 36 | readonly to: string; 37 | readonly value: number; 38 | readonly description?: string | null; 39 | readonly createdAt: Date; 40 | }; 41 | 42 | export const getKarmaCollection = (db: Db) => { 43 | return db.collection('karma'); 44 | }; 45 | -------------------------------------------------------------------------------- /src/handle-github-webhook.spec.ts: -------------------------------------------------------------------------------- 1 | import * as crypto from 'crypto'; 2 | import type Http from 'http'; 3 | import type { AddressInfo } from 'net'; 4 | 5 | import { expect } from 'chai'; 6 | import type Discord from 'discord.js'; 7 | import nock from 'nock'; 8 | import fetch from 'node-fetch'; 9 | import Sinon from 'sinon'; 10 | 11 | import * as Config from './config'; 12 | import { handleGithubWebhook } from './handle-github-webhook'; 13 | import * as handleGithubWebhookModule from './handle-github-webhook'; 14 | import { createHttpServer } from './http-server'; 15 | 16 | const GITHUB_WEBHOOK_SECRET = 's3creTk3Y'; 17 | const GITHUB_WEBHOOK_DISCORD_URL = 'https://discord.com/api/webhooks/12345/key'; 18 | 19 | describe('handleGithubWebhook - unit tests', () => { 20 | beforeEach(() => { 21 | const getConfigStub = Sinon.stub(Config, 'getConfig'); 22 | getConfigStub.withArgs('GITHUB_WEBHOOK_SECRET').returns(GITHUB_WEBHOOK_SECRET); 23 | getConfigStub.withArgs('GITHUB_WEBHOOK_DISCORD_URL').returns(GITHUB_WEBHOOK_DISCORD_URL); 24 | }); 25 | 26 | afterEach(() => { 27 | Sinon.restore(); 28 | }); 29 | 30 | it('should return 401 if webhook signature is invalid', async () => { 31 | const result = await handleGithubWebhook({}, Buffer.from(''), {}); 32 | 33 | expect(result).to.eql({ statusCode: 401 }); 34 | }); 35 | 36 | it('should return 200 if webhook was filtered out', async () => { 37 | const result = await handleGithubWebhook( 38 | ...makeHandleGithubWebhookParams({ 39 | sender: { 40 | login: 'dependabot[bot]', 41 | }, 42 | }), 43 | ); 44 | 45 | expect(result).to.eql({ statusCode: 200 }); 46 | }); 47 | 48 | it('should return status code from discord if the webhook was forwarded', async () => { 49 | const payload = { sender: { login: 'kbkk' } }; 50 | 51 | nock('https://discord.com').post('/api/webhooks/12345/key', payload).reply(599); 52 | 53 | const result = await handleGithubWebhook(...makeHandleGithubWebhookParams(payload)); 54 | 55 | expect(result).to.eql({ statusCode: 599 }); 56 | }); 57 | }); 58 | 59 | describe('handleGithubWebhook - integration tests', () => { 60 | let httpServer: Http.Server; 61 | let baseUrl: string; 62 | 63 | beforeEach(async () => { 64 | nock.cleanAll(); 65 | nock.enableNetConnect(); 66 | 67 | const discordClientMock = { 68 | uptime: 10, 69 | } as Discord.Client; 70 | 71 | httpServer = createHttpServer(discordClientMock, [], [], []); 72 | await new Promise((resolve) => httpServer.listen(0, resolve)); 73 | 74 | baseUrl = `http://localhost:${(httpServer.address() as AddressInfo).port}`; 75 | }); 76 | 77 | afterEach(() => { 78 | httpServer.close(); 79 | Sinon.restore(); 80 | }); 81 | 82 | it('should respond with 400 on invalid request', async () => { 83 | const jsonParseSpy = Sinon.spy(JSON, 'parse'); 84 | 85 | const { status } = await fetch(`${baseUrl}/githubWebhook`, { 86 | method: 'POST', 87 | body: 'invalid json', 88 | }); 89 | 90 | expect(jsonParseSpy).to.throw(); 91 | expect(status).to.eql(400); 92 | }); 93 | 94 | it('should call handleGithubWebhook with headers, rawBody and body', async () => { 95 | const handleGithubWebhookStub = Sinon.stub(handleGithubWebhookModule, 'handleGithubWebhook'); 96 | handleGithubWebhookStub.resolves({ statusCode: 200 }); 97 | 98 | await fetch(`${baseUrl}/githubWebhook`, { 99 | method: 'POST', 100 | body: '{"a":1}', 101 | headers: { 102 | 'x-hub-signature': 'test-signature', 103 | }, 104 | }); 105 | 106 | expect(handleGithubWebhookStub).to.have.been.calledOnceWithExactly( 107 | Sinon.match({ 'x-hub-signature': 'test-signature' }), 108 | Buffer.from('{"a":1}'), 109 | { a: 1 }, 110 | ); 111 | }); 112 | 113 | it('should respond with status code from handleGithubWebhook', async () => { 114 | const handleGithubWebhookStub = Sinon.stub(handleGithubWebhookModule, 'handleGithubWebhook'); 115 | handleGithubWebhookStub.resolves({ statusCode: 599 }); 116 | 117 | const { status } = await fetch(`${baseUrl}/githubWebhook/test`, { 118 | method: 'POST', 119 | body: '{"a":1}', 120 | }); 121 | 122 | expect(status).eql(599); 123 | }); 124 | }); 125 | 126 | function forgeSignature(rawBody: Buffer): string { 127 | const hmacString = crypto.createHmac('sha1', GITHUB_WEBHOOK_SECRET).update(rawBody).digest('hex'); 128 | const signature = `sha1=${hmacString}`; 129 | 130 | return signature; 131 | } 132 | 133 | function makeHandleGithubWebhookParams(body: object): Parameters { 134 | const rawBody = Buffer.from(JSON.stringify(body)); 135 | const signature = forgeSignature(rawBody); 136 | 137 | return [ 138 | { 139 | 'x-hub-signature': signature, 140 | }, 141 | rawBody, 142 | body, 143 | ]; 144 | } 145 | -------------------------------------------------------------------------------- /src/handle-github-webhook.ts: -------------------------------------------------------------------------------- 1 | import * as crypto from 'crypto'; 2 | import type { IncomingHttpHeaders } from 'http'; 3 | 4 | import fetch from 'node-fetch'; 5 | 6 | import { getConfig } from './config'; 7 | 8 | const SENDER_LOGIN_BLOCKLIST = ['dependabot[bot]', 'dependabot-preview[bot]', 'sonarcloud[bot]']; 9 | 10 | // see https://developer.github.com/webhooks/event-payloads/ for full github webhooks reference 11 | 12 | interface GithubWebhookSender { 13 | readonly login: string; 14 | } 15 | 16 | interface GithubWebhookPullRequest { 17 | readonly sender: GithubWebhookSender; 18 | } 19 | 20 | export async function handleGithubWebhook( 21 | headers: IncomingHttpHeaders, 22 | rawBody: Buffer, 23 | body: object, 24 | ): Promise<{ readonly statusCode: number }> { 25 | if (!validateGithubSignature((headers['x-hub-signature'] ?? '') as string, rawBody)) { 26 | return { statusCode: 401 }; 27 | } 28 | 29 | if (!shouldSendWebhook(body)) { 30 | return { statusCode: 200 }; 31 | } 32 | 33 | const discordWebhookUrl = getConfig('GITHUB_WEBHOOK_DISCORD_URL'); 34 | 35 | const newHeaders = { 36 | // 'x-real-ip': headers['x-real-ip'], 37 | // 'x-forwarded-for': headers['x-forwarded-for'], 38 | // host: headers.host, 39 | // 'x-forwarded-proto': headers['x-forwarded-proto'], 40 | // connection: headers.connection, 41 | // 'content-length': headers['content-length'], 42 | // 'x-nginx-ssl': headers['x-nginx-ssl'], 43 | // 'user-agent': headers['user-agent'], 44 | // accept: headers.accept, 45 | 'x-github-delivery': headers['x-github-delivery'], 46 | 'x-github-event': headers['x-github-event'], 47 | 'x-hub-signature': headers['x-hub-signature'], 48 | 'content-type': headers['content-type'], 49 | // 'x-forwarded-https': headers['x-forwarded-https'], 50 | } as Record; 51 | 52 | const res = await fetch(discordWebhookUrl, { 53 | method: 'POST', 54 | body: rawBody, 55 | headers: newHeaders, 56 | }); 57 | 58 | return { statusCode: res.status }; 59 | } 60 | 61 | function shouldSendWebhook(body: object | GithubWebhookPullRequest) { 62 | if ('sender' in body && SENDER_LOGIN_BLOCKLIST.includes(body.sender?.login)) { 63 | return false; 64 | } 65 | 66 | return true; 67 | } 68 | 69 | function validateGithubSignature(receivedSignature: string, rawBody: Buffer) { 70 | const githubSecret = getConfig('GITHUB_WEBHOOK_SECRET'); 71 | const hmacString = crypto.createHmac('sha1', githubSecret).update(rawBody).digest('hex'); 72 | const expectedSignature = `sha1=${hmacString}`; 73 | 74 | return ( 75 | receivedSignature.length === expectedSignature.length && 76 | crypto.timingSafeEqual(Buffer.from(receivedSignature), Buffer.from(expectedSignature)) 77 | ); 78 | } 79 | -------------------------------------------------------------------------------- /src/http-server.ts: -------------------------------------------------------------------------------- 1 | import Http from 'http'; 2 | 3 | import type { Client } from 'discord.js'; 4 | import JsonParse from 'secure-json-parse'; 5 | 6 | import { handleGithubWebhook } from './handle-github-webhook'; 7 | 8 | const BAD_REQUEST = 400; 9 | const OK = 200; 10 | 11 | async function parseBody( 12 | req: Http.IncomingMessage, 13 | ): Promise<{ readonly rawBody: Buffer; readonly body: T }> { 14 | const chunks = []; 15 | // eslint-disable-next-line functional/no-loop-statement 16 | for await (const chunk of req) { 17 | chunks.push(chunk); 18 | } 19 | const rawBody = Buffer.concat(chunks); 20 | const body = JsonParse.parse(rawBody.toString()) as T; 21 | return { rawBody, body }; 22 | } 23 | 24 | export function createHttpServer( 25 | discordClient: Client, 26 | // eslint-disable-next-line functional/prefer-readonly-type 27 | errors: (string | Error)[], 28 | // eslint-disable-next-line functional/prefer-readonly-type 29 | warnings: string[], 30 | // eslint-disable-next-line functional/prefer-readonly-type 31 | debugs: string[], 32 | ): Http.Server { 33 | // eslint-disable-next-line @typescript-eslint/no-misused-promises 34 | return Http.createServer(async (req, res) => { 35 | if (req.url?.startsWith('/githubWebhook')) { 36 | try { 37 | const { headers } = req; 38 | const { rawBody, body } = await parseBody(req); 39 | 40 | const { statusCode } = await handleGithubWebhook(headers, rawBody, body); 41 | 42 | res.statusCode = statusCode; 43 | res.end(); 44 | } catch (error) { 45 | errors.push(String(error)); 46 | res.statusCode = BAD_REQUEST; 47 | res.end(); 48 | } 49 | 50 | return; 51 | } 52 | 53 | res.statusCode = OK; 54 | res.setHeader('Content-Type', 'application/json'); 55 | res.end(JSON.stringify({ uptime: discordClient.uptime, errors, warnings, debugs })); 56 | }); 57 | } 58 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | require('./app'); 2 | -------------------------------------------------------------------------------- /src/thx.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import type * as Discord from 'discord.js'; 3 | 4 | import { getMessageMock } from '../test/mocks'; 5 | 6 | import { thx } from './thx'; 7 | 8 | describe('thx', () => { 9 | let id = 0; 10 | const msgReply = 11 | 'protip: napisz `@nazwa ++`, żeby komuś podziękować! Możesz podziękować kilku osobom w jednej wiadomości!'; 12 | 13 | it('it should ignore random messages', async () => { 14 | const msg = getMessageMock('msg', { content: 'msg', channel: { id: ++id } }); 15 | msg.reply.resolves(); 16 | 17 | await thx(msg as unknown as Discord.Message); 18 | 19 | expect(msg.reply).not.to.have.been.calledOnceWith(msgReply); 20 | }); 21 | 22 | [ 23 | 'thx', 24 | 'thank', 25 | 'thanks', 26 | 'dzieki', 27 | 'dzięki', 28 | 'dziekuje', 29 | 'dziekuję', 30 | 'dziękuje', 31 | 'dziękuję', 32 | ].forEach((text) => 33 | it(`it should respond to ${text}`, async () => { 34 | const msg = getMessageMock('msg', { content: text, channel: { id: ++id } }); 35 | msg.reply.resolves(); 36 | 37 | await thx(msg as unknown as Discord.Message); 38 | 39 | expect(msg.reply).to.have.been.calledOnceWith(msgReply); 40 | }), 41 | ); 42 | 43 | [ 44 | 'dzięki temu', 45 | 'dzięki Tobie', 46 | 'dzięki tobie', 47 | 'dzięki niemu', 48 | 'dzięki Niemu', 49 | 'dzięki Niej', 50 | 'dzięki niej', 51 | ].forEach((text) => 52 | it(`it should ignore exception: ${text}`, async () => { 53 | const msg = getMessageMock('msg', { content: text, channel: { id: ++id } }); 54 | msg.reply.resolves(); 55 | await thx(msg as unknown as Discord.Message); 56 | 57 | expect(msg.reply).not.to.have.been.calledOnceWith(msgReply); 58 | }), 59 | ); 60 | }); 61 | -------------------------------------------------------------------------------- /src/thx.ts: -------------------------------------------------------------------------------- 1 | import type Discord from 'discord.js'; 2 | import Cache from 'node-cache'; 3 | 4 | const THX_TIMEOUT_S = 15 * 60; 5 | const thxTimeoutCache = new Cache({ stdTTL: THX_TIMEOUT_S }); 6 | 7 | export const thx = (msg: Discord.Message) => { 8 | if ( 9 | !/(thx|thank|thanks|dzi[e|ę]ki|dzi[e|ę]kuj[e|ę])($|(\s+(?!temu|niej|niemu|tobie|nim)+.*))/i.test( 10 | msg.content, 11 | ) 12 | ) { 13 | return; 14 | } 15 | 16 | if ( 17 | (thxTimeoutCache.get(msg.channel.id)?.getTime() ?? 0) > 18 | Date.now() - THX_TIMEOUT_S * 1000 19 | ) { 20 | return; 21 | } 22 | 23 | thxTimeoutCache.set(msg.channel.id, new Date()); 24 | return msg.reply( 25 | 'protip: napisz `@nazwa ++`, żeby komuś podziękować! Możesz podziękować kilku osobom w jednej wiadomości!', 26 | ); 27 | }; 28 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import type Discord from 'discord.js'; 2 | 3 | interface CommandCommon { 4 | readonly name: string; 5 | readonly description: string; 6 | readonly guildOnly?: boolean; 7 | readonly permissions?: Discord.PermissionResolvable; 8 | readonly cooldown?: number; 9 | } 10 | 11 | export type CommandWithArgs = { 12 | readonly args: 'required' | 'optional'; 13 | execute( 14 | msg: Discord.Message, 15 | args: readonly string[], 16 | ): Promise; 17 | } & CommandCommon; 18 | 19 | type CommandWithoutArgs = { 20 | readonly args: 'prohibited'; 21 | execute(msg: Discord.Message): Promise; 22 | } & CommandCommon; 23 | 24 | export type Command = CommandWithArgs | CommandWithoutArgs; 25 | 26 | export class InvalidUsageError extends Error {} 27 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | export function randomizeArray(arr: readonly T[]) { 2 | return [...arr].sort(() => Math.random() - 0.5); 3 | } 4 | 5 | export function capitalizeFirst(str: T): Capitalize { 6 | return (str.charAt(0).toUpperCase() + str.slice(1)) as Capitalize; 7 | } 8 | 9 | export const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); 10 | 11 | export function getWeekNumber(d: Date): readonly [year: number, week: number] { 12 | const date = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate())); 13 | 14 | // Set to nearest Thursday: current date + 4 - current day number 15 | // Make Sunday's day number 7 16 | date.setUTCDate(date.getUTCDate() + 4 - (date.getUTCDay() || 7)); 17 | // Get first day of year 18 | const yearStart = new Date(Date.UTC(date.getUTCFullYear(), 0, 1)); 19 | // Calculate full weeks to nearest Thursday 20 | const weekNo = Math.ceil(((Number(date) - Number(yearStart)) / 86400000 + 1) / 7); 21 | 22 | return [date.getUTCFullYear(), weekNo]; 23 | } 24 | 25 | export function getDateForWeekNumber(year: number, weekNo: number): Date { 26 | const yearStart = new Date(year, 0, 1); 27 | return new Date((weekNo * 7 - 1) * 86400000 + Number(yearStart)); 28 | } 29 | 30 | // Offset date by n weeks: e.g offsetDateByWeek(new Date(), 2) will return current date minus two weeks 31 | export const offsetDateByWeeks = (d: Date, weeks: number): Date => { 32 | const offsetDate = new Date(d); 33 | const daysCount = weeks * 7; 34 | offsetDate.setDate(offsetDate.getDate() - daysCount); 35 | 36 | return offsetDate; 37 | }; 38 | 39 | export const wrapErr = (err: unknown): Error => { 40 | if (err instanceof Error) { 41 | return err; 42 | } 43 | return new Error(String(err)); 44 | }; 45 | -------------------------------------------------------------------------------- /ssh-script-deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | source ~/.bash_profile 3 | set -e 4 | 5 | node -v 6 | npm -v 7 | yarn -v 8 | 9 | 10 | cd ~/domains/bot.typeofweb.com/public_nodejs 11 | echo "👉 Pulling from the server…" 12 | git fetch origin 13 | 14 | if git diff --quiet remotes/origin/main; then 15 | echo "👉 Up to date; nothing to do!" 16 | exit 17 | fi 18 | 19 | git pull origin main 20 | 21 | echo "👉 Installing deps…" 22 | yarn --frozen-lockfile 23 | 24 | echo "👉 Bulding…" 25 | NODE_ENV=production ENV=production yarn build 26 | echo `git rev-parse HEAD` > .version 27 | 28 | # echo "👉 Pruning…" 29 | # npm prune 30 | 31 | echo "👉 Restarting the server…" 32 | pm2 restart bot 33 | 34 | echo "👉 Done! 😱 👍" 35 | -------------------------------------------------------------------------------- /test/before-each.spec.ts: -------------------------------------------------------------------------------- 1 | import nock from 'nock'; 2 | import Chai, { expect } from 'chai'; 3 | 4 | import SinonChai from 'sinon-chai'; 5 | import ChaiAsPromised from 'chai-as-promised'; 6 | import Sinon from 'sinon'; 7 | 8 | Chai.use(SinonChai); 9 | Chai.use(ChaiAsPromised); 10 | 11 | beforeEach(() => { 12 | nock.disableNetConnect(); 13 | }); 14 | 15 | afterEach(() => { 16 | if (!nock.isDone()) { 17 | console.error(nock.pendingMocks()); 18 | } 19 | 20 | expect(nock.isDone()).to.equal(true); 21 | nock.cleanAll(); 22 | nock.enableNetConnect(); 23 | 24 | Sinon.restore(); 25 | }); 26 | -------------------------------------------------------------------------------- /test/mocks.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import Discord from 'discord.js'; 3 | 4 | import { getMemberMock } from './mocks'; 5 | 6 | describe('mocks', () => { 7 | it('should return correct user mention and id', () => { 8 | const { id, mention } = getMemberMock(); 9 | 10 | const isMemberMentionCorrect = Discord.MessageMentions.UsersPattern.test(mention); 11 | 12 | expect(isMemberMentionCorrect).to.be.true; 13 | expect(mention).to.have.include(id); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /test/mocks.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-unsafe-assignment */ 2 | /* eslint no-magic-numbers: "off" */ 3 | 4 | import type { Message } from 'discord.js'; 5 | import Sinon from 'sinon'; 6 | 7 | const proxyExistenceMutating = (obj: T, prefix = ''): T => { 8 | // eslint-disable-next-line functional/no-loop-statement 9 | for (const key in obj) { 10 | if (!obj.hasOwnProperty(key)) { 11 | continue; 12 | } 13 | 14 | const val = obj[key] as unknown; 15 | if (typeof val === 'object' && val) { 16 | // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment 17 | obj[key] = proxyExistenceMutating(val, prefix ? prefix + '.' + key : key) as any; 18 | } 19 | } 20 | return new Proxy(obj, { 21 | get(o: any, prop: string) { 22 | if (prop in o) { 23 | // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access 24 | return o[prop]; 25 | } 26 | 27 | const err = new Error( 28 | `The following property is missing in your mock: ${ 29 | prefix ? prefix + '.' + String(prop) : String(prop) 30 | }`, 31 | ); 32 | console.error(err); 33 | throw err; 34 | }, 35 | }); 36 | }; 37 | 38 | export const getMessageMock = ( 39 | name: string, 40 | // @ts-ignore 41 | params: P = {}, 42 | ) => { 43 | const mockMessage = { 44 | ...(params as {}), 45 | channel: { 46 | bulkDelete: Sinon.stub(), 47 | send: Sinon.stub(), 48 | messages: { fetch: Sinon.stub() }, 49 | type: '', 50 | [Symbol.toStringTag]: () => 'MOCK CHANNEL', 51 | ...(params.channel as {}), 52 | }, 53 | guild: { 54 | members: { 55 | cache: { get: Sinon.stub() }, 56 | }, 57 | ...(params.guild as {}), 58 | }, 59 | delete: Sinon.stub(), 60 | author: { 61 | id: '123', 62 | send: Sinon.stub(), 63 | ...(params.author as {}), 64 | }, 65 | reply: Sinon.stub(), 66 | } as const; 67 | return proxyExistenceMutating(mockMessage, name) as typeof mockMessage & P; 68 | }; 69 | 70 | export const getMemberMock = () => { 71 | const id = (Math.random() * 1e18).toFixed(); 72 | 73 | const mention = `<@${id}>`; 74 | 75 | return { id, mention }; 76 | }; 77 | -------------------------------------------------------------------------------- /test/setup-env.js: -------------------------------------------------------------------------------- 1 | require('ts-node').register({ 2 | project: './tsconfig.json', 3 | transpileOnly: true, 4 | }); 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowSyntheticDefaultImports": true, 4 | "baseUrl": ".", 5 | "emitDecoratorMetadata": true, 6 | "esModuleInterop": true, 7 | "experimentalDecorators": true, 8 | "lib": ["es2021"], 9 | "module": "commonjs", 10 | "noFallthroughCasesInSwitch": true, 11 | "noImplicitReturns": true, 12 | "noUnusedLocals": true, 13 | "noUnusedParameters": true, 14 | "outDir": "dist", 15 | "resolveJsonModule": true, 16 | "rootDir": ".", 17 | "skipLibCheck": true, 18 | "sourceMap": true, 19 | "strict": true, 20 | "target": "es2019", 21 | "typeRoots": ["./node_modules/@types", "./typings"] 22 | }, 23 | "exclude": ["dist"] 24 | } 25 | -------------------------------------------------------------------------------- /typings/dom.d.ts: -------------------------------------------------------------------------------- 1 | declare namespace Intl { 2 | interface ListFormatOptions { 3 | style: 'long' | 'short'; 4 | type: 'conjunction' | 'disjunction'; 5 | } 6 | 7 | class ListFormat { 8 | constructor(locales?: string | string[], options?: Intl.ListFormatOptions); 9 | public format(items: string[]): string; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /typings/monitorss/index.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'monitorss' { 2 | import EventEmitter from 'events'; 3 | import Discord from 'discord.js'; 4 | 5 | interface Log { 6 | dates?: boolean; 7 | linkErrs?: boolean; 8 | unfiltered?: boolean; 9 | failedFeeds?: boolean; 10 | } 11 | 12 | interface CommandAliases {} 13 | 14 | interface Bot { 15 | token?: string; 16 | enableCommands?: boolean; 17 | prefix?: string; 18 | status?: string; 19 | activityType?: string; 20 | activityName?: string; 21 | streamActivityURL?: string; 22 | controllerIds?: string[]; 23 | menuColor?: number; 24 | deleteMenus?: boolean; 25 | exitOnSocketIssues?: boolean; 26 | commandAliases?: CommandAliases; 27 | } 28 | 29 | interface Connection { 30 | useNewUrlParser?: boolean; 31 | } 32 | 33 | interface Database { 34 | uri: string; 35 | connection?: Connection; 36 | clean?: boolean; 37 | articlesExpire?: number; 38 | guildBackupsExpire?: number; 39 | } 40 | 41 | interface Decode {} 42 | 43 | interface Feeds { 44 | refreshRateMinutes?: number; 45 | checkTitles?: boolean; 46 | timezone?: string; 47 | dateFormat?: string; 48 | dateLanguage?: string; 49 | dateLanguageList?: string[]; 50 | dateFallback?: boolean; 51 | timeFallback?: boolean; 52 | failLimit?: number; 53 | notifyFail?: boolean; 54 | sendFirstCycle?: boolean; 55 | cycleMaxAge?: number; 56 | defaultMessage?: string; 57 | imgPreviews?: boolean; 58 | imgLinksExistence?: boolean; 59 | checkDates?: boolean; 60 | formatTables?: boolean; 61 | toggleRoleMentions?: boolean; 62 | decode?: Decode; 63 | } 64 | 65 | interface Advanced { 66 | shards?: number; 67 | batchSize?: number; 68 | processorMethod?: string; 69 | parallel?: number; 70 | } 71 | 72 | enum LogLevel { 73 | error = 'error', 74 | success = 'success', 75 | warning = 'warning', 76 | info = 'info', 77 | } 78 | 79 | export interface ClientConfig { 80 | log?: Log; 81 | bot?: Bot; 82 | database: Database; 83 | feeds?: Feeds; 84 | advanced?: Advanced; 85 | suppressLogLevels?: Array; 86 | } 87 | 88 | interface CustomSchedule { 89 | name?: string; 90 | refreshTimeMinutes?: number; 91 | keywords?: string[]; 92 | } 93 | 94 | export type CustomSchedules = Array; 95 | 96 | class ClientManager extends EventEmitter { 97 | constructor( 98 | config: { setPresence: boolean; config: ClientConfig }, 99 | customSchedules?: CustomSchedules, 100 | ); 101 | 102 | login(token: string | Discord.Client | Discord.ShardingManager, noChildren?: boolean): void; 103 | 104 | _defineBot(client: Discord.Client): void; 105 | 106 | listenToShardedEvents(bot: Discord.Client); 107 | 108 | stop(); 109 | 110 | start(callback?: () => any); 111 | 112 | restart(callback?: () => any); 113 | 114 | disableCommands(); 115 | } 116 | 117 | export default { 118 | ClientManager, 119 | }; 120 | } 121 | -------------------------------------------------------------------------------- /xkcd.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | const Bluebird = require('bluebird'); 3 | const Fsp = require('fs/promises'); 4 | const fetch = require('node-fetch').default; 5 | 6 | const run = async () => { 7 | let i = 1; 8 | const result = await Bluebird.map( 9 | Array.from({ length: 2579 }, (_, idx) => idx + 1), 10 | async (idx) => { 11 | try { 12 | const res = await fetch(`https://xkcd.com/${idx}/info.0.json`); 13 | const json = await res.json(); 14 | console.log(`${i++} / 2579`); 15 | return [idx, json]; 16 | } catch (err) { 17 | console.error(err); 18 | return []; 19 | } 20 | }, 21 | { concurrency: 20 }, 22 | ); 23 | 24 | const result2 = result.reduce((acc, [idx, json]) => { 25 | if (!json) { 26 | return acc; 27 | } 28 | acc[idx] = json; 29 | return acc; 30 | }, {}); 31 | 32 | const result3 = { 33 | lastUpdatedAt: new Date().toISOString(), 34 | data: result2, 35 | }; 36 | 37 | await Fsp.writeFile( 38 | `${__dirname}/src/commands/xkcd.cache.json`, 39 | JSON.stringify(result3), 40 | 'utf-8', 41 | ); 42 | await Fsp.writeFile( 43 | `${__dirname}/dist/src/commands/xkcd.cache.json`, 44 | JSON.stringify(result3), 45 | 'utf-8', 46 | ); 47 | }; 48 | 49 | run(); 50 | --------------------------------------------------------------------------------