├── .eslintignore ├── .eslintrc ├── .gitattributes ├── .gitignore ├── .prettierignore ├── .prettierrc ├── .travis.yml ├── LICENSE ├── README.md ├── bin └── cli.js ├── docs ├── discord-bot-credentials.md ├── discord-getting-user-ids.md └── installing-ffmpeg-on-windows.md ├── package.json ├── src ├── commands │ ├── Command.js │ ├── Command.test.js │ └── util │ │ ├── help.js │ │ ├── join.js │ │ ├── leave.js │ │ ├── setAvatar.js │ │ └── setUsername.js ├── constants.js ├── defaults │ ├── commands.js │ ├── messages.js │ ├── permissions.js │ └── preferences.js ├── index.js ├── index.test.js ├── util.js └── util.test.js └── yarn.lock /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | coverage 4 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["airbnb-base", "prettier"], 3 | "env": { 4 | "node": true 5 | }, 6 | "plugins": ["jest", "prettier"], 7 | "rules": { 8 | "prettier/prettier": "warn", 9 | 10 | "jest/no-disabled-tests": "warn", 11 | "jest/no-focused-tests": "error", 12 | "jest/no-identical-title": "error", 13 | "jest/valid-expect": "error", 14 | 15 | "arrow-parens": "off" 16 | }, 17 | "overrides": [ 18 | { 19 | "files": ["**/*.test.js"], 20 | "env": { 21 | "jest": true 22 | } 23 | } 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Common .gitattributes file courtesy of 2 | # https://github.com/alexkaratarakis/gitattributes/blob/master/Common.gitattributes 3 | 4 | # Auto detect text files and perform LF normalization 5 | * text=auto eol=lf 6 | 7 | # The above will handle all files NOT found below 8 | 9 | # Documents 10 | *.pdf diff=astextplain 11 | *.PDF diff=astextplain 12 | *.rtf diff=astextplain 13 | *.RTF diff=astextplain 14 | *.md text 15 | 16 | # Graphics 17 | *.png binary 18 | *.jpg binary 19 | *.jpeg binary 20 | *.gif binary 21 | *.tif binary 22 | *.tiff binary 23 | *.ico binary 24 | # SVG treated as an asset (binary) by default. 25 | *.svg binary 26 | #*.svg text 27 | *.eps binary 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # dependencies 2 | node_modules 3 | 4 | # generated folders 5 | coverage 6 | 7 | # all log files 8 | *.log* 9 | 10 | # ignore editor generated files 11 | .vscode 12 | .idea 13 | 14 | # OS generated files 15 | **/.DS_Store 16 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | coverage 4 | *.json 5 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all", 4 | "printWidth": 120 5 | } 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | node_js: 4 | - "10" 5 | 6 | script: 7 | - yarn lint 8 | - yarn test --coverage && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js 9 | 10 | notifications: 11 | email: 12 | on_success: change 13 | on_failure: always 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Discord Music Bot 2 | 3 | 🎧 A music bot for Discord servers, self-hosted, easy to use and extendable. 4 | 5 | 6 | [![npm](https://img.shields.io/npm/v/@south-paw/discord-music-bot.svg)](https://www.npmjs.com/package/@south-paw/discord-music-bot) 7 | [![CI Status](https://img.shields.io/travis/South-Paw/discord-music-bot.svg)](https://travis-ci.org/South-Paw/discord-music-bot) 8 | [![Coveralls Status](https://img.shields.io/coveralls/github/South-Paw/discord-music-bot.svg)](https://coveralls.io/github/South-Paw/discord-music-bot) 9 | [![Dependencies](https://david-dm.org/South-Paw/discord-music-bot.svg)](https://david-dm.org/South-Paw/discord-music-bot) 10 | [![Dev Dependencies](https://david-dm.org/South-Paw/discord-music-bot/dev-status.svg)](https://david-dm.org/South-Paw/discord-music-bot?type=dev) 11 | 12 | --- 13 | 14 | ## 🐉 HERE BE DRAGONS 15 | 16 | **This bot is still a work-in-progress and will contain bugs!** 17 | 18 | If you manage to find any, please report them [here](https://github.com/South-Paw/discord-music-bot/issues) so they can be squashed. 19 | 20 | ## Features 21 | 22 | * Yes. 23 | 24 | ## 🤖 How do I use this? 25 | 26 | **You must first have...** 27 | 28 | * A `discord token`, `server id` and `text channel id` for your bot, [read this if you don't have those](https://github.com/South-Paw/discord-music-bot/blob/master/docs/discord-getting-user-ids.md) 29 | * The IDs of the users you wish to give admin permissions on the bot to, [read this if you don't have that](https://github.com/South-Paw/discord-music-bot/blob/master/docs/discord-bot-credentials.md) 30 | * A computer that has working internet 31 | * The ability to follow instructions 32 | * Some common sense 33 | 34 | And I thought this note would be covered under common sense but: 35 | 36 | ``` 37 | ⚠️ --------------------------------- ⚠️ 38 | | DO NOT COMMIT OR POST YOUR TOKEN | 39 | ⚠️ --------------------------------- ⚠️ 40 | 41 | and if you go do that or already have done it... reset it. 42 | ``` 43 | 44 | ### Install on Windows 45 | 46 | ⚠️ Package is not published to npm yet! ⚠️ 47 | 48 | 1. Install [Node.js](https://nodejs.org/en/) (Version 10 or above) 49 | 2. Ensure you have [ffmpeg](https://www.ffmpeg.org/) installed and on your system's Path 50 | * If you do not have ffmpeg installed and on your system's Path, [read this to get it set up](https://github.com/South-Paw/discord-music-bot/blob/master/docs/installing-ffmpeg-on-windows.md) 51 | 3. Open a Powershell or Command Prompt window 52 | * Click Start > Run > type `powershell.exe` OR type `cmd.exe` > Press enter 53 | 4. Type `npm i -g @south-paw/discord-music-bot` to install the bot 54 | 5. Run the bot from the same window by typing `discord-music-bot -t YOUR_TOKEN -s YOUR_SERVER_ID -c YOUR_CHANNEL_ID -a YOUR_USER_ID` 55 | * See [CLI commands](#-cli-commands) for more details or type `discord-music-bot --help` 56 | 6. When you want to start the bot again (after a restart or shutdown), just run the command in step 5 57 | 58 | ### Install on Linux 59 | 60 | 1. todo 61 | 62 | ### Install on OSX 63 | 64 | 1. todo 65 | 66 | ## 📦 Advanced Usage 67 | 68 | ⚠️ Package is not published to npm yet! ⚠️ 69 | 70 | 1. Create a new folder for the bot script 71 | 2. Open a command prompt or terminal window in the folder 72 | 3. Install the npm package with `npm i @south-paw/discord-music-bot` 73 | 4. Create a file called `run.js` (or whatever you wish to call it) 74 | 5. Follow the example below for what you're able to configure and how 75 | 6. Start the bot by running `node run.js` from inside the folder 76 | 77 | ```js 78 | // example of `run.js` 79 | 80 | const config = { 81 | // these 3 are always required. 82 | token: 'YOUR DISCORD TOKEN', 83 | serverId: 'YOUR SERVER ID', 84 | textChannelId: 'YOUR COMMANDS TEXT CHANNEL ID', 85 | 86 | // TODO: other options 87 | }; 88 | 89 | const musicbot = new MusicBot(config); 90 | musicbot.run(); 91 | ``` 92 | 93 | ## 👨‍💻 CLI Commands 94 | 95 | ``` 96 | Usage: 97 | discord-music-bot [arguments] 98 | 99 | Required Arguments: 100 | --token, -t Your Discord token. 101 | --server, -s The id of the server you want to join. 102 | --channel, -c The id of the channel you want to listen for commands in. 103 | --admin, -a The user id of a Discord account that should have admin permissions. Pass the arg multiple times to add multiple users. 104 | 105 | Optional Arguments: 106 | --debug, -d Enable debug mode (aka, way more logging). 107 | ``` 108 | 109 | ## License 110 | 111 | This project is licensed under [GNU GPLv3](https://github.com/South-Paw/discord-music-bot/blob/master/LICENSE) 112 | 113 | ``` 114 | Copyright (C) 2017 Alex Gabites 115 | 116 | This program is free software: you can redistribute it and/or modify 117 | it under the terms of the GNU General Public License as published by 118 | the Free Software Foundation, either version 3 of the License, or 119 | (at your option) any later version. 120 | 121 | This program is distributed in the hope that it will be useful, 122 | but WITHOUT ANY WARRANTY; without even the implied warranty of 123 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 124 | GNU General Public License for more details. 125 | 126 | You should have received a copy of the GNU General Public License 127 | along with this program. If not, see . 128 | ``` 129 | -------------------------------------------------------------------------------- /bin/cli.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const meow = require('meow'); 4 | const MusicBot = require('../src/index.js'); 5 | 6 | const cliOptions = { 7 | flags: { 8 | token: { 9 | type: 'string', 10 | alias: 't', 11 | }, 12 | server: { 13 | type: 'string', 14 | alias: 's', 15 | }, 16 | channel: { 17 | type: 'string', 18 | alias: 'c', 19 | }, 20 | admin: { 21 | type: 'string', 22 | alias: 'a', 23 | }, 24 | debug: { 25 | type: 'boolean', 26 | alias: 'd', 27 | }, 28 | }, 29 | }; 30 | 31 | const cli = meow( 32 | ` 33 | Usage: 34 | discord-music-bot [arguments] 35 | 36 | Required Arguments: 37 | --token, -t Your Discord token. 38 | --server, -s The id of the server you want to join. 39 | --channel, -c The id of the channel you want to listen for commands in. 40 | --admin, -a The user id of a Discord account that should have admin permissions. Pass the arg multiple times to add multiple users. 41 | 42 | Optional Arguments: 43 | --debug, -d Enable debug mode (aka, way more logging). 44 | `, 45 | cliOptions, 46 | ); 47 | 48 | const users = {}; 49 | 50 | if (Array.isArray(cli.flags.admin)) { 51 | cli.flags.admin.forEach(id => { 52 | users[id] = 'admin'; 53 | }); 54 | } else if (typeof cli.flags.admin === 'string') { 55 | users[cli.flags.admin] = 'admin'; 56 | } 57 | 58 | const musicBot = new MusicBot({ 59 | token: cli.flags.token, 60 | serverId: cli.flags.server, 61 | textChannelId: cli.flags.channel, 62 | permissions: { users }, 63 | debug: cli.flags.debug, 64 | }); 65 | 66 | musicBot.run(); 67 | -------------------------------------------------------------------------------- /docs/discord-bot-credentials.md: -------------------------------------------------------------------------------- 1 | # todo 2 | -------------------------------------------------------------------------------- /docs/discord-getting-user-ids.md: -------------------------------------------------------------------------------- 1 | # todo 2 | -------------------------------------------------------------------------------- /docs/installing-ffmpeg-on-windows.md: -------------------------------------------------------------------------------- 1 | # Installing [FFmpeg](https://www.ffmpeg.org/) on Windows 2 | 3 | 1. Download a static build of [FFmpeg](http://ffmpeg.zeranoe.com/builds/) for Windows. 4 | 2. Create a directory somewhere on your computer and copy the contents of the ffmpeg zip into it. 5 | * I suggest placing it in a place like `C:/ffmpeg` 6 | 3. You should now have a folder called `bin` inside the ffmpeg folder you've created. 7 | * For example; if you placed your folder at `C:/ffmpeg`, you should have a folder at `C:/ffmpeg/bin` 8 | 4. Open your Environment Variables and add the path to your ffmpeg's bin folder to the `Path` variable. 9 | 1. Start > Search for `enviroment` > Select `Edit the system enviroment variables` > Click `Enviroment Variables...` at the bottom of the dialog 10 | 2. Select `Path` and click `Edit` in the top section > Click `New` and enter the path (eg: `C:/ffmpeg/bin`) > Click `Ok` and `Ok` 11 | 3. To check you've done this correctly, open command prompt or powershell and type `ffmpeg`, you should see something like [this](https://i.imgur.com/TNCc9Jb.png). 12 | 13 | You should now have FFmpeg installed on your system and avaliable via the Path. 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@south-paw/discord-music-bot", 3 | "version": "0.0.1", 4 | "description": "A music bot for Discord servers, self-hosted, easy to use and extendable.", 5 | "keywords": [ 6 | "discord", 7 | "bot", 8 | "music", 9 | "musicbot", 10 | "radio" 11 | ], 12 | "homepage": "https://github.com/South-Paw/discord-music-bot", 13 | "bugs": "https://github.com/South-Paw/discord-music-bot/issues", 14 | "license": "GPL-3.0", 15 | "author": { 16 | "name": "Alex Gabites", 17 | "email": "hello@southpaw.co.nz", 18 | "url": "http://southpaw.co.nz/" 19 | }, 20 | "files": [ 21 | "bin", 22 | "src" 23 | ], 24 | "bin": { 25 | "discord-music-bot": "./bin/cli.js" 26 | }, 27 | "main": "src/index.js", 28 | "repository": { 29 | "type": "git", 30 | "url": "https://github.com/South-Paw/discord-music-bot" 31 | }, 32 | "scripts": { 33 | "lint": "eslint .", 34 | "prepublishOnly": "yarn lint && yarn test", 35 | "test": "jest" 36 | }, 37 | "dependencies": { 38 | "dateformat": "^3.0.3", 39 | "deepmerge": "^3.0.0", 40 | "discord.js": "^11.4.2", 41 | "meow": "^5.0.0", 42 | "string-format": "^2.0.0" 43 | }, 44 | "devDependencies": { 45 | "coveralls": "^3.0.2", 46 | "eslint": "^5.11.1", 47 | "eslint-config-airbnb-base": "^13.1.0", 48 | "eslint-config-prettier": "^3.3.0", 49 | "eslint-plugin-import": "^2.14.0", 50 | "eslint-plugin-jest": "^22.1.2", 51 | "eslint-plugin-prettier": "^3.0.1", 52 | "jest": "^23.6.0", 53 | "prettier": "^1.15.3" 54 | }, 55 | "engines": { 56 | "node": ">=10.15.0" 57 | }, 58 | "publishConfig": { 59 | "access": "public" 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/commands/Command.js: -------------------------------------------------------------------------------- 1 | class Command { 2 | constructor(bot, args, message) { 3 | this.bot = bot; 4 | this.args = args; 5 | this.message = message; 6 | } 7 | } 8 | 9 | module.exports = Command; 10 | -------------------------------------------------------------------------------- /src/commands/Command.test.js: -------------------------------------------------------------------------------- 1 | const Command = require('./Command'); 2 | 3 | describe('Command', () => { 4 | describe('constructor()', () => { 5 | it('behaves as expected', () => { 6 | const bot = 'bot'; 7 | const args = 'args'; 8 | const message = 'message'; 9 | 10 | const Cmd = new Command(bot, args, message); 11 | 12 | expect(Cmd.bot).toBe(bot); 13 | expect(Cmd.args).toBe(args); 14 | expect(Cmd.message).toBe(message); 15 | }); 16 | }); 17 | }); 18 | -------------------------------------------------------------------------------- /src/commands/util/help.js: -------------------------------------------------------------------------------- 1 | const Command = require('../Command'); 2 | const { DIRECT_MESSAGE } = require('../../constants'); 3 | 4 | const MAX_ITEMS_PER_MESSAGE = 10; 5 | 6 | class HelpCommand extends Command { 7 | getSingleDetailBlock(commandDetails) { 8 | const prefix = this.bot.settings.preferences.COMMAND_PREFIX; 9 | const commandAliases = commandDetails.aliases.map(alias => `${prefix}${alias}`); 10 | 11 | let message = '```\n'; 12 | message += `${commandDetails.details.name} Command\n\n`; 13 | message += `${commandDetails.details.description}\n\n`; 14 | message += `Usage: ${prefix + commandDetails.details.usage}\n`; 15 | message += `Aliases: ${commandAliases.join(', ')}`; 16 | message += '```'; 17 | 18 | return message; 19 | } 20 | 21 | run() { 22 | this.bot.messageHandler(DIRECT_MESSAGE, 'HELP_COMMAND_WELCOME_DM', this.message); 23 | 24 | let detailStrings = []; 25 | 26 | Object.keys(this.bot.settings.commandDetails).forEach(key => { 27 | if (detailStrings.length === MAX_ITEMS_PER_MESSAGE) { 28 | this.bot.messageHandler(DIRECT_MESSAGE, 'HELP_COMMAND_DM', this.message, detailStrings); 29 | detailStrings = []; 30 | } 31 | 32 | detailStrings.push(this.getSingleDetailBlock(this.bot.settings.commandDetails[key])); 33 | }); 34 | 35 | if (detailStrings.length > 0) { 36 | this.bot.messageHandler(DIRECT_MESSAGE, 'HELP_COMMAND_DM', this.message, detailStrings); 37 | } 38 | } 39 | } 40 | 41 | const info = { 42 | key: 'help_command', 43 | aliases: ['help', 'h'], 44 | details: { 45 | name: 'Help', 46 | usage: 'help', 47 | description: "Direct messages you with a list of all the bot's commands that you have permission to use.", 48 | }, 49 | }; 50 | 51 | module.exports = { HelpCommand, info }; 52 | -------------------------------------------------------------------------------- /src/commands/util/join.js: -------------------------------------------------------------------------------- 1 | const Command = require('../Command'); 2 | const { LOG_ERROR, LOG_INFO, REPLY } = require('../../constants'); 3 | 4 | class JoinCommand extends Command { 5 | run() { 6 | const callerChannel = this.message.member.voiceChannel; 7 | 8 | if (callerChannel != null) { 9 | if (!callerChannel.joinable) { 10 | this.bot.messageHandler(REPLY, 'JOIN_COMMAND_CANT_JOIN', this.message); 11 | return; 12 | } 13 | 14 | callerChannel 15 | .join() 16 | .then(connection => { 17 | this.bot.setActiveVoiceConnection(connection); 18 | this.bot.logger(LOG_INFO, `Succesfully joined voice channel '${callerChannel.name}'`); 19 | }) 20 | .catch(error => { 21 | this.bot.resetActiveVoiceConnection(); 22 | this.bot.logger(LOG_ERROR, `Something went wrong while joining a voice channel: '${error}'`); 23 | this.bot.messageHandler(REPLY, 'JOIN_COMMAND_ERROR', this.message, error.message); 24 | }); 25 | 26 | return; 27 | } 28 | 29 | this.bot.messageHandler(REPLY, 'JOIN_COMMAND_FAILED', this.message); 30 | this.bot.logger(LOG_INFO, `Attempted to join caller but they were not in a voice channel`); 31 | } 32 | } 33 | 34 | const info = { 35 | key: 'join_command', 36 | aliases: ['join', 'j'], 37 | details: { 38 | name: 'Join', 39 | usage: 'join', 40 | description: 'Bot will join the current voice channel that you are in.', 41 | }, 42 | }; 43 | 44 | module.exports = { JoinCommand, info }; 45 | -------------------------------------------------------------------------------- /src/commands/util/leave.js: -------------------------------------------------------------------------------- 1 | const Command = require('../Command'); 2 | const { LOG_INFO } = require('../../constants'); 3 | 4 | class LeaveCommand extends Command { 5 | run() { 6 | this.bot.resetActiveVoiceConnection(); 7 | 8 | this.bot.logger(LOG_INFO, `Leaving active voice channel`); 9 | } 10 | } 11 | 12 | const info = { 13 | key: 'leave_command', 14 | aliases: ['leave', 'l'], 15 | details: { 16 | name: 'Leave', 17 | usage: 'leave', 18 | description: 'Bot will leave any voice channel it is connected to.', 19 | }, 20 | }; 21 | 22 | module.exports = { LeaveCommand, info }; 23 | -------------------------------------------------------------------------------- /src/commands/util/setAvatar.js: -------------------------------------------------------------------------------- 1 | const Command = require('../Command'); 2 | const { REPLY } = require('../../constants'); 3 | 4 | const urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/; 5 | 6 | class SetAvatarCommand extends Command { 7 | run() { 8 | if (this.args[0] && this.args[0].match(urlRegex)) { 9 | this.bot.client.user 10 | .setAvatar(this.args[0]) 11 | .then(() => this.bot.messageHandler(REPLY, 'SET_AVATAR_COMMAND_SUCCESS', this.message)) 12 | .catch(error => this.bot.messageHandler(REPLY, 'SET_AVATAR_COMMAND_ERROR', this.message, error)); 13 | 14 | return; 15 | } 16 | 17 | this.bot.messageHandler(REPLY, 'SET_AVATAR_COMMAND_INVALID_URL', this.message); 18 | } 19 | } 20 | 21 | const info = { 22 | key: 'setAvatar_command', 23 | aliases: ['setavatar'], 24 | details: { 25 | name: 'Set Avatar', 26 | usage: 'setavatar ', 27 | description: "Set the bot's avatar image to the given url (overrides the previous image).", 28 | }, 29 | }; 30 | 31 | module.exports = { SetAvatarCommand, info }; 32 | -------------------------------------------------------------------------------- /src/commands/util/setUsername.js: -------------------------------------------------------------------------------- 1 | const Command = require('../Command'); 2 | const { REPLY } = require('../../constants'); 3 | 4 | class SetUsernameCommand extends Command { 5 | run() { 6 | if (this.args.length >= 1) { 7 | this.bot.client.user 8 | .setUsername(this.args.join(' ')) 9 | .then(() => this.bot.messageHandler(REPLY, 'SET_USERNAME_COMMAND_SUCCESS', this.message)) 10 | .catch(error => this.bot.messageHandler(REPLY, 'SET_USERNAME_COMMAND_ERROR', this.message, error)); 11 | 12 | return; 13 | } 14 | 15 | this.bot.messageHandler(REPLY, 'SET_USERNAME_COMMAND_INVALID_NAME', this.message); 16 | } 17 | } 18 | 19 | const info = { 20 | key: 'setUsername_command', 21 | aliases: ['setusername'], 22 | details: { 23 | name: 'Set Username', 24 | usage: 'setusername ', 25 | description: "Sets the bot's username.", 26 | }, 27 | }; 28 | 29 | module.exports = { SetUsernameCommand, info }; 30 | -------------------------------------------------------------------------------- /src/constants.js: -------------------------------------------------------------------------------- 1 | const LOG_INFO = 'info'; 2 | const LOG_WARN = 'warn'; 3 | const LOG_ERROR = 'error'; 4 | const LOG_DEBUG = 'debug'; 5 | 6 | const SEND = 'send'; 7 | const REPLY = 'reply'; 8 | const DIRECT_MESSAGE = 'direct_message'; 9 | 10 | module.exports = { 11 | LOG_INFO, 12 | LOG_WARN, 13 | LOG_ERROR, 14 | LOG_DEBUG, 15 | SEND, 16 | REPLY, 17 | DIRECT_MESSAGE, 18 | }; 19 | -------------------------------------------------------------------------------- /src/defaults/commands.js: -------------------------------------------------------------------------------- 1 | const { HelpCommand, info: helpInfo } = require('../commands/util/help'); 2 | const { SetAvatarCommand, info: setAvatarInfo } = require('../commands/util/setAvatar'); 3 | const { SetUsernameCommand, info: setUsernameInfo } = require('../commands/util/setUsername'); 4 | const { JoinCommand, info: joinInfo } = require('../commands/util/join'); 5 | const { LeaveCommand, info: leaveInfo } = require('../commands/util/leave'); 6 | 7 | const defaultCommands = { 8 | [helpInfo.key]: HelpCommand, 9 | [setAvatarInfo.key]: SetAvatarCommand, 10 | [setUsernameInfo.key]: SetUsernameCommand, 11 | [joinInfo.key]: JoinCommand, 12 | [leaveInfo.key]: LeaveCommand, 13 | }; 14 | 15 | const defaultCommandDetails = { 16 | [helpInfo.key]: helpInfo, 17 | [setAvatarInfo.key]: setAvatarInfo, 18 | [setUsernameInfo.key]: setUsernameInfo, 19 | [joinInfo.key]: joinInfo, 20 | [leaveInfo.key]: leaveInfo, 21 | }; 22 | 23 | module.exports = { defaultCommands, defaultCommandDetails }; 24 | -------------------------------------------------------------------------------- /src/defaults/messages.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-unused-vars */ 2 | 3 | const format = require('string-format'); 4 | 5 | const defaultMessageStrings = { 6 | BOT_MENTIONED: 'Hey {}, you should try `{}help` for a list of commands. :ok_hand:', 7 | UNKNOWN_COMMAND: "Hmmm. I couldn't find that command... did you mistype it?", 8 | NO_PERMISSION: "You don't have permission for that command.", 9 | HELP_COMMAND_UNKNOWN: "I can't see a command or alias for that one... why don't you try `{}help`?", 10 | HELP_COMMAND_WELCOME_DM: "Here's a list of all the commands you can use:", 11 | HELP_COMMAND_DM: true, // Message is formatted within the command class. 12 | SET_AVATAR_COMMAND_SUCCESS: ':ok_hand: Avatar successfully set!', 13 | SET_AVATAR_COMMAND_ERROR: 'Unable to set avatar.\n```{}```', 14 | SET_AVATAR_COMMAND_INVALID_URL: "Are you sure that's a valid URL..?", 15 | SET_USERNAME_COMMAND_SUCCESS: ':ok_hand: Username successfully set!', 16 | SET_USERNAME_COMMAND_ERROR: 'Unable to set username.\n```{}```', 17 | SET_USERNAME_COMMAND_INVALID_NAME: "Uhh... that doesn't seem to be something I could name myself...", 18 | JOIN_COMMAND_CANT_JOIN: 'Unable to join your channel, are you sure I have permissions for it?', 19 | JOIN_COMMAND_ERROR: 'Something went wrong while joining the voice channel:\n```{}```', 20 | JOIN_COMMAND_FAILED: 'You need to be in a voice channel before requesting I join you.', 21 | }; 22 | 23 | const messageFunctions = { 24 | /* eslint-disable prettier/prettier */ 25 | BOT_MENTIONED: (string, bot, message) => format(string, message.member.user.toString(), bot.settings.preferences.COMMAND_PREFIX), 26 | UNKNOWN_COMMAND: (string, bot, message) => string, 27 | NO_PERMISSION: (string, bot, message) => string, 28 | HELP_COMMAND_UNKNOWN: (string, bot, message) => format(string, bot.settings.preferences.COMMAND_PREFIX), 29 | HELP_COMMAND_WELCOME_DM: (string, bot, message) => string, 30 | HELP_COMMAND_DM: (string, bot, message, acutualMessage) => acutualMessage, 31 | SET_AVATAR_COMMAND_SUCCESS: (string, bot, message) => string, 32 | SET_AVATAR_COMMAND_ERROR: (string, bot, message, error) => format(string, error), 33 | SET_AVATAR_COMMAND_INVALID_URL: (string, bot, message) => string, 34 | SET_USERNAME_COMMAND_SUCCESS: (string, bot, message) => string, 35 | SET_USERNAME_COMMAND_ERROR: (string, bot, message, error) => format(string, error), 36 | SET_USERNAME_COMMAND_INVALID_NAME: (string, bot, message) => string, 37 | JOIN_COMMAND_CANT_JOIN: (string, bot, message) => string, 38 | JOIN_COMMAND_ERROR: (string, bot, message, error) => format(string, error), 39 | JOIN_COMMAND_FAILED: (string, bot, message) => string, 40 | /* eslint-enable prettier/prettier */ 41 | }; 42 | 43 | module.exports = { defaultMessageStrings, messageFunctions }; 44 | -------------------------------------------------------------------------------- /src/defaults/permissions.js: -------------------------------------------------------------------------------- 1 | const defaultGlobalPermissions = { 2 | help_command: true, 3 | setAvatar_command: false, 4 | setUsername_command: false, 5 | join_command: true, 6 | leave_command: true, 7 | }; 8 | 9 | const defaultGroupPermissions = { 10 | admin: { 11 | ...defaultGlobalPermissions, 12 | setAvatar_command: true, 13 | setUsername_command: true, 14 | }, 15 | }; 16 | 17 | module.exports = { defaultGlobalPermissions, defaultGroupPermissions }; 18 | -------------------------------------------------------------------------------- /src/defaults/preferences.js: -------------------------------------------------------------------------------- 1 | const defaultPreferences = { 2 | COMMAND_PREFIX: '!', 3 | }; 4 | 5 | module.exports = defaultPreferences; 6 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2017 Alex Gabites 3 | * 4 | * This program is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | const Discord = require('discord.js'); 19 | const deepmerge = require('deepmerge'); 20 | 21 | const { defaultCommands, defaultCommandDetails } = require('./defaults/commands'); 22 | const { defaultMessageStrings, messageFunctions } = require('./defaults/messages'); 23 | const { defaultGlobalPermissions, defaultGroupPermissions } = require('./defaults/permissions'); 24 | const defaultPreferences = require('./defaults/preferences'); 25 | 26 | const { LOG_INFO, LOG_WARN, LOG_ERROR, LOG_DEBUG, SEND, REPLY, DIRECT_MESSAGE } = require('./constants'); 27 | const { findCommandKeyByAlias, getLoggerPrefix } = require('./util'); 28 | 29 | const defaultState = { 30 | activeTextChannelId: null, 31 | }; 32 | 33 | class MusicBot { 34 | constructor(config) { 35 | const { 36 | token, 37 | serverId, 38 | textChannelId, 39 | commands = {}, 40 | commandDetails = {}, 41 | messageStrings = {}, 42 | permissions = {}, 43 | preferences = {}, 44 | debug = false, 45 | } = config; 46 | 47 | const { global: globalPermissions = {}, groups: groupPermissions = {}, users: usersPermissions = {} } = permissions; 48 | 49 | const groupPermissionsWithDefaults = {}; 50 | 51 | // Ensure that any provided groupPermissions also contain the defaultGlobalPermissions, otherwise groups may not have access to all commands. 52 | Object.keys(groupPermissions).forEach(key => { 53 | groupPermissionsWithDefaults[key] = deepmerge(defaultGlobalPermissions, groupPermissions[key]); 54 | }); 55 | 56 | this.settings = { 57 | token, 58 | serverId, 59 | textChannelId, 60 | commands: deepmerge(defaultCommands, commands), 61 | commandDetails: deepmerge(defaultCommandDetails, commandDetails), 62 | messageFunctions, 63 | messageStrings: deepmerge(defaultMessageStrings, messageStrings), 64 | permissions: { 65 | global: deepmerge(defaultGlobalPermissions, globalPermissions), 66 | groups: deepmerge(defaultGroupPermissions, groupPermissionsWithDefaults), 67 | users: usersPermissions, 68 | }, 69 | preferences: deepmerge(defaultPreferences, preferences), 70 | debug, 71 | }; 72 | 73 | this.activeVoiceConnection = null; 74 | 75 | this.state = { ...defaultState }; 76 | 77 | this.client = new Discord.Client(); 78 | } 79 | 80 | isDebug() { 81 | return this.settings.debug; 82 | } 83 | 84 | logger(level, message, prefix = getLoggerPrefix) { 85 | /* eslint-disable no-console */ 86 | switch (level) { 87 | case LOG_INFO: 88 | console.info(prefix(level), message); 89 | break; 90 | case LOG_WARN: 91 | console.warn(prefix(level), message); 92 | break; 93 | case LOG_ERROR: 94 | console.error(prefix(level), message); 95 | break; 96 | case LOG_DEBUG: 97 | if (this.isDebug()) console.debug(prefix(level), message); 98 | break; 99 | default: 100 | console.log(prefix(level), message); 101 | } 102 | /* eslint-enable no-console */ 103 | } 104 | 105 | setState(newState) { 106 | this.state = deepmerge(this.state, newState); 107 | } 108 | 109 | resetState() { 110 | this.state = { 111 | ...defaultState, 112 | activeTextChannelId: this.state.activeTextChannelId, 113 | }; 114 | } 115 | 116 | setActiveVoiceConnection(connection) { 117 | this.activeVoiceConnection = connection; 118 | } 119 | 120 | resetActiveVoiceConnection() { 121 | if (this.activeVoiceConnection) { 122 | this.activeVoiceConnection.disconnect(); 123 | } 124 | 125 | this.activeVoiceConnection = null; 126 | } 127 | 128 | messageHandler(type, key, message, ...other) { 129 | const messageString = this.settings.messageStrings[key]; 130 | const messageFunction = this.settings.messageFunctions[key]; 131 | 132 | if (!messageString || !messageFunction) { 133 | this.logger(LOG_ERROR, `Failed to find message (string or function) with key '${key}'`); 134 | return; 135 | } 136 | 137 | const response = messageFunction(messageString, this, message, ...other); 138 | 139 | switch (type) { 140 | case SEND: 141 | message.channel.send(response); 142 | break; 143 | case REPLY: 144 | message.reply(response); 145 | break; 146 | case DIRECT_MESSAGE: 147 | message.member.createDM().then(dm => dm.send(response)); 148 | break; 149 | default: 150 | this.logger(LOG_ERROR, `Unknown message return type '${type}'`); 151 | } 152 | } 153 | 154 | hasCommandPermission(userId, commandKey) { 155 | const { users, groups, global } = this.settings.permissions; 156 | const groupId = users[`${userId}`]; 157 | 158 | if (users[`${userId}`] && groups[`${groupId}`]) { 159 | return !!groups[`${groupId}`][`${commandKey}`]; 160 | } 161 | 162 | return !!global[`${commandKey}`]; 163 | } 164 | 165 | commandHandler(key, args, message) { 166 | const CommandClass = this.settings.commands[key]; 167 | 168 | if (!CommandClass) { 169 | this.logger(LOG_ERROR, `Failed to find command with key '${key}'`); 170 | return; 171 | } 172 | 173 | this.logger(LOG_INFO, `'${message.member.displayName}' called '${key}' with ${JSON.stringify(args)}`); 174 | 175 | if (!this.hasCommandPermission(message.member.id, key)) { 176 | this.logger(LOG_INFO, `'${message.member.displayName}' does not have permission for '${key}'`); 177 | 178 | this.messageHandler(REPLY, 'NO_PERMISSION', message); 179 | 180 | return; 181 | } 182 | 183 | const Command = new CommandClass(this, args, message); 184 | Command.run(); 185 | } 186 | 187 | onReady() { 188 | const { serverId, textChannelId } = this.settings; 189 | 190 | const server = this.client.guilds.get(serverId); 191 | if (!server) { 192 | throw new Error(`Failed to connect to serverId '${serverId}'`); 193 | } 194 | 195 | const activeTextChannel = server.channels.find(({ id, type }) => id === textChannelId && type === 'text'); 196 | if (!activeTextChannel) { 197 | throw new Error(`Failed to find textChannelId '${textChannelId}'`); 198 | } 199 | 200 | this.setState({ activeTextChannelId: activeTextChannel.id }); 201 | 202 | this.logger(LOG_INFO, `Successfully connected to '${server.name}'`); 203 | } 204 | 205 | onMessage(message) { 206 | const { author, channel } = message; 207 | const { activeTextChannelId } = this.state; 208 | 209 | const isInCommandsChannel = channel.id === activeTextChannelId; 210 | const isNotOwnMessage = author.id !== this.client.user.id; 211 | 212 | if (isInCommandsChannel && isNotOwnMessage) { 213 | // If the message begins with the command prefix 214 | if (message.content && message.content[0] === this.settings.preferences.COMMAND_PREFIX) { 215 | const params = message.content 216 | .slice(1) 217 | .split(' ') 218 | .filter(param => param.length > 0); 219 | 220 | const commandAlias = findCommandKeyByAlias(this.settings.commandDetails, params[0]); 221 | 222 | if (!commandAlias) { 223 | this.messageHandler(REPLY, 'UNKNOWN_COMMAND', message); 224 | return; 225 | } 226 | 227 | this.commandHandler(commandAlias, params.slice(1), message); 228 | return; 229 | } 230 | 231 | // If the message mentions the bot 232 | if (message.isMentioned(this.client.user)) { 233 | this.messageHandler(SEND, 'BOT_MENTIONED', message); 234 | } 235 | } 236 | } 237 | 238 | onDisconnect({ reason, code }) { 239 | this.logger(LOG_ERROR, `Bot was disconnected from server.\nReason: ${reason}\nCode: ${code}`); 240 | 241 | throw new Error('Bot was disconnected from server.'); 242 | } 243 | 244 | run() { 245 | const { token, serverId, textChannelId } = this.settings; 246 | const prefix = 'Failed to initialise:'; 247 | 248 | if (!token) { 249 | throw new Error(`${prefix} a 'token' was not provided in the config!`); 250 | } 251 | 252 | if (!serverId) { 253 | throw new Error(`${prefix} a 'serverId' was not provided in the config!`); 254 | } 255 | 256 | if (!textChannelId) { 257 | throw new Error(`${prefix} a 'textChannelId' was not provided in the config!`); 258 | } 259 | 260 | this.client.on('ready', () => this.onReady()); 261 | this.client.on('message', message => this.onMessage(message)); 262 | this.client.on('disconnect', event => this.onDisconnect(event)); 263 | 264 | this.logger(LOG_INFO, 'Logging into server...'); 265 | 266 | this.client.login(token); 267 | } 268 | } 269 | 270 | module.exports = MusicBot; 271 | -------------------------------------------------------------------------------- /src/index.test.js: -------------------------------------------------------------------------------- 1 | const MusicBot = require('./index'); 2 | const { LOG_INFO, LOG_WARN, LOG_ERROR, LOG_DEBUG, SEND, REPLY, DIRECT_MESSAGE } = require('./constants'); 3 | const { defaultMessageStrings } = require('./defaults/messages'); 4 | const Command = require('./commands/Command'); 5 | 6 | const defaultState = { 7 | activeTextChannelId: null, 8 | }; 9 | 10 | describe('MusicBot', () => { 11 | xdescribe('constructor', () => { 12 | it('merges config `commands` into `this.settings.commands` as expected', () => {}); 13 | 14 | it('merges config `commandDetails` into `this.settings.commandDetails` as expected', () => {}); 15 | 16 | it('merges config `messageStrings` into `this.settings.messageStrings` as expected', () => {}); 17 | 18 | it('merges config `permissions.global` into `this.settings.permissions.global` as expected', () => {}); 19 | 20 | it('merges config `permissions.groups` into `this.settings.permissions.groups` as expected', () => {}); 21 | 22 | it('merges config `permissions.users` into `this.settings.permissions.users` as expected', () => {}); 23 | }); 24 | 25 | describe('isDebug()', () => { 26 | it('returns false by default', () => { 27 | const bot = new MusicBot({}); 28 | 29 | expect(bot.isDebug()).toBe(false); 30 | }); 31 | 32 | it('returns true if set in the config', () => { 33 | const bot = new MusicBot({ debug: true }); 34 | 35 | expect(bot.isDebug()).toBe(true); 36 | }); 37 | }); 38 | 39 | describe('logger()', () => { 40 | const noFunc = () => ''; 41 | 42 | it('defaults to `console.log`', () => { 43 | const spy = jest.spyOn(global.console, 'log'); 44 | 45 | const testMsg = 'test'; 46 | const bot = new MusicBot({}); 47 | 48 | bot.logger(testMsg, testMsg, noFunc); 49 | 50 | expect(spy).toHaveBeenCalledWith(noFunc(), testMsg); 51 | 52 | spy.mockReset(); 53 | spy.mockRestore(); 54 | }); 55 | 56 | it('uses `console.info` for `LOG_INFO`', () => { 57 | const spy = jest.spyOn(global.console, 'info'); 58 | 59 | const testMsg = 'test'; 60 | const bot = new MusicBot({}); 61 | 62 | bot.logger(LOG_INFO, testMsg, noFunc); 63 | 64 | expect(spy).toHaveBeenCalledWith(noFunc(), testMsg); 65 | 66 | spy.mockReset(); 67 | spy.mockRestore(); 68 | }); 69 | 70 | it('uses `console.warn` for `LOG_WARN`', () => { 71 | const spy = jest.spyOn(global.console, 'warn'); 72 | 73 | const testMsg = 'test'; 74 | const bot = new MusicBot({}); 75 | 76 | bot.logger(LOG_WARN, testMsg, noFunc); 77 | 78 | expect(spy).toHaveBeenCalledWith(noFunc(), testMsg); 79 | 80 | spy.mockReset(); 81 | spy.mockRestore(); 82 | }); 83 | 84 | it('uses `console.error` for `LOG_ERROR`', () => { 85 | const spy = jest.spyOn(global.console, 'error'); 86 | 87 | const testMsg = 'test'; 88 | const bot = new MusicBot({}); 89 | 90 | bot.logger(LOG_ERROR, testMsg, noFunc); 91 | 92 | expect(spy).toHaveBeenCalledWith(noFunc(), testMsg); 93 | 94 | spy.mockReset(); 95 | spy.mockRestore(); 96 | }); 97 | 98 | it('uses `console.debug` for `LOG_DEBUG` when `isDebug()=true`', () => { 99 | const spy = jest.spyOn(global.console, 'debug'); 100 | 101 | const testMsg = 'test'; 102 | const bot = new MusicBot({ debug: true }); 103 | 104 | bot.logger(LOG_DEBUG, testMsg, noFunc); 105 | 106 | expect(spy).toHaveBeenCalledWith(noFunc(), testMsg); 107 | 108 | spy.mockReset(); 109 | spy.mockRestore(); 110 | }); 111 | 112 | it("doesn't call `console.debug` for `LOG_DEBUG` when `isDebug=false`", () => { 113 | const spy = jest.spyOn(global.console, 'debug'); 114 | 115 | const testMsg = 'aNewTest'; 116 | const bot = new MusicBot({}); 117 | 118 | bot.logger(LOG_DEBUG, testMsg, noFunc); 119 | 120 | expect(spy).toHaveBeenCalledTimes(0); 121 | 122 | spy.mockReset(); 123 | spy.mockRestore(); 124 | }); 125 | }); 126 | 127 | describe('setState()', () => { 128 | it('merges the `newState` into the existing state', () => { 129 | const bot = new MusicBot({}); 130 | 131 | expect(bot.state).toEqual(defaultState); 132 | 133 | bot.setState({ music: 'bot' }); 134 | 135 | expect(bot.state).toEqual({ ...defaultState, music: 'bot' }); 136 | }); 137 | }); 138 | 139 | describe('resetState()', () => { 140 | it("resets the bot's state back to the default", () => { 141 | const bot = new MusicBot({}); 142 | 143 | const initialState = bot.state; 144 | 145 | bot.setState({ thing: 'test' }); 146 | 147 | expect(bot.state).toEqual({ ...defaultState, thing: 'test' }); 148 | 149 | bot.resetState(); 150 | 151 | expect(bot.state).toEqual(initialState); 152 | }); 153 | }); 154 | 155 | describe('setActiveVoiceConnection', () => { 156 | it('sets the active voice connection', () => { 157 | const expected = 'expected-value'; 158 | 159 | const bot = new MusicBot({}); 160 | 161 | bot.setActiveVoiceConnection(expected); 162 | 163 | expect(bot.activeVoiceConnection).toBe(expected); 164 | }); 165 | }); 166 | 167 | describe('resetActiveVoiceConnection', () => { 168 | it('clears the active voice connection and calls disconnect()', () => { 169 | const mockFn = jest.fn(); 170 | const connection = { disconnect: mockFn }; 171 | 172 | const bot = new MusicBot({}); 173 | 174 | bot.activeVoiceConnection = connection; 175 | 176 | bot.resetActiveVoiceConnection(); 177 | 178 | expect(mockFn.mock.calls.length).toBe(1); 179 | expect(bot.activeVoiceConnection).toBe(null); 180 | }); 181 | 182 | it("does not call disconnect() on the connection if it's not set", () => { 183 | const bot = new MusicBot({}); 184 | 185 | bot.activeVoiceConnection = null; 186 | 187 | bot.resetActiveVoiceConnection(); 188 | 189 | expect(bot.activeVoiceConnection).toBe(null); 190 | }); 191 | }); 192 | 193 | describe('messageHandler()', () => { 194 | it('logs an error if the given key is not found in `messageString`', () => { 195 | const mockFn = jest.fn(); 196 | 197 | const bot = new MusicBot({}); 198 | 199 | bot.logger = mockFn; 200 | 201 | bot.messageHandler(SEND, 'TEST_STRING', {}); 202 | 203 | expect(mockFn.mock.calls[0][1]).toBe("Failed to find message (string or function) with key 'TEST_STRING'"); 204 | }); 205 | 206 | it('logs an error if the given key is not found in `messageFunction`', () => { 207 | const mockFn = jest.fn(); 208 | 209 | const TEST_STRING = 'test string'; 210 | const bot = new MusicBot({ messageStrings: { TEST_STRING } }); 211 | 212 | bot.logger = mockFn; 213 | 214 | bot.messageHandler(SEND, 'TEST_STRING', {}); 215 | 216 | expect(mockFn.mock.calls[0][1]).toBe("Failed to find message (string or function) with key 'TEST_STRING'"); 217 | }); 218 | 219 | it('calls send on a message when type = `SEND`', () => { 220 | const mockFn = jest.fn(); 221 | 222 | const bot = new MusicBot({}); 223 | 224 | bot.messageHandler(SEND, 'UNKNOWN_COMMAND', { channel: { send: mockFn } }); 225 | 226 | expect(mockFn.mock.calls[0][0]).toBe(defaultMessageStrings.UNKNOWN_COMMAND); 227 | }); 228 | 229 | it('calls send on a message when type = `REPLY`', () => { 230 | const mockFn = jest.fn(); 231 | 232 | const bot = new MusicBot({}); 233 | 234 | bot.messageHandler(REPLY, 'UNKNOWN_COMMAND', { reply: mockFn }); 235 | 236 | expect(mockFn.mock.calls[0][0]).toBe(defaultMessageStrings.UNKNOWN_COMMAND); 237 | }); 238 | 239 | it('calls send on a message when type = `DIRECT_MESSAGE`', () => { 240 | const mockFn = jest.fn(); 241 | 242 | const bot = new MusicBot({}); 243 | 244 | bot.messageHandler(DIRECT_MESSAGE, 'UNKNOWN_COMMAND', { 245 | member: { createDM: () => ({ then: fn => fn({ send: mockFn }) }) }, 246 | }); 247 | 248 | expect(mockFn.mock.calls[0][0]).toBe(defaultMessageStrings.UNKNOWN_COMMAND); 249 | }); 250 | 251 | it('logs an error when the type is unknown', () => { 252 | const mockFn = jest.fn(); 253 | 254 | const bot = new MusicBot({}); 255 | 256 | bot.logger = mockFn; 257 | 258 | bot.messageHandler('TEST_TYPE', 'UNKNOWN_COMMAND', {}); 259 | 260 | expect(mockFn.mock.calls[0][1]).toBe("Unknown message return type 'TEST_TYPE'"); 261 | }); 262 | }); 263 | 264 | describe('hasCommandPermission()', () => { 265 | it('uses the global permissions if the `userId` is not in the users list', () => { 266 | const bot = new MusicBot({}); 267 | 268 | expect(bot.hasCommandPermission('1234', 'setUsername_command')).toBe(false); 269 | }); 270 | 271 | it("uses the global permissions if the `userId` has a group but the group doesn't exist", () => { 272 | const bot = new MusicBot({ 273 | permissions: { 274 | users: { 275 | '1234': 'agroup', 276 | }, 277 | }, 278 | }); 279 | 280 | expect(bot.hasCommandPermission('1234', 'setUsername_command')).toBe(false); 281 | }); 282 | 283 | it('returns the command permission for the group the given `userId` belongs to', () => { 284 | const bot = new MusicBot({ 285 | permissions: { 286 | users: { 287 | '1234': 'agroup', 288 | }, 289 | groups: { 290 | agroup: { 291 | setUsername_command: true, 292 | }, 293 | }, 294 | }, 295 | }); 296 | 297 | expect(bot.hasCommandPermission('1234', 'setUsername_command')).toBe(true); 298 | }); 299 | }); 300 | 301 | describe('commandHandler()', () => { 302 | it('logs an error if there is no command for the given key', () => { 303 | const mockFn = jest.fn(); 304 | 305 | const bot = new MusicBot({}); 306 | 307 | bot.logger = mockFn; 308 | 309 | bot.commandHandler('unknown_key', [], {}); 310 | 311 | expect(mockFn.mock.calls[0][1]).toBe("Failed to find command with key 'unknown_key'"); 312 | }); 313 | 314 | it('logs a message and args used if the command exists', () => { 315 | const mockLogger = jest.fn(); 316 | const mockMessageHandler = jest.fn(); 317 | 318 | const bot = new MusicBot({}); 319 | 320 | bot.logger = mockLogger; 321 | bot.messageHandler = mockMessageHandler; 322 | 323 | bot.commandHandler('setUsername_command', ['arg1', 'arg2', 'arg3'], { member: { displayName: 'test user' } }); 324 | 325 | expect(mockLogger.mock.calls[0][1]).toBe( 326 | '\'test user\' called \'setUsername_command\' with ["arg1","arg2","arg3"]', 327 | ); 328 | }); 329 | 330 | it("logs a message and replies to the user if they don't have permission for the command", () => { 331 | const mockLogger = jest.fn(); 332 | const mockMessageHandler = jest.fn(); 333 | 334 | const bot = new MusicBot({}); 335 | 336 | bot.logger = mockLogger; 337 | bot.messageHandler = mockMessageHandler; 338 | 339 | bot.commandHandler('setUsername_command', ['newName'], { member: { displayName: 'test user' } }); 340 | 341 | expect(mockLogger.mock.calls[1][1]).toBe("'test user' does not have permission for 'setUsername_command'"); 342 | expect(mockMessageHandler.mock.calls[0][1]).toBe('NO_PERMISSION'); 343 | }); 344 | 345 | it('runs the command if everything is okay', () => { 346 | const mockCommandRun = jest.fn(); 347 | const mockLogger = jest.fn(); 348 | const mockMessageHandler = jest.fn(); 349 | 350 | const bot = new MusicBot({}); 351 | 352 | class MockCommand extends Command { 353 | run() { 354 | mockCommandRun(this.args); 355 | } 356 | } 357 | 358 | bot.settings.commands.help_command = MockCommand; 359 | bot.logger = mockLogger; 360 | bot.messageHandler = mockMessageHandler; 361 | 362 | const args = ['arg1', 'arg2', 'arg3']; 363 | 364 | bot.commandHandler('help_command', args, { member: { displayName: 'test user' } }); 365 | 366 | expect(mockCommandRun.mock.calls[0][0]).toBe(args); 367 | }); 368 | }); 369 | 370 | describe('onReady()', () => { 371 | it("throws an Error if the `serverId` isn't resolvable", () => { 372 | const serverId = 'test'; 373 | const bot = new MusicBot({ serverId }); 374 | 375 | let result; 376 | 377 | try { 378 | bot.onReady(); 379 | } catch (e) { 380 | result = e; 381 | } 382 | 383 | expect(result.message).toBe(`Failed to connect to serverId '${serverId}'`); 384 | }); 385 | 386 | it("throws an Error if the textChannelId isn't in the `server.channels`", () => { 387 | const textChannelId = 'test'; 388 | const bot = new MusicBot({ serverId: 'test', textChannelId }); 389 | 390 | bot.client.guilds.get = () => ({ channels: [] }); 391 | 392 | let result; 393 | 394 | try { 395 | bot.onReady(); 396 | } catch (e) { 397 | result = e; 398 | } 399 | 400 | expect(result.message).toBe(`Failed to find textChannelId '${textChannelId}'`); 401 | }); 402 | 403 | it('will log a success message when it can connect', () => { 404 | const textChannelId = 'test'; 405 | const bot = new MusicBot({ serverId: 'test', textChannelId }); 406 | 407 | bot.client.guilds.get = () => ({ channels: [{ id: textChannelId, type: 'text' }] }); 408 | 409 | const mockFn = jest.fn(); 410 | bot.logger = mockFn; 411 | 412 | bot.onReady(); 413 | 414 | expect(mockFn.mock.calls.length).toBe(1); 415 | }); 416 | }); 417 | 418 | describe('onMessage()', () => { 419 | it("should not reply to it's own messages", () => { 420 | const botUserId = 123; 421 | const channelId = 'test-channel'; 422 | const mockFn = jest.fn(); 423 | 424 | const bot = new MusicBot({}); 425 | bot.client = { user: { id: botUserId } }; 426 | bot.setState({ activeTextChannelId: channelId }); 427 | 428 | const message = { 429 | author: { id: botUserId }, 430 | channel: { id: channelId, send: mockFn }, 431 | }; 432 | 433 | bot.onMessage(message); 434 | 435 | expect(mockFn.mock.calls.length).toBe(0); 436 | }); 437 | 438 | it('should not reply to messages in other channels', () => { 439 | const mockFn = jest.fn(); 440 | 441 | const bot = new MusicBot({}); 442 | bot.client = { user: { id: 123 } }; 443 | bot.setState({ activeTextChannelId: 'test-channel' }); 444 | 445 | const message = { 446 | author: { id: 456 }, 447 | channel: { id: 'test-channel2', send: mockFn }, 448 | }; 449 | 450 | bot.onMessage(message); 451 | 452 | expect(mockFn.mock.calls.length).toBe(0); 453 | }); 454 | 455 | it('should reply to the user if the bot was mentioned', () => { 456 | const channelId = 'test-channel'; 457 | const mockMessageHandler = jest.fn(); 458 | 459 | const bot = new MusicBot({}); 460 | bot.messageHandler = mockMessageHandler; 461 | bot.client = { user: { id: 123 } }; 462 | bot.setState({ activeTextChannelId: channelId }); 463 | 464 | const message = { 465 | author: { id: 456 }, 466 | channel: { id: channelId }, 467 | isMentioned: () => true, 468 | content: 'hi there', 469 | }; 470 | 471 | bot.onMessage(message); 472 | 473 | expect(mockMessageHandler.mock.calls.length).toBe(1); 474 | }); 475 | 476 | it("will not do anything when it's just a message in the channel", () => { 477 | const channelId = 'test-channel'; 478 | const mockMessageHandler = jest.fn(); 479 | 480 | const bot = new MusicBot({}); 481 | bot.messageHandler = mockMessageHandler; 482 | bot.client = { user: { id: 123 } }; 483 | bot.setState({ activeTextChannelId: channelId }); 484 | 485 | const message = { 486 | author: { id: 456 }, 487 | channel: { id: channelId }, 488 | isMentioned: () => false, 489 | }; 490 | 491 | bot.onMessage(message); 492 | 493 | expect(mockMessageHandler.mock.calls.length).toBe(0); 494 | }); 495 | 496 | describe('it should attempt to interpret the message as a command if the first character is the `COMMAND_PREFIX`', () => { 497 | it('should return the `UNKNOWN_COMMAND` message to the channel if the command was unknown', () => { 498 | const channelId = 'test-channel'; 499 | const mockMessageHandler = jest.fn(); 500 | 501 | const bot = new MusicBot({}); 502 | bot.messageHandler = mockMessageHandler; 503 | bot.client = { user: { id: 123 } }; 504 | bot.setState({ activeTextChannelId: channelId }); 505 | 506 | const message = { 507 | author: { id: 456 }, 508 | channel: { id: channelId }, 509 | content: '!unknownCommand', 510 | isMentioned: () => false, 511 | }; 512 | 513 | bot.onMessage(message); 514 | 515 | expect(mockMessageHandler.mock.calls[0][1]).toBe('UNKNOWN_COMMAND'); 516 | }); 517 | 518 | it("should call the command handler with the command's alias, args and the message", () => { 519 | const channelId = 'test-channel'; 520 | const mockCommandHandler = jest.fn(); 521 | 522 | const bot = new MusicBot({}); 523 | bot.commandHandler = mockCommandHandler; 524 | bot.client = { user: { id: 123 } }; 525 | bot.setState({ activeTextChannelId: channelId }); 526 | 527 | const message = { 528 | author: { id: 456 }, 529 | channel: { id: channelId }, 530 | content: '!help arg1', 531 | isMentioned: () => false, 532 | }; 533 | 534 | bot.onMessage(message); 535 | 536 | expect(mockCommandHandler.mock.calls[0][0]).toBe('help_command'); 537 | expect(mockCommandHandler.mock.calls[0][1][0]).toBe('arg1'); 538 | expect(mockCommandHandler.mock.calls[0][2]).toEqual(message); 539 | }); 540 | }); 541 | }); 542 | 543 | describe('onDisconnect()', () => { 544 | it('calls the logger to log an error message to the console', () => { 545 | const spy = jest.spyOn(global.console, 'error'); 546 | 547 | const error = { reason: 'testing', code: 0 }; 548 | const bot = new MusicBot({}); 549 | 550 | try { 551 | bot.onDisconnect(error); 552 | } catch (e) {} // eslint-disable-line 553 | 554 | expect(spy.mock.calls[0][1]).toBe( 555 | `Bot was disconnected from server.\nReason: ${error.reason}\nCode: ${error.code}`, 556 | ); 557 | 558 | spy.mockReset(); 559 | spy.mockRestore(); 560 | }); 561 | 562 | it('throws an Error when disconnected', () => { 563 | const error = { reason: 'testing', code: 0 }; 564 | const bot = new MusicBot({}); 565 | 566 | let result; 567 | 568 | try { 569 | bot.onDisconnect(error); 570 | } catch (e) { 571 | result = e; 572 | } 573 | 574 | expect(result.message).toBe('Bot was disconnected from server.'); 575 | }); 576 | }); 577 | 578 | describe('run()', () => { 579 | it('throws an Error if a `token` is not provided', () => { 580 | const bot = new MusicBot({}); 581 | 582 | let result; 583 | 584 | try { 585 | bot.run(); 586 | } catch (e) { 587 | result = e; 588 | } 589 | 590 | expect(result.message).toBe("Failed to initialise: a 'token' was not provided in the config!"); 591 | }); 592 | 593 | it('throws an Error if a `serverId` is not provided', () => { 594 | const bot = new MusicBot({ token: 'abc' }); 595 | 596 | let result; 597 | 598 | try { 599 | bot.run(); 600 | } catch (e) { 601 | result = e; 602 | } 603 | 604 | expect(result.message).toBe("Failed to initialise: a 'serverId' was not provided in the config!"); 605 | }); 606 | 607 | it('throws an Error if a `textChannelId` is not provided', () => { 608 | const bot = new MusicBot({ token: 'abc', serverId: 'def' }); 609 | 610 | let result; 611 | 612 | try { 613 | bot.run(); 614 | } catch (e) { 615 | result = e; 616 | } 617 | 618 | expect(result.message).toBe("Failed to initialise: a 'textChannelId' was not provided in the config!"); 619 | }); 620 | 621 | it('registers the listener functions', () => { 622 | const bot = new MusicBot({ token: 'abc', serverId: 'def', textChannelId: 'ghi' }); 623 | 624 | const mockFn = jest.fn(); 625 | bot.client.on = mockFn; 626 | 627 | bot.run(); 628 | 629 | expect(mockFn.mock.calls[0][0]).toBe('ready'); 630 | expect(mockFn.mock.calls[0][1]).toBeInstanceOf(Function); 631 | 632 | expect(mockFn.mock.calls[1][0]).toBe('message'); 633 | expect(mockFn.mock.calls[1][1]).toBeInstanceOf(Function); 634 | 635 | expect(mockFn.mock.calls[2][0]).toBe('disconnect'); 636 | expect(mockFn.mock.calls[2][1]).toBeInstanceOf(Function); 637 | }); 638 | 639 | it('calls `bot.login` if all is well', () => { 640 | const token = 'abc'; 641 | const bot = new MusicBot({ token, serverId: 'def', textChannelId: 'ghi' }); 642 | 643 | const mockFn = jest.fn(); 644 | bot.client.login = mockFn; 645 | 646 | bot.run(); 647 | 648 | expect(mockFn.mock.calls.length).toBe(1); 649 | expect(mockFn.mock.calls[0][0]).toBe(token); 650 | }); 651 | }); 652 | }); 653 | -------------------------------------------------------------------------------- /src/util.js: -------------------------------------------------------------------------------- 1 | const dateFormat = require('dateformat'); 2 | 3 | const findCommandKeyByAlias = (commandDetails, givenAlias) => { 4 | let commandKey = null; 5 | 6 | Object.keys(commandDetails).forEach(key => { 7 | if (commandDetails[key].aliases.includes(givenAlias.toLowerCase())) { 8 | commandKey = key; 9 | return; // eslint-disable-line no-useless-return 10 | } 11 | }); 12 | 13 | return commandKey; 14 | }; 15 | 16 | const getLoggerPrefix = level => { 17 | const time = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss:l'); 18 | return `[${time}] (${level.toUpperCase()})`; 19 | }; 20 | 21 | module.exports = { 22 | findCommandKeyByAlias, 23 | getLoggerPrefix, 24 | }; 25 | -------------------------------------------------------------------------------- /src/util.test.js: -------------------------------------------------------------------------------- 1 | const { findCommandKeyByAlias } = require('./util'); 2 | 3 | describe('Utilities', () => { 4 | describe('findCommandKeyByAlias()', () => { 5 | it('returns null when an unknown command key is given', () => { 6 | expect(findCommandKeyByAlias({ def: { aliases: ['def'] } }, 'abc')).toBe(null); 7 | }); 8 | 9 | it('returns the correct command key when a valid alias is given', () => { 10 | expect(findCommandKeyByAlias({ help_key: { aliases: ['help'] } }, 'help')).toBe('help_key'); 11 | }); 12 | 13 | it('returns the correct command key when a valid uppercase alias is given', () => { 14 | expect(findCommandKeyByAlias({ help_key: { aliases: ['help'] } }, 'HELP')).toBe('help_key'); 15 | }); 16 | }); 17 | 18 | xdescribe('getLoggerPrefix()', () => { 19 | it('returns the logger prefix', () => {}); 20 | }); 21 | }); 22 | --------------------------------------------------------------------------------