commit 5a6670befee6db8744ae3508227f14ece9fabcfc Author: Elara Musayelyan Date: Mon Dec 4 15:55:01 2023 -0800 Initial Commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cc40972 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/owobot +/owobot.db \ No newline at end of file diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..16cd036 --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,72 @@ +before: + hooks: + - go mod tidy +builds: + - id: owobot + env: + - CGO_ENABLED=0 + binary: owobot + goos: + - linux + goarch: + - amd64 + - 386 + - arm64 + - arm + - riscv64 +archives: + - files: + - scripts/completion/* +nfpms: + - id: owobot + description: "The coolest bot ever written" + homepage: 'https://gitea.elara.ws/owobot/owobot' + maintainer: 'Elara Musayelyan ' + license: AGPLv3 + formats: + - deb + - rpm + - archlinux + provides: + - owobot + conflicts: + - owobot + contents: + - src: scripts/completion/bash + dst: /usr/share/bash-completion/completions/lure +aurs: + - name: owobot-bin + homepage: 'https://gitea.elara.ws/owobot/owobot' + description: "The coolest bot ever written" + maintainers: + - 'Elara Musayelyan ' + license: GPLv3 + private_key: '{{ .Env.AUR_KEY }}' + git_url: 'ssh://aur@aur.archlinux.org/owobot-bin.git' + provides: + - owobot + conflicts: + - owobot + package: |- + # binaries + install -Dm755 ./owobot "${pkgdir}/usr/bin/owobot" + + # services + # TODO +release: + gitea: + owner: owobot + name: owobot +announce: + discord: + enabled: true +gitea_urls: + api: 'https://gitea.elara.ws/api/v1/' + download: 'https://gitea.elara.ws' + skip_tls_verify: false +checksum: + name_template: 'checksums.txt' +snapshot: + name_template: "{{ incpatch .Version }}-next" +changelog: + sort: asc \ No newline at end of file diff --git a/.woodpecker.yml b/.woodpecker.yml new file mode 100644 index 0000000..476587a --- /dev/null +++ b/.woodpecker.yml @@ -0,0 +1,23 @@ +platform: linux/amd64 +steps: + docker: + image: gitea.elara.ws/elara6331/builder + environment: + - REGISTRY=gitea.elara.ws + - REGISTRY_USERNAME=Elara6331 + - KO_DOCKER_REPO=gitea.elara.ws/owobot + - KO_DEFAULTBASEIMAGE=gitea.elara.ws/elara6331/static + secrets: [ registry_password ] + commands: + - registry-login + - ko build -B --platform=linux/amd64,linux/arm64,linux/riscv64 --sbom=none + when: + event: tag + + release: + image: goreleaser/goreleaser + commands: + - goreleaser release + secrets: [ gitea_token, aur_key, discord_webhook_id, discord_webhook_token ] + when: + event: tag \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c691148 --- /dev/null +++ b/README.md @@ -0,0 +1,107 @@ +# owobot - The coolest bot ever written + +## Introduction + +owobot is a powerful Discord bot designed to handle a wide range of tasks in your server, from moderation to entertainment. It takes advantage of several cutting-edge discord features, such as message buttons and modals. + +## Features + +### Vetting + +In order to catch trolls and other troublemakers before they get access to your server, owobot can be configured to require new users to go through a vetting process before gaining access to the server. + +To create your vetting message, just choose any message, click `More > Apps > Make Vetting Message`, and that's it! owobot will delete the message and post a new one with a message button which can be used by users to request vetting. + +When users click the request vetting button, owobot will send a vetting request in the vetting request channel. + +If a moderator accepts the request, a new ticket will be created in which mods can talk to the user. When they're finished, they can either kick the user which will automatically close the ticket, or they can approve the user using the `/approve` command. + +Commands: + +- `/vetting role` can be used by anyone with the `Manage Server` permission to set the server's vetting role. owobot will assign this role to all new users. +- `/vetting req_channel` can be used by anyone with the `Manage Server` permission to set the server's vetting request channel. This is where owobot will post vetting requests. +- `/approve` can be used by anyone with the `Kick Members` permission to approve users that are in vetting. + +### Tickets + +owobot can create tickets to allow users to privately talk to your server's moderators. Only one ticket per user can exist at any time. When a ticket is closed, a log containing all the messages in the ticket is sent to the event log ticket channel. + +Commands: + +- `/ticket` can be used by any user to create a ticket for themselves +- `/mod_ticket` can be used by anyone with the `Manage Channels` permission to create a ticket for another user +- `/close_ticket` can be used by anyone with the `Manage Channels` permission to close a user's ticket +- `/ticket_category` can be used by anyone with the `Manage Server` permission to set the category in which ticket channels are created. + +### Eventlog + +The eventlog sends important events such as kicks/bans, role changes, etc. to a configurable discord channel. + +Commands: + +- `/eventlog channel` can be used by anyone with the `Manage Server` permission to set the channel for the event log +- `/eventlog ticket_channel` can be used by anyone with the `Manage Server` permission to set the channel in which ticket conversations logs will be sent + +### Reactions + +owobot has a very powerful reaction system which can find content inside of messages and then react with an emoji or reply with text. + +A single reaction consists of a match type, match, reaction type, reaction, and an optional random chance. + +The match type can either be `contains` or `regex`. The `contains` matcher checks if a message contains the match. The `regex` matcher checks if a message matches a regular expression and extracts any submatches. If you're using the `regex` matcher with the `text` reaction type, you can include submatches in your reply by putting the submatch index in curly braces (for example: `{1}` or `{5}`). + +The optional random chance allows you to add reactions that only occur a certain percentage of the time. Setting it to `10`, for example, means the reaction will only happen in 10% of detected messages. + +Commands: + +- `/reactions add` can be used by anyone with the `Manage Expressions` permission to add new reactions +- `/reactions list` can be used by anyone with the `Manage Expressions` permission to get a list of all existing reactions +- `/reactions delete` can be used by anyone with the `Manage Expressions` permission to delete an existing reaction + +> [!NOTE] +> The `/reactions delete` command has an extra check to make sure the user has `Manage Expressions`, so you can safely add a role override on the `/reactions` command without allowing anyone without that permission to delete reactions. + +### Reaction Roles + +Reaction roles allow users to easily assign roles to themselves using message buttons. + +Reaction roles are organized in categories, which can have a name and a description. You can't have more than one category with the same name in a given channel. + +Commands: + +- `/reaction_roles new_category` can be used by anyone with the `Manage Server` permission to create a new reaction role category in the current channel +- `/reaction_roles remove_category` can be used by anyone with the `Manage Server` permission to remove an existing reaction role category from the current channel +- `/reaction_roles add` can be used by anyone with the `Manage Server` permission to add a reaction role to a category +- `/reaction_roles remove` can be used by anyone with the `Manage Server` permission to remove an existing reaction role from a category + +> [!TIP] +> There's a `/neopronoun` command that any user can use to assign themselves a pronoun role. It will never assign a role that provides any permissions, so it's safe to allow for everyone. + +### Polls + +owobot can easily create polls for your members to vote in. Polls use message components and privacy tokens to ensure that votes are always private and even the person running the bot can't find out who voted for what. + +A poll can be created using the `/poll` command. owobot will create a message with just the title and two buttons: `Add Options` and `Finish`. Clicking the `Add Options` button opens a modal (pop up) where you can type the text for a new option. Once that's done, owobot edits the message and asks the poll owner to react with the emoji they'd like to use for that poll. Once they react, that option is added. Options can keep being added until the Finish button is clicked, which finalizes the poll, creates a thread, and opens it up to votes. + +Commands: + +- `/poll` can be used by any user to create a poll + +### Starboard + +The starboard is a way for your users to feature the messages they like. Users can react to messages with stars, and once a configurable threshold of stars is reached, the message will be posted to the starboard channel. + +Commands: + +- `/starboard stars` can be used by anyone with the `Manage Server` permission to set the star reaction threshold for the starboard (The default is 3) +- `/starboard channel` can be used by anyone with the `Manage Server` permission to set the starboard channel for the server. + +### Rate Limiting + +owobot will rate limit events such as channel deletions, kicks, and bans, ensuring that compromised mod accounts can't destroy the server. If a user gets near the rate limit, they'll receive two warnings and then they'll be kicked from the server. + +Here are the current rate limits: + +- `channel_delete`: 10 / minute +- `kick`: 10 / minute +- `ban`: 7 / 5 minutes \ No newline at end of file diff --git a/config.go b/config.go new file mode 100644 index 0000000..cdcc96c --- /dev/null +++ b/config.go @@ -0,0 +1,40 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package main + +import ( + "github.com/bwmarrin/discordgo" + "github.com/caarlos0/env/v10" +) + +type Config struct { + Token string `env:"TOKEN,notEmpty"` + DBPath string `env:"DB_PATH" envDefault:"owobot.db"` + Activity Activity `envPrefix:"ACTIVITY_"` +} + +type Activity struct { + Type discordgo.ActivityType `env:"TYPE" envDefault:"-1"` + Name string `env:"NAME" envDefault:""` +} + +func loadEnv() (*Config, error) { + cfg := &Config{} + return cfg, env.ParseWithOptions(cfg, env.Options{Prefix: "OWOBOT_"}) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a922fc4 --- /dev/null +++ b/go.mod @@ -0,0 +1,41 @@ +module go.elara.ws/owobot + +go 1.21.3 + +require ( + github.com/bwmarrin/discordgo v0.27.1 + github.com/caarlos0/env/v10 v10.0.0 + github.com/jmoiron/sqlx v1.3.5 + github.com/rivo/uniseg v0.4.4 + github.com/valyala/fasttemplate v1.2.2 + go.elara.ws/logger v0.0.0-20230928062203-85e135cf02ae + modernc.org/sqlite v1.27.0 + mvdan.cc/xurls v1.1.0 +) + +require ( + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/gookit/color v1.5.1 // indirect + github.com/gorilla/websocket v1.4.2 // indirect + github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect + github.com/mattn/go-isatty v0.0.17 // indirect + github.com/mvdan/xurls v1.1.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/stretchr/testify v1.8.1 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect + golang.org/x/crypto v0.5.0 // indirect + golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect + golang.org/x/sys v0.9.0 // indirect + golang.org/x/tools v0.1.12 // indirect + lukechampine.com/uint128 v1.2.0 // indirect + modernc.org/cc/v3 v3.40.0 // indirect + modernc.org/ccgo/v3 v3.16.13 // indirect + modernc.org/libc v1.29.0 // indirect + modernc.org/mathutil v1.6.0 // indirect + modernc.org/memory v1.7.2 // indirect + modernc.org/opt v0.1.3 // indirect + modernc.org/strutil v1.1.3 // indirect + modernc.org/token v1.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..6dae775 --- /dev/null +++ b/go.sum @@ -0,0 +1,106 @@ +github.com/bwmarrin/discordgo v0.27.1 h1:ib9AIc/dom1E/fSIulrBwnez0CToJE113ZGt4HoliGY= +github.com/bwmarrin/discordgo v0.27.1/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0kIVMCHkZtRY= +github.com/caarlos0/env/v10 v10.0.0 h1:yIHUBZGsyqCnpTkbjk8asUlx6RFhhEs+h7TOBdgdzXA= +github.com/caarlos0/env/v10 v10.0.0/go.mod h1:ZfulV76NvVPw3tm591U4SwL3Xx9ldzBP9aGxzeN7G18= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= +github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= +github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gookit/color v1.5.1 h1:Vjg2VEcdHpwq+oY63s/ksHrgJYCTo0bwWvmmYWdE9fQ= +github.com/gookit/color v1.5.1/go.mod h1:wZFzea4X8qN6vHOSP2apMb4/+w/orMznEzYsIHPaqKM= +github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g= +github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ= +github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= +github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= +github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0= +github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= +github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= +github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y= +github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= +github.com/mvdan/xurls v1.1.0 h1:OpuDelGQ1R1ueQ6sSryzi6P+1RtBpfQHM8fJwlE45ww= +github.com/mvdan/xurls v1.1.0/go.mod h1:tQlNn3BED8bE/15hnSL2HLkDeLWpNPAwtw7wkEq44oU= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= +github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= +github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 h1:QldyIu/L63oPpyvQmHgvgickp1Yw510KJOqX7H24mg8= +github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs= +go.elara.ws/logger v0.0.0-20230928062203-85e135cf02ae h1:d+gJUhEWSrOjrrfgeydYWEr8TTnx0DLvcVhghaOsFeE= +go.elara.ws/logger v0.0.0-20230928062203-85e135cf02ae/go.mod h1:qng49owViqsW5Aey93lwBXONw20oGbJIoLVscB16mPM= +golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE= +golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s= +golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI= +lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= +modernc.org/cc/v3 v3.40.0 h1:P3g79IUS/93SYhtoeaHW+kRCIrYaxJ27MFPv+7kaTOw= +modernc.org/cc/v3 v3.40.0/go.mod h1:/bTg4dnWkSXowUO6ssQKnOV0yMVxDYNIsIrzqTFDGH0= +modernc.org/ccgo/v3 v3.16.13 h1:Mkgdzl46i5F/CNR/Kj80Ri59hC8TKAhZrYSaqvkwzUw= +modernc.org/ccgo/v3 v3.16.13/go.mod h1:2Quk+5YgpImhPjv2Qsob1DnZ/4som1lJTodubIcoUkY= +modernc.org/ccorpus v1.11.6 h1:J16RXiiqiCgua6+ZvQot4yUuUy8zxgqbqEEUuGPlISk= +modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ= +modernc.org/httpfs v1.0.6 h1:AAgIpFZRXuYnkjftxTAZwMIiwEqAfk8aVB2/oA6nAeM= +modernc.org/httpfs v1.0.6/go.mod h1:7dosgurJGp0sPaRanU53W4xZYKh14wfzX420oZADeHM= +modernc.org/libc v1.29.0 h1:tTFRFq69YKCF2QyGNuRUQxKBm1uZZLubf6Cjh/pVHXs= +modernc.org/libc v1.29.0/go.mod h1:DaG/4Q3LRRdqpiLyP0C2m1B8ZMGkQ+cCgOIjEtQlYhQ= +modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= +modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= +modernc.org/memory v1.7.2 h1:Klh90S215mmH8c9gO98QxQFsY+W451E8AnzjoE2ee1E= +modernc.org/memory v1.7.2/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E= +modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= +modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= +modernc.org/sqlite v1.27.0 h1:MpKAHoyYB7xqcwnUwkuD+npwEa0fojF0B5QRbN+auJ8= +modernc.org/sqlite v1.27.0/go.mod h1:Qxpazz0zH8Z1xCFyi5GSL3FzbtZ3fvbjmywNogldEW0= +modernc.org/strutil v1.1.3 h1:fNMm+oJklMGYfU9Ylcywl0CO5O6nTfaowNsh2wpPjzY= +modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw= +modernc.org/tcl v1.15.2 h1:C4ybAYCGJw968e+Me18oW55kD/FexcHbqH2xak1ROSY= +modernc.org/tcl v1.15.2/go.mod h1:3+k/ZaEbKrC8ePv8zJWPtBSW0V7Gg9g8rkmhI1Kfs3c= +modernc.org/token v1.0.1 h1:A3qvTqOwexpfZZeyI0FeGPDlSWX5pjZu9hF4lU+EKWg= +modernc.org/token v1.0.1/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= +modernc.org/z v1.7.3 h1:zDJf6iHjrnB+WRD88stbXokugjyc0/pB91ri1gO6LZY= +modernc.org/z v1.7.3/go.mod h1:Ipv4tsdxZRbQyLq9Q1M6gdbkxYzdlrciF2Hi/lS7nWE= +mvdan.cc/xurls v1.1.0 h1:kj0j2lonKseISJCiq1Tfk+iTv65dDGCl0rTbanXJGGc= +mvdan.cc/xurls v1.1.0/go.mod h1:TNWuhvo+IqbUCmtUIb/3LJSQdrzel8loVpgFm0HikbI= diff --git a/internal/cache/cache.go b/internal/cache/cache.go new file mode 100644 index 0000000..a226113 --- /dev/null +++ b/internal/cache/cache.go @@ -0,0 +1,89 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package cache + +import ( + "errors" + + "github.com/bwmarrin/discordgo" +) + +// Member gets a discord member from the cache. If it doesn't exist in the cache, it +// gets it from discord and adds it to the cache. +func Member(s *discordgo.Session, guildID, userID string) (*discordgo.Member, error) { + member, err := s.State.Member(guildID, userID) + if errors.Is(err, discordgo.ErrStateNotFound) { + // If the member wasn't found in the state struct, + // get the member from discord and add it. + member, err = s.GuildMember(guildID, userID) + if err != nil { + return nil, err + } + return member, s.State.MemberAdd(member) + } else if err != nil { + return nil, err + } + return member, nil +} + +// Role gets a discord role from the cache. If it doesn't exist in the cache, it +// gets it from discord and adds it to the cache. +func Role(s *discordgo.Session, guildID, roleID string) (*discordgo.Role, error) { + role, err := s.State.Role(guildID, roleID) + if errors.Is(err, discordgo.ErrStateNotFound) { + // If the role wasn't found in the state struct, + // get the guild roles from discord and add them. + roles, err := s.GuildRoles(guildID) + if err != nil { + return nil, err + } + for _, role := range roles { + err = s.State.RoleAdd(guildID, role) + if err != nil { + return nil, err + } + } + return s.State.Role(guildID, roleID) + } else if err != nil { + return nil, err + } + return role, nil +} + +// Roles gets a list of roles in a discord guild from the cache. If it doesn't +// exist in the cache, it gets it from discord and adds it to the cache. +func Roles(s *discordgo.Session, guildID string) ([]*discordgo.Role, error) { + guild, err := s.State.Guild(guildID) + if errors.Is(err, discordgo.ErrStateNotFound) { + return s.GuildRoles(guildID) + } else if err != nil { + return nil, err + } + + if len(guild.Roles) == 0 { + roles, err := s.GuildRoles(guildID) + if err != nil { + return nil, err + } + guild.Roles = roles + return roles, nil + } + + return guild.Roles, nil +} diff --git a/internal/cache/regex.go b/internal/cache/regex.go new file mode 100644 index 0000000..e0b031f --- /dev/null +++ b/internal/cache/regex.go @@ -0,0 +1,49 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package cache + +import ( + "regexp" + "sync" +) + +var ( + regexMtx = sync.RWMutex{} + regexes = map[string]*regexp.Regexp{} +) + +func Regex(regex string) (*regexp.Regexp, error) { + regexMtx.RLock() + if re, ok := regexes[regex]; ok { + regexMtx.RUnlock() + return re, nil + } + regexMtx.RUnlock() + + re, err := regexp.Compile(regex) + if err != nil { + return nil, err + } + + regexMtx.Lock() + regexes[regex] = re + regexMtx.Unlock() + + return re, nil +} diff --git a/internal/db/db.go b/internal/db/db.go new file mode 100644 index 0000000..5b33d17 --- /dev/null +++ b/internal/db/db.go @@ -0,0 +1,109 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package db + +import ( + "context" + "embed" + "io" + "io/fs" + "path/filepath" + + "github.com/jmoiron/sqlx" + _ "modernc.org/sqlite" +) + +//go:embed migrations +var migrations embed.FS + +var db *sqlx.DB + +// Init opens the database and applies migrations +func Init(ctx context.Context, dsn string) error { + g, err := sqlx.Open("sqlite", dsn) + if err != nil { + return err + } + db = g + return migrate(ctx, db) +} + +func Close() error { + return db.Close() +} + +// version returns the current version of the database. +func version(ctx context.Context, db *sqlx.DB) string { + var out string + row := db.QueryRowxContext(ctx, "SELECT current FROM version") + _ = row.Scan(&out) + if out == "" { + out = "0.sql" + } + return out +} + +// migrate applies database migrations using the embedded sql files. +func migrate(ctx context.Context, db *sqlx.DB) error { + current := version(ctx, db) + return fs.WalkDir(migrations, "migrations", func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + + // If the file is a directory, is not an sql file, or is not newer than current, + // skip it. + if d.IsDir() || filepath.Ext(path) != ".sql" || d.Name() <= current { + return nil + } + + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + + // Open the sql file containing the migration code + fl, err := migrations.Open(path) + if err != nil { + return err + } + defer fl.Close() + + // Read the file + data, err := io.ReadAll(fl) + if err != nil { + return err + } + + // Execute the migration + _, err = tx.ExecContext(ctx, string(data)) + if err != nil { + return err + } + + // Update the version number + _, err = tx.ExecContext(ctx, "DELETE FROM version; INSERT INTO version VALUES (?)", d.Name()) + if err != nil { + return err + } + + return tx.Commit() + }) +} diff --git a/internal/db/guilds.go b/internal/db/guilds.go new file mode 100644 index 0000000..4cab7c5 --- /dev/null +++ b/internal/db/guilds.go @@ -0,0 +1,98 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package db + +import ( + "database/sql" + "errors" +) + +type Guild struct { + ID string `db:"id"` + StarboardChanID string `db:"starboard_chan_id"` + StarboardStars int `db:"starboard_stars"` + LogChanID string `db:"log_chan_id"` + TicketLogChanID string `db:"ticket_log_chan_id"` + TicketCategoryID string `db:"ticket_category_id"` + VettingReqChanID string `db:"vetting_req_chan_id"` + VettingRoleID string `db:"vetting_role_id"` +} + +func AllGuilds() ([]Guild, error) { + var out []Guild + err := db.Select(&out, "SELECT * FROM guilds") + return out, err +} + +func GuildByID(id string) (Guild, error) { + var out Guild + err := db.QueryRowx("SELECT * FROM guilds WHERE id = ? LIMIT 1", id).StructScan(&out) + return out, err +} + +func CreateGuild(guildID string) error { + _, err := db.Exec(`INSERT OR IGNORE INTO guilds (id) VALUES (?)`, guildID) + return err +} + +func SetStarboardChannel(guildID, channelID string) error { + _, err := db.Exec("UPDATE guilds SET starboard_chan_id = ? WHERE id = ?", channelID, guildID) + return err +} + +func SetStarboardStars(guildID string, stars int64) error { + _, err := db.Exec("UPDATE guilds SET starboard_stars = ? WHERE id = ?", stars, guildID) + return err +} + +func SetLogChannel(guildID, channelID string) error { + _, err := db.Exec("UPDATE guilds SET log_chan_id = ? WHERE id = ?", channelID, guildID) + return err +} + +func SetTicketLogChannel(guildID, channelID string) error { + _, err := db.Exec("UPDATE guilds SET ticket_log_chan_id = ? WHERE id = ?", channelID, guildID) + return err +} + +func SetTicketCategory(guildID, categoryID string) error { + _, err := db.Exec("UPDATE guilds SET ticket_category_id = ? WHERE id = ?", categoryID, guildID) + return err +} + +func SetVettingReqChannel(guildID, channelID string) error { + _, err := db.Exec("UPDATE guilds SET vetting_req_chan_id = ? WHERE id = ?", channelID, guildID) + return err +} + +func SetVettingRoleID(guildID, roleID string) error { + _, err := db.Exec("UPDATE guilds SET vetting_role_id = ? WHERE id = ?", roleID, guildID) + return err +} + +func IsVettingMsg(msgID string) (bool, error) { + var out bool + err := db.QueryRow("SELECT 1 FROM guild WHERE vetting_msg_id = ?", msgID).Scan(&out) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } else if err != nil { + return false, err + } + return true, nil +} diff --git a/internal/db/migrations/20231204.sql b/internal/db/migrations/20231204.sql new file mode 100644 index 0000000..7a56366 --- /dev/null +++ b/internal/db/migrations/20231204.sql @@ -0,0 +1,82 @@ +/* version holds the current database version for migrations */ +CREATE TABLE version ( + current TEXT NOT NULL +); + +/* guilds holds all the guilds this bot is in and their settings */ +CREATE TABLE guilds ( + id TEXT PRIMARY KEY, + starboard_chan_id TEXT NOT NULL DEFAULT '', + starboard_stars INT NOT NULL DEFAULT 3, + log_chan_id TEXT NOT NULL DEFAULT '', + ticket_log_chan_id TEXT NOT NULL DEFAULT '', + ticket_category_id TEXT NOT NULL DEFAULT '', + vetting_req_chan_id TEXT NOT NULL DEFAULT '', + vetting_role_id TEXT NOT NULL DEFAULT '' +); + +/* tickets holds all open tickets */ +CREATE TABLE tickets ( + user_id TEXT PRIMARY KEY, + guild_id TEXT NOT NULL DEFAULT '', + channel_id TEXT UNIQUE, + UNIQUE(user_id, guild_id) +); + +/* vetting_requests holds all open vetting requests */ +CREATE TABLE vetting_requests ( + user_id TEXT PRIMARY KEY, + guild_id TEXT NOT NULL DEFAULT '', + msg_id TEXT UNIQUE, + UNIQUE(user_id, guild_id) +); + +/* starboard holds all the messages that have been added to the starboard */ +CREATE TABLE starboard ( + id TEXT PRIMARY KEY +); + +/* polls holds all the poll messages created by the bot and their state */ +CREATE TABLE polls ( + msg_id TEXT PRIMARY KEY, + owner_id TEXT NOT NULL, + title TEXT NOT NULL, + finished BOOL NOT NULL DEFAULT false, + opt_emojis TEXT NOT NULL DEFAULT '', + opt_text TEXT NOT NULL DEFAULT '' +); + +/* votes holds all the poll votes */ +CREATE TABLE votes ( + poll_msg_id TEXT NOT NULL, + user_token TEXT NOT NULL, + option INT NOT NULL, + UNIQUE(poll_msg_id, user_token) ON CONFLICT REPLACE +); + +CREATE INDEX idx_votes_option ON votes(option); +CREATE INDEX idx_votes_poll_msg_id ON votes(poll_msg_id); + +/* reactions holds all the message reactions */ +CREATE TABLE reactions ( + guild_id TEXT NOT NULL, + match_type TEXT NOT NULL, + match TEXT NOT NULL, + reaction_type TEXT NOT NULL, + reaction TEXT NOT NULL, + chance INT NOT NULL CHECK (chance >= 1 AND chance <= 100) DEFAULT 100 +); + +CREATE INDEX idx_reactions_guild_id ON reactions(guild_id); +CREATE INDEX idx_reactions_match ON reactions(match); + +/* reaction_role_categories holds the reaction roles */ +CREATE TABLE reaction_role_categories ( + msg_id TEXT PRIMARY KEY, + channel_id TEXT NOT NULL, + name TEXT NOT NULL, + description TEXT NOT NULL, + emoji TEXT NOT NULL, + roles TEXT NOT NULL, + UNIQUE(channel_id, name) +); \ No newline at end of file diff --git a/internal/db/polls.go b/internal/db/polls.go new file mode 100644 index 0000000..5ff8694 --- /dev/null +++ b/internal/db/polls.go @@ -0,0 +1,123 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package db + +import ( + "errors" + "slices" + "strings" +) + +type Poll struct { + MsgID string + OwnerID string + Title string + Finished bool + OptionEmojis []string + OptionText []string +} + +func CreatePoll(msgID, ownerID, title string) error { + _, err := db.Exec("INSERT INTO polls(msg_id, owner_id, title) VALUES (?, ?, ?)", msgID, ownerID, title) + return err +} + +func GetPoll(msgID string) (*Poll, error) { + var title, ownerID, emojis, text string + var finished bool + err := db.QueryRow("SELECT title, owner_id, finished, opt_emojis, opt_text FROM polls WHERE msg_id = ?", msgID).Scan(&title, &ownerID, &finished, &emojis, &text) + if err != nil { + return nil, err + } + return &Poll{ + MsgID: msgID, + OwnerID: ownerID, + Title: title, + Finished: finished, + OptionEmojis: splitOptions(emojis), + OptionText: splitOptions(text), + }, nil +} + +func AddPollOptionText(msgID string, text string) error { + var optText string + err := db.QueryRow("SELECT opt_text FROM polls WHERE msg_id = ?", msgID).Scan(&optText) + if err != nil { + return err + } + + splitText := splitOptions(optText) + splitText = append(splitText, text) + + _, err = db.Exec("UPDATE polls SET opt_text = ? WHERE msg_id = ?", strings.Join(splitText, ","), msgID) + return err +} + +func AddPollOptionEmoji(msgID string, emoji string) error { + var optEmojis string + err := db.QueryRow("SELECT opt_emojis FROM polls WHERE msg_id = ?", msgID).Scan(&optEmojis) + if err != nil { + return err + } + + splitEmojis := splitOptions(optEmojis) + if slices.Contains(splitEmojis, emoji) { + return errors.New("emojis can only be used once") + } + splitEmojis = append(splitEmojis, emoji) + + _, err = db.Exec("UPDATE polls SET opt_emojis = ? WHERE msg_id = ?", strings.Join(splitEmojis, ","), msgID) + return err +} + +func FinishPoll(msgID string) error { + _, err := db.Exec("UPDATE polls SET finished = true WHERE msg_id = ?", msgID) + return err +} + +type Vote struct { + PollMsgID string `db:"poll_msg_id"` + UserToken string `db:"user_token"` + Option int `db:"option"` +} + +func UserVote(msgID, userToken string) (Vote, error) { + var out Vote + row := db.QueryRowx("SELECT * FROM votes WHERE poll_msg_id = ? AND user_token = ?", msgID, userToken) + err := row.StructScan(&out) + return out, err +} + +func AddVote(v Vote) error { + _, err := db.NamedExec("INSERT OR REPLACE INTO votes (poll_msg_id, user_token, option) VALUES (:poll_msg_id, :user_token, :option)", v) + return err +} + +func VoteAmount(msgID string, option int) (int64, error) { + var out int64 + err := db.QueryRow("SELECT COUNT(1) FROM votes WHERE poll_msg_id = ? AND option = ?", msgID, option).Scan(&out) + return out, err +} + +func splitOptions(s string) []string { + if s == "" { + return nil + } + return strings.Split(s, ",") +} diff --git a/internal/db/reactions.go b/internal/db/reactions.go new file mode 100644 index 0000000..ae30a79 --- /dev/null +++ b/internal/db/reactions.go @@ -0,0 +1,58 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package db + +type MatchType string + +const ( + MatchTypeRegex MatchType = "regex" + MatchTypeContains MatchType = "contains" +) + +type ReactionType string + +const ( + ReactionTypeEmoji ReactionType = "emoji" + ReactionTypeText ReactionType = "text" +) + +type Reaction struct { + GuildID string `db:"guild_id"` + MatchType MatchType `db:"match_type"` + Match string `db:"match"` + ReactionType ReactionType `db:"reaction_type"` + Reaction string `db:"reaction"` + Chance int `db:"chance"` +} + +func AddReaction(guildID string, r Reaction) error { + r.GuildID = guildID + _, err := db.NamedExec("INSERT INTO reactions VALUES (:guild_id, :match_type, :match, :reaction_type, :reaction, :chance)", r) + return err +} + +func DeleteReaction(guildID string, match string) error { + _, err := db.Exec("DELETE FROM reactions WHERE guild_id = ? AND match = ? LIMIT 1", guildID, match) + return err +} + +func Reactions(guildID string) (rs []Reaction, err error) { + err = db.Select(&rs, "SELECT * FROM reactions WHERE guild_id = ?", guildID) + return rs, err +} diff --git a/internal/db/roles.go b/internal/db/roles.go new file mode 100644 index 0000000..2d71c2c --- /dev/null +++ b/internal/db/roles.go @@ -0,0 +1,120 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package db + +import ( + "slices" + "strings" + + "github.com/bwmarrin/discordgo" +) + +type ReactionRoleCategory struct { + MsgID string `db:"msg_id"` + ChannelID string `db:"channel_id"` + Name string `db:"name"` + Description string `db:"description"` + Emoji []string `db:"emoji"` + Roles []string `db:"roles"` +} + +func AddReactionRoleCategory(channelID string, rrc ReactionRoleCategory) error { + _, err := db.Exec( + "INSERT INTO reaction_role_categories VALUES (?, ?, ?, ?, ?, ?)", + rrc.MsgID, + channelID, + rrc.Name, + rrc.Description, + strings.Join(rrc.Emoji, ","), + strings.Join(rrc.Roles, ","), + ) + return err +} + +func GetReactionRoleCategory(channelID, name string) (*ReactionRoleCategory, error) { + var msgID, description, emoji, roles string + err := db.QueryRow( + "SELECT msg_id, description, emoji, roles FROM reaction_role_categories WHERE channel_id = ? AND name = ?", + channelID, + name, + ).Scan(&msgID, &description, &emoji, &roles) + if err != nil { + return nil, err + } + + return &ReactionRoleCategory{ + MsgID: msgID, + ChannelID: channelID, + Name: name, + Description: description, + Emoji: splitOptions(emoji), + Roles: splitOptions(roles), + }, nil +} + +func DeleteReactionRoleCategory(channelID, name string) error { + _, err := db.Exec("DELETE FROM reaction_role_categories WHERE name = ? AND channel_id = ?", name, channelID) + return err +} + +func AddReactionRole(channelID, category, emoji string, role *discordgo.Role) error { + var oldEmoji, oldRoles string + err := db.QueryRow("SELECT emoji, roles FROM reaction_role_categories WHERE name = ? AND channel_id = ?", category, channelID).Scan(&oldEmoji, &oldRoles) + if err != nil { + return err + } + + splitEmoji, splitRoles := splitOptions(oldEmoji), splitOptions(oldRoles) + splitEmoji = append(splitEmoji, strings.TrimSpace(emoji)) + splitRoles = append(splitRoles, role.ID) + + _, err = db.Exec( + "UPDATE reaction_role_categories SET emoji = ?, roles = ? WHERE name = ? AND channel_id = ?", + strings.Join(splitEmoji, ","), + strings.Join(splitRoles, ","), + category, + channelID, + ) + return err +} + +func DeleteReactionRole(channelID, category string, role *discordgo.Role) error { + var oldEmoji, oldRoles string + err := db.QueryRow("SELECT emoji, roles FROM reaction_role_categories WHERE name = ? AND channel_id = ?", category, channelID).Scan(&oldEmoji, &oldRoles) + if err != nil { + return err + } + + splitEmoji, splitRoles := splitOptions(oldEmoji), splitOptions(oldRoles) + if i := slices.Index(splitRoles, role.ID); i == -1 { + return nil + } else { + splitEmoji = append(splitEmoji[:i], splitEmoji[i+1:]...) + splitRoles = append(splitRoles[:i], splitRoles[i+1:]...) + } + + _, err = db.Exec( + "UPDATE reaction_role_categories SET emoji = ?, roles = ? WHERE name = ? AND channel_id = ?", + strings.Join(splitEmoji, ","), + strings.Join(splitRoles, ","), + category, + channelID, + ) + return err +} diff --git a/internal/db/starboard.go b/internal/db/starboard.go new file mode 100644 index 0000000..79233df --- /dev/null +++ b/internal/db/starboard.go @@ -0,0 +1,41 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package db + +import ( + "database/sql" + "errors" +) + +func AddToStarboard(msgID string) error { + _, err := db.Exec("INSERT OR ABORT INTO starboard VALUES (?)", msgID) + return err +} + +func ExistsInStarboard(msgID string) (bool, error) { + var out bool + row := db.QueryRowx("SELECT 1 FROM starboard WHERE id = ?", msgID) + err := row.Scan(&out) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } else if err != nil { + return false, err + } + return true, nil +} diff --git a/internal/db/tickets.go b/internal/db/tickets.go new file mode 100644 index 0000000..ea66550 --- /dev/null +++ b/internal/db/tickets.go @@ -0,0 +1,36 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package db + +func AddTicket(guildID, userID, channelID string) error { + _, err := db.Exec("INSERT OR ABORT INTO tickets (guild_id, user_id, channel_id) VALUES (?, ?, ?)", guildID, userID, channelID) + return err +} + +func TicketChannelID(guildID, userID string) (string, error) { + var out string + row := db.QueryRowx("SELECT channel_id FROM tickets WHERE user_id = ? AND guild_id = ?", userID, guildID) + err := row.Scan(&out) + return out, err +} + +func RemoveTicket(guildID, userID string) error { + _, err := db.Exec("DELETE FROM tickets WHERE user_id = ? AND guild_id = ?", userID, guildID) + return err +} diff --git a/internal/db/vetting.go b/internal/db/vetting.go new file mode 100644 index 0000000..390b814 --- /dev/null +++ b/internal/db/vetting.go @@ -0,0 +1,43 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package db + +func AddVettingReq(guildID, userID, msgID string) error { + _, err := db.Exec("INSERT OR ABORT INTO vetting_requests (guild_id, user_id, msg_id) VALUES (?, ?, ?)", guildID, userID, msgID) + return err +} + +func VettingReqID(guildID, userID string) (string, error) { + var out string + row := db.QueryRowx("SELECT msg_id FROM vetting_requests WHERE user_id = ? AND guild_id = ?", userID, guildID) + err := row.Scan(&out) + return out, err +} + +func VettingReqUserID(guildID, msgID string) (string, error) { + var out string + row := db.QueryRowx("SELECT user_id FROM vetting_requests WHERE msg_id = ? AND guild_id = ?", msgID, guildID) + err := row.Scan(&out) + return out, err +} + +func RemoveVettingReq(guildID, userID string) error { + _, err := db.Exec("DELETE FROM vetting_requests WHERE user_id = ? AND guild_id = ?", userID, guildID) + return err +} diff --git a/internal/emoji/emoji.go b/internal/emoji/emoji.go new file mode 100644 index 0000000..c7893cf --- /dev/null +++ b/internal/emoji/emoji.go @@ -0,0 +1,173 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package emoji + +import ( + "regexp" + "strings" + "unicode" + + "github.com/rivo/uniseg" +) + +var ( + customEmojiRegex = regexp.MustCompile(`^<(a?):(\w+):(\d+)>$`) + unicodeEmojiTable = &unicode.RangeTable{ + R32: []unicode.Range32{ + { // Enclosed Alphanumeric Supplement + Lo: 0x1F100, + Hi: 0x1F1FF, + Stride: 1, + }, + { // Miscellaneous Symbols and Pictographs + Lo: 0x1F300, + Hi: 0x1F5FF, + Stride: 1, + }, + { // Emoticons + Lo: 0x1F600, + Hi: 0x1F64F, + Stride: 1, + }, + { // Transport and Map Symbols + Lo: 0x1F680, + Hi: 0x1F6FF, + Stride: 1, + }, + { // Geometric Shapes Extended + Lo: 0x1F780, + Hi: 0x1F7FF, + Stride: 1, + }, + { // Supplemental Symbols and Pictographs + Lo: 0x1F900, + Hi: 0x1F9FF, + Stride: 1, + }, + }, + R16: []unicode.Range16{ + { // Zero-width characters + Lo: 0x200B, + Hi: 0x200D, + Stride: 1, + }, + { // Miscellaneous Technical + Lo: 0x2300, + Hi: 0x23FF, + Stride: 1, + }, + { // Miscellaneous Symbols + Lo: 0x2600, + Hi: 0x26FF, + Stride: 1, + }, + { // Dingbats + Lo: 0x2700, + Hi: 0x27BF, + Stride: 1, + }, + { // Miscellaneous Symbols and Arrows + Lo: 0x2B00, + Hi: 0x2BFF, + Stride: 1, + }, + { // Variation Selectors + Lo: 0xFE00, + Hi: 0xFE0F, + Stride: 1, + }, + }, + } +) + +// Emoji represents a Discord emoji. +type Emoji struct { + Name string + ID string + IsAnimated bool + IsCustom bool +} + +// APIFormat returns a string that represents the emoji +// in discord API requests. +func (e *Emoji) APIFormat() string { + if e.IsCustom { + return e.Name + ":" + e.ID + } else { + return e.Name + } +} + +// MessageFormat returns a string that represents the emoji +// in discord messages. +func (e *Emoji) MessageFormat() string { + if e.IsCustom { + var sb strings.Builder + sb.WriteByte('<') + if e.IsAnimated { + sb.WriteByte('a') + } + sb.WriteByte(':') + sb.WriteString(e.Name) + sb.WriteByte(':') + sb.WriteString(e.ID) + sb.WriteByte('>') + return sb.String() + } else { + return e.Name + } +} + +// Parse parses a single Discord emoji. It can handle both +// unicode emoji and custom emoji. +func Parse(s string) (Emoji, bool) { + s = strings.TrimSpace(s) + + if isEmoji(s) { + // This string should only contain a single emoji. + // If it has more, return false. + if uniseg.GraphemeClusterCount(s) != 1 { + return Emoji{}, false + } + return Emoji{Name: s}, true + } + + if customEmojiRegex.MatchString(s) { + matches := customEmojiRegex.FindStringSubmatch(s) + return Emoji{ + Name: matches[2], + ID: matches[3], + IsAnimated: matches[1] == "a", + IsCustom: true, + }, true + } + + return Emoji{}, false +} + +// isEmoji checks to make sure all the characters in the string +// are within the unicode emoji range table. +func isEmoji(s string) bool { + for _, char := range s { + if !unicode.In(char, unicodeEmojiTable) { + return false + } + } + return true +} diff --git a/internal/limiter/limiter.go b/internal/limiter/limiter.go new file mode 100644 index 0000000..10de3c1 --- /dev/null +++ b/internal/limiter/limiter.go @@ -0,0 +1,90 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package limiter + +import ( + "sync" + "time" +) + +// Limiter is a token bucket rate limiter +type Limiter struct { + TotalAmt int + WarnAmt int + Duration time.Duration + + mu sync.Mutex + tokens map[string]int +} + +// New returns a new limiter with the given parameters +func New(warnAmt, totalAmt int, duration time.Duration) *Limiter { + limiter := &Limiter{ + TotalAmt: totalAmt, + WarnAmt: warnAmt, + Duration: duration, + tokens: map[string]int{}, + } + go limiter.resetTokens() + return limiter +} + +// Decrement removes one token from the bucket with the given key +func (l *Limiter) Decrement(key string) { + l.mu.Lock() + defer l.mu.Unlock() + tokenAmt, ok := l.tokens[key] + if ok { + l.tokens[key] = tokenAmt - 1 + } else { + l.tokens[key] = l.TotalAmt - 1 + } +} + +// IsWarning returns true if the token amount equals the warn amount of l. +func (l *Limiter) IsWarning(key string) bool { + l.mu.Lock() + defer l.mu.Unlock() + tokenAmt, ok := l.tokens[key] + if !ok { + return false + } + return tokenAmt > 0 && tokenAmt <= (l.TotalAmt-l.WarnAmt) +} + +// IsWarning returns true if the token amount for the given key is depleted. +func (l *Limiter) IsDepleted(key string) bool { + l.mu.Lock() + defer l.mu.Unlock() + tokenAmt, ok := l.tokens[key] + if !ok { + return false + } + return tokenAmt <= 0 +} + +// resetTokens resets all the token buckets at a regular interval +func (l *Limiter) resetTokens() { + for { + l.mu.Lock() + l.tokens = map[string]int{} + l.mu.Unlock() + time.Sleep(l.Duration) + } +} diff --git a/internal/systems/commands/register.go b/internal/systems/commands/register.go new file mode 100644 index 0000000..d56abd7 --- /dev/null +++ b/internal/systems/commands/register.go @@ -0,0 +1,113 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package commands + +import ( + "sync" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/logger/log" + "go.elara.ws/owobot/internal/util" +) + +var ( + mu = sync.Mutex{} + cmds = map[string]CmdFunc{} + acs = []*discordgo.ApplicationCommand{} +) + +type CmdFunc func(s *discordgo.Session, i *discordgo.InteractionCreate) error + +func Init(s *discordgo.Session) error { + s.AddHandler(onCmd) + _, err := s.ApplicationCommandBulkOverwrite(s.State.Application.ID, "", acs) + acs = nil // Allow the ACs to be GC'd + return err +} + +func onCmd(s *discordgo.Session, i *discordgo.InteractionCreate) { + if i.Type != discordgo.InteractionApplicationCommand { + return + } + + data := i.ApplicationCommandData() + + mu.Lock() + defer mu.Unlock() + cmdFn, ok := cmds[data.Name] + if !ok { + return + } + + err := cmdFn(s, i) + if err != nil { + log.Warn("Error in command function").Str("cmd", data.Name).Err(err).Send() + sendError(s, i.Interaction, err) + return + } +} + +func Register(s *discordgo.Session, fn CmdFunc, ac *discordgo.ApplicationCommand) { + // If the DM permission hasn't been explicitly set, assume false + if ac.DMPermission == nil { + ac.DMPermission = util.Pointer(false) + } + + mu.Lock() + // Skip commands that already exist + if _, ok := cmds[ac.Name]; ok { + mu.Unlock() + return + } + cmds[ac.Name] = fn + mu.Unlock() + + acs = append(acs, ac) +} + +func sendError(s *discordgo.Session, i *discordgo.Interaction, serr error) { + err := util.RespondEphemeral(s, i, "ERROR: "+serr.Error()) + if err != nil { + log.Warn("Error while trying to send error").Err(err).Send() + return + } +} + +// commandSync checks if any registered commands have been removed and, if so, +// deletes them. +func commandSync(s *discordgo.Session) error { + appCmds, err := s.ApplicationCommands(s.State.Application.ID, "") + if err != nil { + return err + } + + deleted := 0 + for _, appCmd := range appCmds { + if _, ok := cmds[appCmd.Name]; !ok { + err = s.ApplicationCommandDelete(appCmd.ApplicationID, "", appCmd.ID) + if err != nil { + return err + } + deleted++ + } + } + + log.Info("Command sync completed").Int("deleted", deleted).Send() + return nil +} diff --git a/internal/systems/eventlog/eventlog.go b/internal/systems/eventlog/eventlog.go new file mode 100644 index 0000000..39470b9 --- /dev/null +++ b/internal/systems/eventlog/eventlog.go @@ -0,0 +1,162 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package eventlog + +import ( + "fmt" + "io" + "time" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/owobot/internal/db" + "go.elara.ws/owobot/internal/systems/commands" + "go.elara.ws/owobot/internal/util" +) + +func Init(s *discordgo.Session) error { + commands.Register(s, eventlogCmd, &discordgo.ApplicationCommand{ + Name: "eventlog", + Description: "Manage the event log", + DefaultMemberPermissions: util.Pointer[int64](discordgo.PermissionManageServer), + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "channel", + Description: "Set the event log channel", + Type: discordgo.ApplicationCommandOptionSubCommand, + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "channel", + Description: "The channel for the event log", + Type: discordgo.ApplicationCommandOptionChannel, + ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildText}, + Required: true, + }, + }, + }, + { + Name: "ticket_channel", + Description: "Set the ticket log channel", + Type: discordgo.ApplicationCommandOptionSubCommand, + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "channel", + Description: "The channel for the ticket log", + Type: discordgo.ApplicationCommandOptionChannel, + ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildText}, + Required: true, + }, + }, + }, + }, + }) + + return nil +} + +func eventlogCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + switch name := data.Options[0].Name; name { + case "channel": + return channelCmd(s, i) + case "ticket_channel": + return ticketChannelCmd(s, i) + default: + return fmt.Errorf("unknown eventlog subcommand: %s", name) + } +} + +func channelCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + // Get the subcommand options + args := i.ApplicationCommandData().Options[0].Options + + c := args[0].ChannelValue(s) + err := db.SetLogChannel(i.GuildID, c.ID) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully set event log channel to <#%s>!", c.ID)) +} + +func ticketChannelCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + // Get the subcommand options + args := i.ApplicationCommandData().Options[0].Options + + c := args[0].ChannelValue(s) + err := db.SetTicketLogChannel(i.GuildID, c.ID) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully set ticket log channel to <#%s>!", c.ID)) +} + +type Entry struct { + Title string + Description string + ImageURL string + Author *discordgo.User +} + +func Log(s *discordgo.Session, guildID string, e Entry) error { + guild, err := db.GuildByID(guildID) + if err != nil { + return err + } + + if guild.LogChanID == "" { + return nil + } + + embed := &discordgo.MessageEmbed{ + Title: e.Title, + Description: e.Description, + Footer: &discordgo.MessageEmbedFooter{ + Text: util.FormatJucheTime(time.Now()), + }, + } + + if e.Author != nil { + embed.Author = &discordgo.MessageEmbedAuthor{ + Name: e.Author.Username, + IconURL: e.Author.AvatarURL(""), + } + } + + if e.ImageURL != "" { + embed.Image = &discordgo.MessageEmbedImage{URL: e.ImageURL} + } + + _, err = s.ChannelMessageSendEmbed(guild.LogChanID, embed) + return err +} + +func TicketMsgLog(s *discordgo.Session, guildID string, msgLog io.Reader) error { + guild, err := db.GuildByID(guildID) + if err != nil { + return err + } + + if guild.TicketLogChanID == "" { + return nil + } + + _, err = s.ChannelFileSend(guild.TicketLogChanID, "log.txt", msgLog) + return err +} diff --git a/internal/systems/guilds/guilds.go b/internal/systems/guilds/guilds.go new file mode 100644 index 0000000..8f57c3d --- /dev/null +++ b/internal/systems/guilds/guilds.go @@ -0,0 +1,52 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package guilds + +import ( + "github.com/bwmarrin/discordgo" + "go.elara.ws/logger/log" + "go.elara.ws/owobot/internal/db" +) + +func Init(s *discordgo.Session) error { + s.AddHandler(onGuildCreate) + return guildSync(s) +} + +// onGuildCreate adds a guild to the database if it doesn't already exist +func onGuildCreate(s *discordgo.Session, gc *discordgo.GuildCreate) { + err := db.CreateGuild(gc.ID) + if err != nil { + log.Warn("Error creating guild").Err(err).Send() + return + } +} + +// guildSync makes sure all the guilds the bot is in +// exist in the database. If not, it adds them. +func guildSync(s *discordgo.Session) error { + for _, guild := range s.State.Guilds { + err := db.CreateGuild(guild.ID) + if err != nil { + return err + } + } + log.Info("Guild sync completed").Send() + return nil +} diff --git a/internal/systems/members/invites.go b/internal/systems/members/invites.go new file mode 100644 index 0000000..875ce92 --- /dev/null +++ b/internal/systems/members/invites.go @@ -0,0 +1,69 @@ +package members + +import ( + "sync" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/logger/log" +) + +var ( + mu = sync.RWMutex{} + inviteMap = map[string]*discordgo.Invite{} +) + +// populateInviteMap gets invites from all the guilds this bot is in +// and adds them to the invite map. +func populateInviteMap(s *discordgo.Session) { + for _, guild := range s.State.Guilds { + invites, err := s.GuildInvites(guild.ID) + if err != nil { + log.Warn("Error getting invites for guild").Str("guild-id", guild.ID).Str("task", "populate-invites").Send() + continue + } + addToMap(invites) + } + log.Info("Invite map populated").Send() +} + +// addToMap adds a slice of invites to the map +func addToMap(invites []*discordgo.Invite) { + mu.Lock() + defer mu.Unlock() + for _, invite := range invites { + inviteMap[invite.Code] = invite + } +} + +// addOneToMap adds a single invite to the map +func addOneToMap(invite *discordgo.Invite) { + mu.Lock() + defer mu.Unlock() + inviteMap[invite.Code] = invite +} + +// findLastUsedInvites attempts to detect the invites that potentially might've been used last +// in order to figure out what invite a user used to join. +func findLastUsedInvites(s *discordgo.Session, guildID string) ([]string, error) { + invites, err := s.GuildInvites(guildID) + if err != nil { + return nil, err + } + var out []string + for _, invite := range invites { + mu.RLock() + oldInvite, ok := inviteMap[invite.Code] + mu.RUnlock() + if ok { + if oldInvite.Uses != invite.Uses { + out = append(out, invite.Code) + } + } else { + if invite.Uses > 0 { + out = append(out, invite.Code) + } + } + addOneToMap(invite) + } + return out, nil +} diff --git a/internal/systems/members/members.go b/internal/systems/members/members.go new file mode 100644 index 0000000..84f61f0 --- /dev/null +++ b/internal/systems/members/members.go @@ -0,0 +1,200 @@ +package members + +import ( + "fmt" + "slices" + "strings" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/logger/log" + "go.elara.ws/owobot/internal/cache" + "go.elara.ws/owobot/internal/systems/eventlog" +) + +func Init(s *discordgo.Session) error { + go populateInviteMap(s) + s.AddHandler(onMemberAdd) + s.AddHandler(onMemberUpdate) + s.AddHandler(onMemberLeave) + s.AddHandler(onChannelDelete) + return nil +} + +// onMemberAdd attempts to detect which invite(s) were used to invite the user +// and logs the member join. +func onMemberAdd(s *discordgo.Session, gma *discordgo.GuildMemberAdd) { + invites, err := findLastUsedInvites(s, gma.GuildID) + if err != nil { + log.Warn("Error finding last used invite").Err(err).Send() + } + + code := "Unknown" + if len(invites) > 0 { + code = strings.Join(invites, " or ") + } + + err = eventlog.Log(s, gma.GuildID, eventlog.Entry{ + Title: "New Member Joined!", + Description: fmt.Sprintf("**User:**\n%s\n**ID:**\n%s\n**Invite Code:**\n%s", gma.Member.User.Mention(), gma.Member.User.ID, code), + Author: gma.Member.User, + }) + if err != nil { + log.Warn("Error sending member joined log").Str("member", gma.Member.User.Username).Err(err).Send() + } +} + +// onMemberUpdate logs member updates, such as roles being assigned or removed +func onMemberUpdate(s *discordgo.Session, gmu *discordgo.GuildMemberUpdate) { + if gmu.BeforeUpdate == nil || gmu.Member == nil { + return + } + + if !slices.Equal(gmu.BeforeUpdate.Roles, gmu.Member.Roles) { + var added, removed []string + for _, newRole := range gmu.Member.Roles { + if !slices.Contains(gmu.BeforeUpdate.Roles, newRole) { + added = append(added, fmt.Sprintf("<@&%s>", newRole)) + } + } + for _, oldRole := range gmu.BeforeUpdate.Roles { + if !slices.Contains(gmu.Member.Roles, oldRole) { + removed = append(removed, fmt.Sprintf("<@&%s>", oldRole)) + } + } + + err := eventlog.Log(s, gmu.GuildID, eventlog.Entry{ + Title: "Roles Updated", + Description: fmt.Sprintf( + "**User:** %s\n**Added:** %s\n**Removed:** %s", + gmu.Member.User.Mention(), + strings.Join(added, " "), + strings.Join(removed, " "), + ), + Author: gmu.Member.User, + }) + if err != nil { + log.Warn("Error roles updated log").Str("member", gmu.Member.User.Username).Err(err).Send() + } + } +} + +// onMemberLeave logs member leave events and handles bans and kicks +func onMemberLeave(s *discordgo.Session, gmr *discordgo.GuildMemberRemove) { + err := handleBanOrKick(s, gmr) + if err != nil { + log.Warn("Error logging ban or kick").Str("member", gmr.Member.User.Username).Err(err).Send() + } + + err = eventlog.Log(s, gmr.GuildID, eventlog.Entry{ + Title: "Member Left", + Description: fmt.Sprintf("**User:**\n%s\n**ID:**\n%s", gmr.Member.User.Mention(), gmr.Member.User.ID), + Author: gmr.Member.User, + }) + if err != nil { + log.Warn("Error sending member left log").Str("member", gmr.Member.User.Username).Err(err).Send() + } +} + +// onChannelDelete attempts to detect the user responsible for a channel deletion +// and logs it. It also handles rate limiting for channel delete events. +func onChannelDelete(s *discordgo.Session, cd *discordgo.ChannelDelete) { + if cd.Type == discordgo.ChannelTypeDM || cd.Type == discordgo.ChannelTypeGroupDM { + return + } + + auditLog, err := s.GuildAuditLog(cd.GuildID, "", "", int(discordgo.AuditLogActionChannelDelete), 5) + if err != nil { + log.Error("Error getting audit log").Err(err).Send() + return + } + + for _, entry := range auditLog.AuditLogEntries { + // If the deleted channel isn't the one this event is for, + // skip it. + if entry.TargetID != cd.ID { + continue + } + + // If the bot deleted the channel, we don't care about this event + if entry.UserID == s.State.User.ID { + return + } + + err = handleRatelimit(s, "channel_delete", cd.GuildID, entry.UserID) + if err != nil { + log.Error("Error handling rate limit").Err(err).Send() + } + + member, err := cache.Member(s, cd.GuildID, entry.UserID) + if err != nil { + log.Error("Error getting member").Err(err).Send() + return + } + + err = eventlog.Log(s, cd.GuildID, eventlog.Entry{ + Title: "Channel Deleted", + Description: fmt.Sprintf("**Name:** `%s`\n**Deleted By:** %s", cd.Name, member.User.Mention()), + Author: member.User, + }) + if err != nil { + log.Warn("Error sending channel deleted log").Str("channel", cd.Name).Err(err).Send() + return + } + + return + } +} + +// handleBanOrKick attempts to detect the user responsible for a ban or kick, and +// logs it. It also handles rate limiting for bans and kicks. +func handleBanOrKick(s *discordgo.Session, gmr *discordgo.GuildMemberRemove) error { + auditLog, err := s.GuildAuditLog(gmr.GuildID, "", "", 0, 5) + if err != nil { + return err + } + + for _, entry := range auditLog.AuditLogEntries { + // If there's no action type or the user isn't the one this + // event is for, skip it. + if entry.ActionType == nil || entry.TargetID != gmr.User.ID { + continue + } + + switch *entry.ActionType { + case discordgo.AuditLogActionMemberBanAdd: + executor, err := cache.Member(s, gmr.GuildID, entry.UserID) + if err != nil { + return err + } + + err = eventlog.Log(s, gmr.GuildID, eventlog.Entry{ + Title: "User banned", + Description: fmt.Sprintf("**Target:** %s\n**Banned by:** %s\n**Reason:** %s", gmr.User.Mention(), executor.User.Mention(), entry.Reason), + Author: gmr.User, + }) + if err != nil { + return err + } + + return handleRatelimit(s, "ban", gmr.GuildID, executor.User.ID) + case discordgo.AuditLogActionMemberKick: + executor, err := cache.Member(s, gmr.GuildID, entry.UserID) + if err != nil { + return err + } + + err = eventlog.Log(s, gmr.GuildID, eventlog.Entry{ + Title: "User kicked", + Description: fmt.Sprintf("**Target:** %s\n**Kicked by:** %s\n**Reason:** %s", gmr.User.Mention(), executor.User.Mention(), entry.Reason), + Author: gmr.User, + }) + if err != nil { + return err + } + + return handleRatelimit(s, "kick", gmr.GuildID, executor.User.ID) + } + } + + return nil +} diff --git a/internal/systems/members/ratelimit.go b/internal/systems/members/ratelimit.go new file mode 100644 index 0000000..055a265 --- /dev/null +++ b/internal/systems/members/ratelimit.go @@ -0,0 +1,60 @@ +package members + +import ( + "fmt" + "time" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/owobot/internal/limiter" +) + +// limiters contains the rate limiters for each event type +var limiters = map[string]*limiter.Limiter{ + "channel_delete": limiter.New(8, 10, time.Minute), + "kick": limiter.New(8, 10, time.Minute), + "ban": limiter.New(5, 7, 5*time.Minute), +} + +// handleRatelimit handles rate limiting for a given guild and user ID. +// It decrements the token count for the event, then checks if a warning +// or kick is required, and performs that if needed. +func handleRatelimit(s *discordgo.Session, limit, guildID, userID string) error { + l, ok := limiters[limit] + if !ok || userID == s.State.User.ID { + return nil + } + + ch, err := s.UserChannelCreate(userID) + if err != nil { + return err + } + + key := fmt.Sprintf("%s:%s", guildID, userID) + + var serverName string + guild, err := s.State.Guild(guildID) + if err != nil || guild.Name == "" { + serverName = "the server" + } else { + serverName = guild.Name + } + + l.Decrement(key) + if l.IsWarning(key) { + _, err = s.ChannelMessageSend(ch.ID, fmt.Sprintf("<@%s> WARNING: You are near the `%s` limit. If you reach it, you'll be kicked from %s.", userID, limit, serverName)) + if err != nil { + return err + } + } else if l.IsDepleted(key) { + // We ignore the error here because even if the message can't be sent, + // we want to kick the user from the server anyway. + _, _ = s.ChannelMessageSend(ch.ID, fmt.Sprintf("<@%s> You've reached the `%s` limit and have been kicked from %s.", userID, limit, serverName)) + + err = s.GuildMemberDelete(guildID, userID, discordgo.WithAuditLogReason(fmt.Sprintf("Exceeded `%s` rate limit", limit))) + if err != nil { + return err + } + } + + return nil +} diff --git a/internal/systems/polls/polls.go b/internal/systems/polls/polls.go new file mode 100644 index 0000000..24c3316 --- /dev/null +++ b/internal/systems/polls/polls.go @@ -0,0 +1,408 @@ +package polls + +import ( + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/base64" + "errors" + "fmt" + "io" + "strconv" + "strings" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/logger/log" + "go.elara.ws/owobot/internal/db" + "go.elara.ws/owobot/internal/emoji" + "go.elara.ws/owobot/internal/systems/commands" + "go.elara.ws/owobot/internal/util" + "go.elara.ws/owobot/internal/xsync" +) + +func Init(s *discordgo.Session) error { + s.AddHandler(util.InteractionErrorHandler("poll-add-opt", onPollAddOpt)) + s.AddHandler(util.InteractionErrorHandler("poll-opt-submit", onAddOptModalSubmit)) + s.AddHandler(util.InteractionErrorHandler("poll-finish", onPollFinish)) + s.AddHandler(onPollReaction) + s.AddHandler(onVote) + + commands.Register(s, pollCmd, &discordgo.ApplicationCommand{ + Name: "poll", + Description: "Create a new poll", + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "title", + Description: "The title of the poll", + Type: discordgo.ApplicationCommandOptionString, + Required: true, + }, + }, + }) + + return nil +} + +func pollCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + title := data.Options[0].StringValue() + + err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseChannelMessageWithSource, + Data: &discordgo.InteractionResponseData{ + Content: "**" + title + "**", + Components: []discordgo.MessageComponent{ + discordgo.ActionsRow{Components: []discordgo.MessageComponent{ + discordgo.Button{ + Label: "Add Option", + Style: discordgo.PrimaryButton, + CustomID: "poll-add-opt", + }, + discordgo.Button{ + Label: "Finish", + Style: discordgo.SuccessButton, + CustomID: "poll-finish", + }, + }}, + }, + }, + }) + if err != nil { + return err + } + + msg, err := s.InteractionResponse(i.Interaction) + if err != nil { + return err + } + return db.CreatePoll(msg.ID, i.Member.User.ID, title) +} + +// onPollAddOpt handles the Add Option button on unfinished polls. +func onPollAddOpt(s *discordgo.Session, i *discordgo.InteractionCreate) error { + if i.Type != discordgo.InteractionMessageComponent { + return nil + } + + data := i.MessageComponentData() + if data.CustomID != "poll-add-opt" { + return nil + } + + if i.Member.User.ID != i.Message.Interaction.User.ID { + return errors.New("only the creator of the poll may add options to it") + } + + return s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseModal, + Data: &discordgo.InteractionResponseData{ + Title: "Add an option", + CustomID: "poll-opt-modal", + Components: []discordgo.MessageComponent{ + discordgo.ActionsRow{Components: []discordgo.MessageComponent{ + discordgo.TextInput{ + Label: "Option text", + Style: discordgo.TextInputShort, + Required: true, + }, + }}, + }, + }, + }) +} + +// onAddOptModalSubmit handles the submission of the Add Option modal. +func onAddOptModalSubmit(s *discordgo.Session, i *discordgo.InteractionCreate) error { + if i.Type != discordgo.InteractionModalSubmit { + return nil + } + + data := i.ModalSubmitData() + if data.CustomID != "poll-opt-modal" { + return nil + } + + row := data.Components[0].(*discordgo.ActionsRow) + textInput := row.Components[0].(*discordgo.TextInput) + + err := db.AddPollOptionText(i.Message.ID, textInput.Value) + if err != nil { + return err + } + + return updatePollWaitReaction(s, i.Interaction) +} + +// onPollReaction handles reactions to a poll. +func onPollReaction(s *discordgo.Session, mra *discordgo.MessageReactionAdd) { + poll, err := db.GetPoll(mra.MessageID) + if errors.Is(err, sql.ErrNoRows) { + return + } else if err != nil { + log.Error("Error getting poll from database").Err(err).Send() + return + } + + err = s.MessageReactionRemove(mra.ChannelID, mra.MessageID, mra.Emoji.APIName(), mra.UserID) + if err != nil { + log.Error("Error removing poll reaction").Err(err).Send() + return + } + + // If the poll is finished, there's already an emoji for every option, + // or the user who reacted is not the owner of the poll, return. + if poll.Finished || + len(poll.OptionEmojis) == len(poll.OptionText) || + mra.Member.User.ID != poll.OwnerID { + return + } + + err = db.AddPollOptionEmoji(mra.MessageID, mra.Emoji.MessageFormat()) + if err != nil { + log.Error("Error adding poll option emoji").Err(err).Send() + return + } + + err = updatePollUnfinished(s, mra.MessageID, mra.ChannelID) + if err != nil { + log.Error("Error updating poll message").Err(err).Send() + return + } +} + +// onPollFinish handles the Finish button on an unfinished poll. +func onPollFinish(s *discordgo.Session, i *discordgo.InteractionCreate) error { + if i.Type != discordgo.InteractionMessageComponent { + return nil + } + + data := i.MessageComponentData() + if data.CustomID != "poll-finish" { + return nil + } + + if i.Member.User.ID != i.Message.Interaction.User.ID { + return errors.New("only the creator of the poll may finish it") + } + + poll, err := db.GetPoll(i.Message.ID) + if err != nil { + return err + } + + privacyToken, err := makePrivacyToken() + if err != nil { + return err + } + + var ( + components []discordgo.MessageComponent + currentRow discordgo.ActionsRow + ) + + for i := 0; i < len(poll.OptionEmojis); i++ { + // Action rows can only contain 5 elements, + // so we create a new row if we reach a multiple + // of 5. + if i > 0 && i%5 == 0 { + components = append(components, currentRow) + currentRow = discordgo.ActionsRow{} + } + + e, ok := emoji.Parse(poll.OptionEmojis[i]) + if !ok { + return fmt.Errorf("invalid emoji: %s", poll.OptionEmojis[i]) + } + + currentRow.Components = append(currentRow.Components, discordgo.Button{ + CustomID: "vote:" + strconv.Itoa(i) + ":" + privacyToken, + Style: discordgo.SecondaryButton, + Emoji: discordgo.ComponentEmoji{ + Name: e.Name, + ID: e.ID, + }, + }) + } + + if len(currentRow.Components) != 0 { + components = append(components, currentRow) + } + + err = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseUpdateMessage, + Data: &discordgo.InteractionResponseData{ + Content: i.Message.Content, + Components: components, + }, + }) + if err != nil { + return err + } + + err = db.FinishPoll(i.Message.ID) + if err != nil { + log.Error("Error finishing poll").Err(err).Send() + return nil + } + + _, err = s.MessageThreadStart(i.ChannelID, i.Message.ID, poll.Title, 1440) + if err != nil { + log.Error("Error starting poll thread").Err(err).Send() + return nil + } + + return nil +} + +// voteMtx ensures only one vote is being processed at a time +// for each message, since handlers may be executed concurrently. +var voteMtx xsync.KeyedMutex + +// onVote handles poll votes. +func onVote(s *discordgo.Session, i *discordgo.InteractionCreate) { + if i.Type != discordgo.InteractionMessageComponent { + return + } + + data := i.MessageComponentData() + splitID := strings.SplitN(data.CustomID, ":", 3) + if splitID[0] != "vote" { + return + } + + // Respond with a deferred update since we have no idea how long this could take + // because we have to get the vote lock which may take a while depending on how many + // votes are being processed for this poll at the moment. + err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseDeferredMessageUpdate, + }) + if err != nil { + log.Error("Error responding to interaction").Err(err).Send() + } + + voteMtx.Lock(i.Message.ID) + defer voteMtx.Unlock(i.Message.ID) + + option, err := strconv.Atoi(splitID[1]) + if err != nil { + log.Error("Error parsing button option").Err(err).Send() + return + } + + err = db.AddVote(db.Vote{ + PollMsgID: i.Message.ID, + UserToken: makeUserToken(splitID[2], i.Member.User.ID), + Option: option, + }) + if err != nil { + log.Error("Error adding vote to database").Err(err).Send() + return + } + + poll, err := db.GetPoll(i.Message.ID) + if err != nil { + log.Error("Error getting poll from database").Err(err).Send() + return + } + + content, err := generatePollContent(poll) + if err != nil { + log.Error("Error generating poll content").Err(err).Send() + return + } + + _, err = s.ChannelMessageEditComplex(&discordgo.MessageEdit{ + ID: i.Message.ID, + Channel: i.ChannelID, + Content: util.Pointer(content), + }) + if err != nil { + log.Error("Error editing poll message").Err(err).Send() + return + } +} + +// makePrivacyToken creates a random token to be hashed with the user's +// id to create an anonymous but deterministic user token for use in +// poll votes. +func makePrivacyToken() (string, error) { + randomData := make([]byte, 25) + _, err := io.ReadFull(rand.Reader, randomData) + return base64.URLEncoding.EncodeToString(randomData), err +} + +// makeUserToken hashes a privacy token with a user ID to create +// a user token. +func makeUserToken(privacyToken, userID string) string { + userTokenData := sha256.Sum256(append([]byte(privacyToken), userID...)) + return base64.URLEncoding.EncodeToString(userTokenData[:]) +} + +// updatePollWaitReaction updates a poll to wait for an emoji reaction. +func updatePollWaitReaction(s *discordgo.Session, i *discordgo.Interaction) error { + content := i.Message.Content + content += "\n\n_Please react with the emoji that you'd like to use for this option._" + return s.InteractionRespond(i, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseUpdateMessage, + Data: &discordgo.InteractionResponseData{Content: content}, + }) +} + +// updatePollUnfinished updates an unfinished poll. +func updatePollUnfinished(s *discordgo.Session, msgID, channelID string) error { + poll, err := db.GetPoll(msgID) + if err != nil { + return err + } + + content, err := generatePollContent(poll) + if err != nil { + return err + } + + _, err = s.ChannelMessageEditComplex(&discordgo.MessageEdit{ + ID: msgID, + Channel: channelID, + Content: &content, + Components: []discordgo.MessageComponent{ + discordgo.ActionsRow{Components: []discordgo.MessageComponent{ + discordgo.Button{ + Label: "Add Option", + Style: discordgo.PrimaryButton, + CustomID: "poll-add-opt", + }, + discordgo.Button{ + Label: "Finish", + Style: discordgo.SuccessButton, + CustomID: "poll-finish", + }, + }}, + }, + }) + return err +} + +// generatePollContent generates the body of the poll, with the title and +// option list. +func generatePollContent(poll *db.Poll) (string, error) { + var sb strings.Builder + + sb.WriteString("**") + sb.WriteString(poll.Title) + sb.WriteString("**\n") + + for i, emoji := range poll.OptionEmojis { + sb.WriteString(emoji) + sb.WriteByte(' ') + voteAmount, err := db.VoteAmount(poll.MsgID, i) + if err != nil { + return "", err + } + sb.WriteString(strconv.Itoa(int(voteAmount))) + sb.WriteByte(' ') + sb.WriteString(poll.OptionText[i]) + sb.WriteByte('\n') + } + + return sb.String(), nil +} diff --git a/internal/systems/reactions/commands.go b/internal/systems/reactions/commands.go new file mode 100644 index 0000000..b8e2d19 --- /dev/null +++ b/internal/systems/reactions/commands.go @@ -0,0 +1,149 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package reactions + +import ( + "errors" + "fmt" + "strconv" + "strings" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/owobot/internal/cache" + "go.elara.ws/owobot/internal/db" + "go.elara.ws/owobot/internal/emoji" + "go.elara.ws/owobot/internal/util" +) + +func reactionsCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + + switch name := data.Options[0].Name; name { + case "add": + return reactionsAddCmd(s, i) + case "list": + return reactionsListCmd(s, i) + case "delete": + return reactionsDeleteCmd(s, i) + default: + return fmt.Errorf("unknown reactions subcommand: %s", name) + } +} + +func reactionsAddCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + args := data.Options[0].Options + + reaction := db.Reaction{ + MatchType: db.MatchType(args[0].StringValue()), + Match: strings.TrimSpace(args[1].StringValue()), + ReactionType: db.ReactionType(args[2].StringValue()), + Reaction: strings.TrimSpace(args[3].StringValue()), + Chance: 100, + } + + if len(args) == 5 { + reaction.Chance = int(args[4].IntValue()) + } + + switch reaction.MatchType { + case db.MatchTypeRegex: + if _, err := cache.Regex(reaction.Match); err != nil { + return err + } + case db.MatchTypeContains: + // Ensure the contains match is lowercase so we can check it + // against a lowercase string later, in the message handler. + reaction.Match = strings.ToLower(reaction.Match) + } + + if reaction.ReactionType == db.ReactionTypeEmoji { + if err := validateEmoji(reaction.Reaction); err != nil { + return err + } + } + + err := db.AddReaction(i.GuildID, reaction) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, "Successfully added reaction!") +} + +func reactionsListCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + reactions, err := db.Reactions(i.GuildID) + if err != nil { + return err + } + + var sb strings.Builder + sb.WriteString("**Reactions:**\n") + for _, reaction := range reactions { + sb.WriteString("- _[") + if reaction.Chance < 100 { + sb.WriteString(strconv.Itoa(reaction.Chance)) + sb.WriteString("% ") + } + sb.WriteString(string(reaction.MatchType)) + sb.WriteString("]_ `") + sb.WriteString(reaction.Match) + sb.WriteString("`: \"") + sb.WriteString(reaction.Reaction) + sb.WriteString("\" _(") + sb.WriteString(string(reaction.ReactionType)) + sb.WriteString(")_\n") + } + + return util.RespondEphemeral(s, i.Interaction, sb.String()) +} + +func reactionsDeleteCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + // Make sure the user has the manage expressions permission + // in case a role/member override allows someone else to use it + if i.Member.Permissions&discordgo.PermissionManageEmojis == 0 { + return errors.New("you do not have permission to delete reactions") + } + + data := i.ApplicationCommandData() + args := data.Options[0].Options + + err := db.DeleteReaction(i.GuildID, args[0].StringValue()) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, "Successfully removed reaction") +} + +func validateEmoji(s string) error { + if strings.Contains(s, ",") { + split := strings.Split(s, ",") + for _, emojiStr := range split { + if _, ok := emoji.Parse(emojiStr); !ok { + return fmt.Errorf("invalid reaction emoji: %s", emojiStr) + } + } + } else { + if _, ok := emoji.Parse(s); !ok { + return fmt.Errorf("invalid reaction emoji: %s", s) + } + } + return nil +} diff --git a/internal/systems/reactions/reactions.go b/internal/systems/reactions/reactions.go new file mode 100644 index 0000000..7cb4cc0 --- /dev/null +++ b/internal/systems/reactions/reactions.go @@ -0,0 +1,229 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package reactions + +import ( + "fmt" + "math/rand" + "strconv" + "strings" + "sync" + "time" + + "github.com/bwmarrin/discordgo" + "github.com/valyala/fasttemplate" + "go.elara.ws/logger/log" + "go.elara.ws/owobot/internal/cache" + "go.elara.ws/owobot/internal/db" + "go.elara.ws/owobot/internal/emoji" + "go.elara.ws/owobot/internal/systems/commands" + "go.elara.ws/owobot/internal/util" +) + +func Init(s *discordgo.Session) error { + s.AddHandler(onMessage) + + commands.Register(s, reactionsCmd, &discordgo.ApplicationCommand{ + Name: "reactions", + Description: "Manage message reactions", + DefaultMemberPermissions: util.Pointer[int64](discordgo.PermissionManageEmojis), + Options: []*discordgo.ApplicationCommandOption{ + { + Type: discordgo.ApplicationCommandOptionSubCommand, + Name: "add", + Description: "Add a new message reaction", + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "match_type", + Type: discordgo.ApplicationCommandOptionString, + Description: "The matcher type for this reaction", + Required: true, + Choices: []*discordgo.ApplicationCommandOptionChoice{ + { + Name: "contains", + Value: "contains", + }, + { + Name: "regex", + Value: "regex", + }, + }, + }, + { + Name: "match", + Description: "What the matcher should look for", + Type: discordgo.ApplicationCommandOptionString, + Required: true, + }, + { + Name: "reaction_type", + Description: "The reaction type", + Type: discordgo.ApplicationCommandOptionString, + Required: true, + Choices: []*discordgo.ApplicationCommandOptionChoice{ + { + Name: "emoji", + Value: "emoji", + }, + { + Name: "text", + Value: "text", + }, + }, + }, + { + Name: "reaction", + Description: "The contents of the reaction", + Type: discordgo.ApplicationCommandOptionString, + Required: true, + }, + { + Name: "chance", + Description: "The percent chance that the reaction occurs", + MinValue: util.Pointer[float64](1), + MaxValue: 100, + Type: discordgo.ApplicationCommandOptionInteger, + }, + }, + }, + { + Type: discordgo.ApplicationCommandOptionSubCommand, + Name: "list", + Description: "List all the reactions for this guild", + }, + { + Type: discordgo.ApplicationCommandOptionSubCommand, + Name: "delete", + Description: "Remove all message reactions with the given match", + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "match", + Description: "The match value for which to remove reactions", + Type: discordgo.ApplicationCommandOptionString, + Required: true, + }, + }, + }, + }, + }) + + return nil +} + +func onMessage(s *discordgo.Session, mc *discordgo.MessageCreate) { + if mc.Author.ID == s.State.User.ID { + return + } + + reactions, err := db.Reactions(mc.GuildID) + if err != nil { + log.Error("Error getting reactions from database").Err(err).Send() + return + } + + for _, reaction := range reactions { + switch reaction.MatchType { + case db.MatchTypeContains: + if strings.Contains(strings.ToLower(mc.Content), reaction.Match) { + err = performReaction(s, reaction, reaction.Reaction, mc) + if err != nil { + log.Error("Error performing reaction").Err(err).Send() + continue + } + } + case db.MatchTypeRegex: + re, err := cache.Regex(reaction.Match) + if err != nil { + log.Error("Error compiling regex").Err(err).Send() + continue + } + + var content string + switch reaction.ReactionType { + case db.ReactionTypeText: + submatch := re.FindSubmatch([]byte(mc.Content)) + if len(submatch) > 1 { + replacements := map[string]any{} + for i, match := range submatch { + replacements[strconv.Itoa(i)] = match + } + content = fasttemplate.ExecuteStringStd(reaction.Reaction, "{", "}", replacements) + } else if len(submatch) == 1 { + content = reaction.Reaction + } + case db.ReactionTypeEmoji: + if re.MatchString(mc.Content) { + content = reaction.Reaction + } + } + + if content != "" { + err = performReaction(s, reaction, content, mc) + if err != nil { + log.Error("Error performing reaction").Err(err).Send() + continue + } + } + } + } +} + +var ( + rngMtx = sync.Mutex{} + rng = rand.New(rand.NewSource(time.Now().UnixNano())) +) + +func performReaction(s *discordgo.Session, reaction db.Reaction, content string, mc *discordgo.MessageCreate) error { + if reaction.Chance < 100 { + rngMtx.Lock() + randNum := rng.Intn(100) + 1 + rngMtx.Unlock() + if randNum > reaction.Chance { + return nil + } + } + + switch reaction.ReactionType { + case db.ReactionTypeText: + _, err := s.ChannelMessageSendReply(mc.ChannelID, content, mc.Reference()) + if err != nil { + return err + } + case db.ReactionTypeEmoji: + var emojis []string + if strings.Contains(content, ",") { + emojis = strings.Split(content, ",") + } else { + emojis = []string{content} + } + + for _, emojiStr := range emojis { + e, ok := emoji.Parse(emojiStr) + if !ok { + return fmt.Errorf("invalid emoji: %s", emojiStr) + } + + err := s.MessageReactionAdd(mc.ChannelID, mc.ID, e.APIFormat()) + if err != nil { + return err + } + } + } + return nil +} diff --git a/internal/systems/roles/commands.go b/internal/systems/roles/commands.go new file mode 100644 index 0000000..b7be7a7 --- /dev/null +++ b/internal/systems/roles/commands.go @@ -0,0 +1,215 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package roles + +import ( + "fmt" + "strings" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/owobot/internal/db" + "go.elara.ws/owobot/internal/emoji" + "go.elara.ws/owobot/internal/util" +) + +// reactionRolesCmd calls the correct subcommand handler for the reaction_roles command +func reactionRolesCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + + switch name := data.Options[0].Name; name { + case "new_category": + return reactionRolesNewCategoryCmd(s, i) + case "remove_category": + return reactionRolesRemoveCategoryCmd(s, i) + case "add": + return reactionRolesAddCmd(s, i) + case "remove": + return reactionRolesRemoveCmd(s, i) + default: + return fmt.Errorf("unknown reaction_roles subcommand: %s", name) + } +} + +// reactionRolesNewCategoryCmd creates a new reaction role category. +func reactionRolesNewCategoryCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + args := data.Options[0].Options + + rrc := db.ReactionRoleCategory{ + Name: args[0].StringValue(), + } + + if len(args) > 1 { + rrc.Description = args[1].StringValue() + } + + msg, err := s.ChannelMessageSendEmbed(i.ChannelID, &discordgo.MessageEmbed{ + Title: rrc.Name, + Description: rrc.Description, + }) + if err != nil { + return err + } + + rrc.MsgID = msg.ID + err = db.AddReactionRoleCategory(i.ChannelID, rrc) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully added a new reaction role category called `%s`!", rrc.Name)) +} + +// reactionRolesRemoveCategoryCmd removes an existing reaction role category. +func reactionRolesRemoveCategoryCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + args := data.Options[0].Options + + name := args[0].StringValue() + + rrc, err := db.GetReactionRoleCategory(i.ChannelID, name) + if err != nil { + return err + } + + err = s.ChannelMessageDelete(rrc.ChannelID, rrc.MsgID) + if err != nil { + return err + } + + err = db.DeleteReactionRoleCategory(i.ChannelID, name) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Removed reaction role category `%s`", args[0].StringValue())) +} + +// reactionRolesAddCmd adds a reaction role to a category. +func reactionRolesAddCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + args := data.Options[0].Options + + category := args[0].StringValue() + role := args[1].RoleValue(s, i.GuildID) + emojiStr := args[2].StringValue() + + _, ok := emoji.Parse(emojiStr) + if !ok { + return fmt.Errorf("invalid reaction role emoji: %s", emojiStr) + } + + err := db.AddReactionRole(i.ChannelID, category, emojiStr, role) + if err != nil { + return err + } + + err = updateReactionRoleCategoryMsg(s, i.ChannelID, category) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Added reaction role %s to `%s`", role.Mention(), category)) +} + +// reactionRolesRemoveCmd removes a reaction role from a category. +func reactionRolesRemoveCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + args := data.Options[0].Options + + category := args[0].StringValue() + role := args[1].RoleValue(s, i.GuildID) + + err := db.DeleteReactionRole(i.ChannelID, category, role) + if err != nil { + return err + } + + err = updateReactionRoleCategoryMsg(s, i.ChannelID, category) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Removed reaction role %s from `%s`", role.Mention(), category)) +} + +// updateReactionRoleCategoryMsg updates a reaction role category message +func updateReactionRoleCategoryMsg(s *discordgo.Session, channelID, category string) error { + rrc, err := db.GetReactionRoleCategory(channelID, category) + if err != nil { + return err + } + + var sb strings.Builder + if rrc.Description != "" { + sb.WriteString(rrc.Description) + sb.WriteString("\n\n") + } + + var ( + components []discordgo.MessageComponent + currentRow discordgo.ActionsRow + ) + + for i, roleID := range rrc.Roles { + // Action rows can only contain 5 elements, + // so we create a new row if we reach a multiple + // of 5. + if i > 0 && i%5 == 0 { + components = append(components, currentRow) + currentRow = discordgo.ActionsRow{} + } + + e, ok := emoji.Parse(rrc.Emoji[i]) + if !ok { + return fmt.Errorf("invalid reaction role emoji: %s", rrc.Emoji[i]) + } + + sb.WriteString(rrc.Emoji[i]) + sb.WriteString(" - <@&") + sb.WriteString(roleID) + sb.WriteString(">\n") + + currentRow.Components = append(currentRow.Components, discordgo.Button{ + CustomID: "role:" + roleID, + Style: discordgo.SecondaryButton, + Emoji: discordgo.ComponentEmoji{ + Name: e.Name, + ID: e.ID, + }, + }) + } + + if len(currentRow.Components) > 0 { + components = append(components, currentRow) + } + + _, err = s.ChannelMessageEditComplex(&discordgo.MessageEdit{ + Channel: channelID, + ID: rrc.MsgID, + Embeds: []*discordgo.MessageEmbed{ + { + Title: rrc.Name, + Description: sb.String(), + }, + }, + Components: components, + }) + return err +} diff --git a/internal/systems/roles/neopronouns.go b/internal/systems/roles/neopronouns.go new file mode 100644 index 0000000..ede141c --- /dev/null +++ b/internal/systems/roles/neopronouns.go @@ -0,0 +1,88 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package roles + +import ( + "fmt" + "regexp" + "slices" + "strings" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/owobot/internal/cache" + "go.elara.ws/owobot/internal/util" +) + +var neopronounValidationRegex = regexp.MustCompile(`^[a-z]+(/[a-z]+)+$`) + +// neopronounCmd assigns a neopronoun role to the user that ran it. +func neopronounCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + name := data.Options[0].StringValue() + name = strings.ToLower(name) + + if !neopronounValidationRegex.MatchString(name) { + return fmt.Errorf("invalid neopronoun: `%s`", name) + } + + roles, err := cache.Roles(s, i.GuildID) + if err != nil { + return err + } + + var roleID string + for _, role := range roles { + // Skip this role if it provides any permissions, so that + // we don't accidentally grant the member any extra permissions + if role.Permissions != 0 { + continue + } + + if role.Name == name { + roleID = role.ID + break + } + } + + if roleID == "" { + role, err := s.GuildRoleCreate(i.GuildID, &discordgo.RoleParams{ + Name: name, + Mentionable: util.Pointer(false), + Permissions: util.Pointer[int64](0), + }) + if err != nil { + return err + } + roleID = role.ID + } + + if slices.Contains(i.Member.Roles, roleID) { + err = s.GuildMemberRoleRemove(i.GuildID, i.Member.User.ID, roleID) + if err != nil { + return err + } + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Unassigned the `%s` role", name)) + } else { + err = s.GuildMemberRoleAdd(i.GuildID, i.Member.User.ID, roleID) + if err != nil { + return err + } + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully assigned the `%s` role to you!", name)) + } +} diff --git a/internal/systems/roles/roles.go b/internal/systems/roles/roles.go new file mode 100644 index 0000000..1e7cc9f --- /dev/null +++ b/internal/systems/roles/roles.go @@ -0,0 +1,161 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package roles + +import ( + "fmt" + "slices" + "strings" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/owobot/internal/systems/commands" + "go.elara.ws/owobot/internal/util" +) + +func Init(s *discordgo.Session) error { + s.AddHandler(util.InteractionErrorHandler("on-role-btn", onRoleButton)) + + commands.Register(s, reactionRolesCmd, &discordgo.ApplicationCommand{ + Name: "reaction_roles", + Description: "Manage reaction roles", + DefaultMemberPermissions: util.Pointer[int64](discordgo.PermissionManageServer), + Options: []*discordgo.ApplicationCommandOption{ + { + Type: discordgo.ApplicationCommandOptionSubCommand, + Name: "new_category", + Description: "Create a new reaction role category", + Options: []*discordgo.ApplicationCommandOption{ + { + Type: discordgo.ApplicationCommandOptionString, + Name: "name", + Description: "The name of the category", + Required: true, + }, + { + Type: discordgo.ApplicationCommandOptionString, + Name: "description", + Description: "The description of the reaction role category", + }, + }, + }, + { + Type: discordgo.ApplicationCommandOptionSubCommand, + Name: "remove_category", + Description: "Remove a reaction role category", + Options: []*discordgo.ApplicationCommandOption{ + { + Type: discordgo.ApplicationCommandOptionString, + Name: "name", + Description: "The category which should be removed", + Required: true, + }, + }, + }, + { + Type: discordgo.ApplicationCommandOptionSubCommand, + Name: "add", + Description: "Create a new reaction role", + Options: []*discordgo.ApplicationCommandOption{ + { + Type: discordgo.ApplicationCommandOptionString, + Name: "category", + Description: "The category to which the reaction role will be added", + Required: true, + }, + { + Type: discordgo.ApplicationCommandOptionRole, + Name: "role", + Description: "The role to add", + Required: true, + }, + { + Type: discordgo.ApplicationCommandOptionString, + Name: "emoji", + Description: "The emoji to use for the role", + Required: true, + }, + }, + }, + { + Type: discordgo.ApplicationCommandOptionSubCommand, + Name: "remove", + Description: "Remove a reaction role", + Options: []*discordgo.ApplicationCommandOption{ + { + Type: discordgo.ApplicationCommandOptionString, + Name: "category", + Description: "The category from which to remove the reaction role", + Required: true, + }, + { + Type: discordgo.ApplicationCommandOptionRole, + Name: "role", + Description: "The role to remove", + Required: true, + }, + }, + }, + }, + }) + + commands.Register(s, neopronounCmd, &discordgo.ApplicationCommand{ + Name: "neopronoun", + Description: "Assign a neopronoun role to yourself", + Options: []*discordgo.ApplicationCommandOption{ + { + Type: discordgo.ApplicationCommandOptionString, + Name: "neopronoun", + Description: "The neopronouns to assign to you", + Required: true, + }, + }, + }) + + return nil +} + +// onRoleButton handles users clicking a role reaction button. It checks if they have +// the role the button is codes for, and if they do, it removes it. Otherwise, it +// assigns it to them. +func onRoleButton(s *discordgo.Session, i *discordgo.InteractionCreate) error { + if i.Type != discordgo.InteractionMessageComponent { + return nil + } + + data := i.MessageComponentData() + + buttonID, roleID, ok := strings.Cut(data.CustomID, ":") + if !ok || buttonID != "role" { + return nil + } + + if slices.Contains(i.Member.Roles, roleID) { + err := s.GuildMemberRoleRemove(i.GuildID, i.Member.User.ID, roleID) + if err != nil { + return err + } + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Unassigned role <@&%s>", roleID)) + } else { + err := s.GuildMemberRoleAdd(i.GuildID, i.Member.User.ID, roleID) + if err != nil { + return err + } + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully assigned role <@&%s> to you", roleID)) + } +} diff --git a/internal/systems/starboard/starboard.go b/internal/systems/starboard/starboard.go new file mode 100644 index 0000000..5bfd946 --- /dev/null +++ b/internal/systems/starboard/starboard.go @@ -0,0 +1,258 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package starboard + +import ( + "errors" + "fmt" + "mime" + "net/url" + "path" + "strings" + "time" + + "mvdan.cc/xurls" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/logger/log" + "go.elara.ws/owobot/internal/db" + "go.elara.ws/owobot/internal/systems/commands" + "go.elara.ws/owobot/internal/util" +) + +const ( + starEmoji = "\u2b50" + embedColor = 0xFF5833 +) + +func Init(s *discordgo.Session) error { + s.AddHandler(onReaction) + + commands.Register(s, starboardCmd, &discordgo.ApplicationCommand{ + Name: "starboard", + Description: "Modify starboard settings", + DefaultMemberPermissions: util.Pointer[int64](discordgo.PermissionManageServer), + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "channel", + Description: "Set the starboard channel", + Type: discordgo.ApplicationCommandOptionSubCommand, + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "channel", + Description: "The channel to use for the starboard", + Type: discordgo.ApplicationCommandOptionChannel, + ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildText}, + Required: true, + }, + }, + }, + { + Name: "stars", + Description: "Set the amount of stars for the starboard", + Type: discordgo.ApplicationCommandOptionSubCommand, + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "stars", + Description: "The amount of stars to require", + Type: discordgo.ApplicationCommandOptionInteger, + Required: true, + }, + }, + }, + }, + }) + + return nil +} + +// starboardCmd calls the correct subcommand handler for the starboard command +func starboardCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + switch name := data.Options[0].Name; name { + case "channel": + return channelCmd(s, i) + case "stars": + return starsCmd(s, i) + default: + return fmt.Errorf("unknown subcommand: %s", name) + } +} + +// channelCmd sets the starboard channel for the guild +func channelCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + // Get the subcommand options + args := i.ApplicationCommandData().Options[0].Options + + c := args[0].ChannelValue(s) + err := db.SetStarboardChannel(i.GuildID, c.ID) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully set starboard channel to <#%s>!", c.ID)) +} + +// starsCmd sets the amount of stars that trigger the starboard for the guild +func starsCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + // Get the subcommand options + args := i.ApplicationCommandData().Options[0].Options + + stars := args[0].IntValue() + if stars <= 0 { + return errors.New("star amount must be greater than 0") + } + + err := db.SetStarboardStars(i.GuildID, stars) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully set the amount of stars required to get on the starboard to %d!", stars)) +} + +// onReaction detects star reactions, and if the message qualifies for starboard +// based on the guild's settings, it replies to it and adds it to the starboard. +func onReaction(s *discordgo.Session, mra *discordgo.MessageReactionAdd) { + if mra.Emoji.Name != starEmoji { + return + } + + msgExists, err := db.ExistsInStarboard(mra.MessageID) + if err != nil { + log.Warn("Error checking if the message exists in the starboard").Err(err).Send() + return + } + + // If the message has already been added to the starboard, + // we can skip it. + if msgExists { + return + } + + guild, err := db.GuildByID(mra.GuildID) + if err != nil { + log.Warn("Error getting guild from the database").Str("id", mra.GuildID).Err(err).Send() + return + } + + // If the guild has no starboard channel ID set, we can + // skip this message. + if guild.StarboardChanID == "" { + return + } + + reactions, err := s.MessageReactions(mra.ChannelID, mra.MessageID, starEmoji, guild.StarboardStars, "", "") + if err != nil { + log.Warn("Error getting message reactions").Err(err).Send() + return + } + + if len(reactions) >= guild.StarboardStars { + msg, err := s.ChannelMessage(mra.ChannelID, mra.MessageID) + if err != nil { + log.Warn("Error getting channel message").Err(err).Send() + return + } + + ch, err := s.Channel(mra.ChannelID) + if err != nil { + log.Warn("Error getting channel").Err(err).Send() + return + } + + _, err = s.ChannelMessageSendReply( + msg.ChannelID, + fmt.Sprintf("Congrats %s! You've made it to <#%s>!!", msg.Author.Mention(), guild.StarboardChanID), + msg.Reference(), + ) + if err != nil { + log.Warn("Error sending message reply").Err(err).Send() + return + } + + embed := &discordgo.MessageEmbed{ + Title: fmt.Sprintf("%s - #%s - %s has made it!", starEmoji, ch.Name, msg.Author.Username), + Author: &discordgo.MessageEmbedAuthor{ + Name: msg.Author.Username, + IconURL: msg.Author.AvatarURL(""), + }, + Description: fmt.Sprintf( + "[**Jump to Message**](https://discord.com/channels/%s/%s/%s)", + msg.GuildID, + msg.ChannelID, + msg.ID, + ), + Color: embedColor, + Footer: &discordgo.MessageEmbedFooter{ + Text: util.FormatJucheTime(time.Now()), + }, + } + + if imageURL := getImageURL(msg); imageURL != "" { + // If the message has an image, add it to the embed + embed.Image = &discordgo.MessageEmbedImage{URL: imageURL} + } + + if msg.Content != "" { + // If the message has content, we add it above the + // jump to message link currently in the embed description. + embed.Description = fmt.Sprintf( + "**Message Content**\n%s\n\n%s", + msg.Content, + embed.Description, + ) + } + + _, err = s.ChannelMessageSendEmbed(guild.StarboardChanID, embed) + if err != nil { + log.Warn("Error sending starboard message").Err(err).Send() + return + } + + err = db.AddToStarboard(mra.MessageID) + if err != nil { + log.Warn("Error adding message to starboard").Err(err).Send() + return + } + } +} + +// getImageURL looks through the message content and attachments +// to try to find images. If it finds one, it returns the URL. +// Otherwise, it returns an empty string. +func getImageURL(msg *discordgo.Message) string { + if xurl := xurls.Strict.FindString(msg.Content); xurl != "" { + u, err := url.Parse(xurl) + if err == nil { + mt := mime.TypeByExtension(path.Ext(u.Path)) + if strings.HasPrefix(mt, "image/") { + return xurl + } + } + } + + for _, attachment := range msg.Attachments { + if strings.HasPrefix(attachment.ContentType, "image/") { + return attachment.URL + } + } + + return "" +} diff --git a/internal/systems/tickets/tickets.go b/internal/systems/tickets/tickets.go new file mode 100644 index 0000000..d020796 --- /dev/null +++ b/internal/systems/tickets/tickets.go @@ -0,0 +1,256 @@ +package tickets + +import ( + "bytes" + "database/sql" + "errors" + "fmt" + "io" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/logger/log" + "go.elara.ws/owobot/internal/db" + "go.elara.ws/owobot/internal/systems/commands" + "go.elara.ws/owobot/internal/systems/eventlog" + "go.elara.ws/owobot/internal/util" +) + +const ticketPermissions = discordgo.PermissionSendMessages | discordgo.PermissionViewChannel | discordgo.PermissionReadMessageHistory + +func Init(s *discordgo.Session) error { + s.AddHandler(onMemberLeave) + + commands.Register(s, ticketCmd, &discordgo.ApplicationCommand{ + Name: "ticket", + Description: "Open a ticket to talk to the mods", + }) + + commands.Register(s, ticketCategoryCmd, &discordgo.ApplicationCommand{ + Name: "ticket_category", + Description: "Set the category in which to create ticket channels", + DefaultMemberPermissions: util.Pointer[int64](discordgo.PermissionManageServer), + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "category", + Description: "The category to put ticket channels in", + Type: discordgo.ApplicationCommandOptionChannel, + ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildCategory}, + Required: true, + }, + }, + }) + + commands.Register(s, modTicketCmd, &discordgo.ApplicationCommand{ + Name: "mod_ticket", + Description: "Open a ticket for a user to talk to the mods", + DefaultMemberPermissions: util.Pointer[int64](discordgo.PermissionManageChannels), + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "user", + Description: "The user to open a ticket for", + Type: discordgo.ApplicationCommandOptionUser, + Required: true, + }, + }, + }) + + commands.Register(s, closeTicketCmd, &discordgo.ApplicationCommand{ + Name: "close_ticket", + Description: "Close a user's ticket", + DefaultMemberPermissions: util.Pointer[int64](discordgo.PermissionManageChannels), + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "user", + Description: "The user whose ticket to close", + Type: discordgo.ApplicationCommandOptionUser, + Required: true, + }, + }, + }) + + return nil +} + +// ticketCategoryCmd sets the category in which future ticket channels will be created +func ticketCategoryCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + category := data.Options[0].ChannelValue(s) + err := db.SetTicketCategory(i.GuildID, category.ID) + if err != nil { + return err + } + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully set the ticket category to `%s`!", category.Name)) +} + +// modTicketCmd handles the mod_ticket command. It opens a new ticket for the given user. +func modTicketCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + chID, err := Open(s, i.GuildID, data.Options[0].UserValue(s), i.Member.User) + if err != nil { + return err + } + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully opened a ticket at <#%s>!", chID)) +} + +// ticketCmd handles the ticket command. It opens a new ticket for the user that ran it. +func ticketCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + chID, err := Open(s, i.GuildID, i.Member.User, i.Member.User) + if err != nil { + return err + } + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully opened a ticket at <#%s>!", chID)) +} + +// closeTicketCmd handles the close_ticket command. It closes the ticket that the given user +// has open if it exists. +func closeTicketCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + user := data.Options[0].UserValue(s) + err := Close(s, i.GuildID, user, i.Member.User) + if err != nil { + return err + } + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully closed ticket for <@%s>", user.ID)) +} + +// onMemberLeave closes any tickets a user had open when they leave +func onMemberLeave(s *discordgo.Session, gmr *discordgo.GuildMemberRemove) { + // If the user had a ticket open when they left, make sure to close it. + err := Close(s, gmr.GuildID, gmr.User, s.State.User) + if errors.Is(err, sql.ErrNoRows) { + // If the error is ErrNoRows, the user didn't have a ticket, so just return + return + } else if err != nil { + log.Warn("Error removing ticket after user left").Err(err).Send() + return + } +} + +// Open opens a new ticket. It checks if a ticket already exists, and if not, creates a new channel for it, +// allows the user it's for to see and send messages in it, adds it to the database, and logs the ticket open. +func Open(s *discordgo.Session, guildID string, user, executor *discordgo.User) (string, error) { + channelID, err := db.TicketChannelID(guildID, user.ID) + if err == nil { + return "", fmt.Errorf("ticket already exists for %s at <#%s>", user.Mention(), channelID) + } + + guild, err := db.GuildByID(guildID) + if err != nil { + return "", err + } + + c, err := s.GuildChannelCreateComplex(guildID, discordgo.GuildChannelCreateData{ + Name: "ticket-" + user.Username, + Type: discordgo.ChannelTypeGuildText, + ParentID: guild.TicketCategoryID, + PermissionOverwrites: []*discordgo.PermissionOverwrite{{ + ID: user.ID, + Type: discordgo.PermissionOverwriteTypeMember, + Allow: ticketPermissions, + }}, + }) + if err != nil { + return "", err + } + + err = db.AddTicket(guildID, user.ID, c.ID) + if err != nil { + return "", err + } + + return c.ID, eventlog.Log(s, guildID, eventlog.Entry{ + Title: "New ticket opened!", + Description: "**Executed by:** " + executor.Mention(), + Author: user, + }) +} + +// Close closes the given user's ticket. It gets the channel ID of the ticket, logs all the messages +// inside it, deletes the channel, removes the ticket from the database, and logs the ticket close. +func Close(s *discordgo.Session, guildID string, user, executor *discordgo.User) error { + channelID, err := db.TicketChannelID(guildID, user.ID) + if err != nil { + return err + } + + guild, err := db.GuildByID(guildID) + if err != nil { + return err + } + + if guild.TicketLogChanID != "" { + buf, err := getChannelMessageLog(s, channelID) + if err != nil { + return err + } + + if buf != nil { + err = eventlog.TicketMsgLog(s, guildID, buf) + if err != nil { + return err + } + } + } + + _, err = s.ChannelDelete(channelID) + if err != nil { + return err + } + + err = db.RemoveTicket(guildID, user.ID) + if err != nil { + return err + } + + return eventlog.Log(s, guildID, eventlog.Entry{ + Title: "Ticket Closed", + Description: "**Executed by:** " + executor.Mention(), + Author: user, + }) +} + +// getChannelMessageLog generates a log for the given channel. It retrieves all the messages +// inside it and writes them to a buffer. +func getChannelMessageLog(s *discordgo.Session, channelID string) (*bytes.Buffer, error) { + out := &bytes.Buffer{} + + msgs, err := s.ChannelMessages(channelID, 100, "", "", "") + if err != nil { + return nil, err + } + + if len(msgs) == 0 { + return nil, nil + } + + err = writeMsgs(msgs, out) + if err != nil { + return nil, err + } + + msgAmt := len(msgs) + for msgAmt == 100 { + innerMsgs, err := s.ChannelMessages(channelID, 100, "", msgs[99].ID, "") + if err != nil { + return nil, err + } + err = writeMsgs(innerMsgs, out) + if err != nil { + return nil, err + } + msgAmt = len(innerMsgs) + } + + return out, nil +} + +// writeMsgs writes a slice of messages to w. +func writeMsgs(msgs []*discordgo.Message, w io.Writer) error { + for _, msg := range msgs { + _, err := io.WriteString(w, fmt.Sprintf("%s - %s\n", msg.Author.Username, msg.Content)) + if err != nil { + return err + } + } + return nil +} diff --git a/internal/systems/vetting/handlers.go b/internal/systems/vetting/handlers.go new file mode 100644 index 0000000..b29ae06 --- /dev/null +++ b/internal/systems/vetting/handlers.go @@ -0,0 +1,336 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package vetting + +import ( + "database/sql" + "errors" + "fmt" + "slices" + "strings" + "time" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/logger/log" + "go.elara.ws/owobot/internal/cache" + "go.elara.ws/owobot/internal/db" + "go.elara.ws/owobot/internal/systems/eventlog" + "go.elara.ws/owobot/internal/systems/tickets" + "go.elara.ws/owobot/internal/util" +) + +// vettingCmd runs the correct subcommand handler for the vetting command +func vettingCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + switch name := data.Options[0].Name; name { + case "role": + return vettingRoleCmd(s, i) + case "req_channel": + return vettingReqChannelCmd(s, i) + default: + return fmt.Errorf("unknown vetting subcommand: %s", name) + } +} + +// vettingRoleCmd sets the vetting role for a guild +func vettingRoleCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + args := data.Options[0].Options + role := args[0].RoleValue(s, i.GuildID) + + err := db.SetVettingRoleID(i.GuildID, role.ID) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully set %s as the vetting role!", role.Mention())) +} + +// vettingReqChannelCmd sets the vettign request channel for a guild +func vettingReqChannelCmd(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + args := data.Options[0].Options + channel := args[0].ChannelValue(s) + + err := db.SetVettingReqChannel(i.GuildID, channel.ID) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, fmt.Sprintf("Successfully set %s as the vetting request channel!", channel.Mention())) +} + +// onMemberJoin adds the vetting role to a user when they join in order to allow them +// to access the vetting questions +func onMemberJoin(s *discordgo.Session, gma *discordgo.GuildMemberAdd) { + guild, err := db.GuildByID(gma.GuildID) + if err != nil { + log.Warn("Error getting guild from database").Str("guild-id", gma.GuildID).Str("task", "vetting-member-join").Err(err).Send() + return + } + + if guild.VettingRoleID == "" { + return + } + + err = s.GuildMemberRoleAdd(gma.GuildID, gma.User.ID, guild.VettingRoleID) + if err != nil { + log.Warn("Error assigning vetting role to new user").Str("guild-id", gma.GuildID).Str("task", "vetting-member-join").Err(err).Send() + return + } +} + +// onMakeVettingMsg deletes and reposts a message with a vetting request button +// that allows users to request vetting. +func onMakeVettingMsg(s *discordgo.Session, i *discordgo.InteractionCreate) error { + data := i.ApplicationCommandData() + msg := data.Resolved.Messages[data.TargetID] + + err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseChannelMessageWithSource, + Data: &discordgo.InteractionResponseData{ + Content: msg.Content, + Components: []discordgo.MessageComponent{ + discordgo.ActionsRow{Components: []discordgo.MessageComponent{ + discordgo.Button{ + Label: "Request Vetting", + Style: discordgo.SuccessButton, + Disabled: false, + Emoji: discordgo.ComponentEmoji{Name: clipboardEmoji}, + CustomID: "vetting-req", + }, + }}, + }, + }, + }) + if err != nil { + return err + } + + return s.ChannelMessageDelete(msg.ChannelID, msg.ID) +} + +// onVettingRequest handles sends vetting requests in the vetting request channel +func onVettingRequest(s *discordgo.Session, i *discordgo.InteractionCreate) error { + if i.Type != discordgo.InteractionMessageComponent { + return nil + } + + data := i.MessageComponentData() + + if data.CustomID != "vetting-req" { + return nil + } + + guild, err := db.GuildByID(i.GuildID) + if err != nil { + return err + } + + if guild.VettingRoleID == "" || guild.VettingReqChanID == "" { + return nil + } + + if !slices.Contains(i.Member.Roles, guild.VettingRoleID) { + return errors.New("you do not have the vetting role") + } + + _, err = s.ChannelMessageSendComplex(guild.VettingReqChanID, &discordgo.MessageSend{ + Embed: &discordgo.MessageEmbed{ + Title: "Vetting Request", + Author: &discordgo.MessageEmbedAuthor{ + Name: i.Member.User.Username, + IconURL: i.Member.User.AvatarURL(""), + }, + Description: "Accept the vetting request to create a ticket, or reject it to kick the user.", + Footer: &discordgo.MessageEmbedFooter{ + Text: util.FormatJucheTime(time.Now()), + }, + }, + Components: []discordgo.MessageComponent{ + discordgo.ActionsRow{Components: []discordgo.MessageComponent{ + discordgo.Button{ + Label: "Accept", + Emoji: discordgo.ComponentEmoji{Name: checkEmoji}, + Style: discordgo.SuccessButton, + CustomID: "vetting-accept:" + i.Member.User.ID, + }, + discordgo.Button{ + Label: "Reject", + Emoji: discordgo.ComponentEmoji{Name: crossEmoji}, + Style: discordgo.DangerButton, + CustomID: "vetting-reject:" + i.Member.User.ID, + }, + }}, + }, + }) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, "Successfully sent your vetting request!") +} + +// onApprove approves a user in vetting. It removes their vetting role, assigns a +// role of the approver's choosing, closes the user's vetting ticket, and logs +// the approval. +func onApprove(s *discordgo.Session, i *discordgo.InteractionCreate) error { + guild, err := db.GuildByID(i.GuildID) + if err != nil { + return err + } + + if guild.VettingRoleID == "" { + return errors.New("vetting role id is not set for this guild") + } + + data := i.ApplicationCommandData() + user := data.Options[0].UserValue(s) + role := data.Options[1].RoleValue(s, i.GuildID) + + _, err = db.TicketChannelID(i.GuildID, user.ID) + if errors.Is(err, sql.ErrNoRows) { + return fmt.Errorf("%s has no open ticket", user.Mention()) + } + + roleSetAllowed := false + for _, roleID := range i.Member.Roles { + executorRole, err := cache.Role(s, i.GuildID, roleID) + if err != nil { + return err + } + if executorRole.Position >= role.Position { + roleSetAllowed = true + break + } + } + + if !roleSetAllowed { + return errors.New("you don't have permission to approve a user as a role higher than your own") + } + + err = s.GuildMemberRoleAdd(i.GuildID, user.ID, role.ID) + if err != nil { + return err + } + + err = s.GuildMemberRoleRemove(i.GuildID, user.ID, guild.VettingRoleID) + if err != nil { + return err + } + + err = tickets.Close(s, i.GuildID, user, i.Member.User) + if err != nil { + return err + } + + err = eventlog.Log(s, i.GuildID, eventlog.Entry{ + Title: "New Member Approved!", + Description: fmt.Sprintf("User: %s\nRole: %s\nApproved By: %s", user.Mention(), role.Mention(), i.Member.User.Mention()), + Author: user, + }) + if err != nil { + return err + } + + return util.RespondEphemeral(s, i.Interaction, "Successfully approved "+user.Mention()+" as "+role.Mention()+"!") +} + +// onVettingResponse handles responses to vetting requests. If the user was accepted, +// it creates a vetting ticket for them. If they were rejected, it kicks them from the server. +func onVettingResponse(s *discordgo.Session, i *discordgo.InteractionCreate) error { + if i.Type != discordgo.InteractionMessageComponent { + return nil + } + + data := i.MessageComponentData() + + resType, userID, ok := strings.Cut(data.CustomID, ":") + if !ok { + return nil + } + + if resType != "vetting-accept" && resType != "vetting-reject" { + return nil + } + + executor := i.Member + member, err := cache.Member(s, i.GuildID, userID) + if err != nil { + return err + } + + switch resType { + case "vetting-accept": + channelID, err := tickets.Open(s, i.GuildID, member.User, executor.User) + if err != nil { + return err + } + + err = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseUpdateMessage, + Data: &discordgo.InteractionResponseData{ + Embeds: []*discordgo.MessageEmbed{ + { + Title: "Vetting Request Accepted!", + Description: fmt.Sprintf("This vetting request has been accepted and a vetting ticket has been created at <#%s>.\n\n**Accepted By:** <@%s>", channelID, executor.User.ID), + Author: &discordgo.MessageEmbedAuthor{ + Name: member.User.Username, + IconURL: member.User.AvatarURL(""), + }, + Footer: &discordgo.MessageEmbedFooter{ + Text: util.FormatJucheTime(time.Now()), + }, + }, + }, + }, + }) + if err != nil { + return err + } + case "vetting-reject": + err = s.GuildMemberDeleteWithReason(i.GuildID, member.User.ID, "Vetting request rejected") + if err != nil { + return err + } + + err = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseUpdateMessage, + Data: &discordgo.InteractionResponseData{ + Embeds: []*discordgo.MessageEmbed{ + { + Title: "Vetting Request Rejected", + Description: fmt.Sprintf("This vetting request has been rejected and <@%s> has been kicked from the server.\n\n**Rejected By:** <@%s>", member.User.ID, executor.User.ID), + Author: &discordgo.MessageEmbedAuthor{ + Name: member.User.Username, + IconURL: member.User.AvatarURL(""), + }, + Footer: &discordgo.MessageEmbedFooter{ + Text: util.FormatJucheTime(time.Now()), + }, + }, + }, + }, + }) + if err != nil { + return err + } + } + return nil +} diff --git a/internal/systems/vetting/vetting.go b/internal/systems/vetting/vetting.go new file mode 100644 index 0000000..e547302 --- /dev/null +++ b/internal/systems/vetting/vetting.go @@ -0,0 +1,100 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package vetting + +import ( + "github.com/bwmarrin/discordgo" + "go.elara.ws/owobot/internal/systems/commands" + "go.elara.ws/owobot/internal/util" +) + +const ( + clipboardEmoji = "\U0001f4cb" + checkEmoji = "\u2705" + crossEmoji = "\u2694\ufe0f" +) + +func Init(s *discordgo.Session) error { + commands.Register(s, onMakeVettingMsg, &discordgo.ApplicationCommand{ + Name: "Make Vetting Message", + Type: discordgo.MessageApplicationCommand, + DefaultMemberPermissions: util.Pointer[int64](discordgo.PermissionManageServer), + }) + + commands.Register(s, vettingCmd, &discordgo.ApplicationCommand{ + Name: "vetting", + Description: "Manage vetting", + DefaultMemberPermissions: util.Pointer[int64](discordgo.PermissionManageServer), + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "role", + Description: "Set the vetting role", + Type: discordgo.ApplicationCommandOptionSubCommand, + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "role", + Description: "The role to use for vetting", + Type: discordgo.ApplicationCommandOptionRole, + Required: true, + }, + }, + }, + { + Name: "req_channel", + Description: "Set the vetting request channel", + Type: discordgo.ApplicationCommandOptionSubCommand, + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "role", + Description: "The channel to use for vetting requests", + Type: discordgo.ApplicationCommandOptionChannel, + ChannelTypes: []discordgo.ChannelType{discordgo.ChannelTypeGuildText}, + Required: true, + }, + }, + }, + }, + }) + + commands.Register(s, onApprove, &discordgo.ApplicationCommand{ + Name: "approve", + Description: "Approve a member in vetting", + DefaultMemberPermissions: util.Pointer[int64](discordgo.PermissionKickMembers), + Options: []*discordgo.ApplicationCommandOption{ + { + Name: "member", + Description: "The member to approve", + Type: discordgo.ApplicationCommandOptionUser, + Required: true, + }, + { + Name: "role", + Description: "The role to approve the member as", + Type: discordgo.ApplicationCommandOptionRole, + Required: true, + }, + }, + }) + + s.AddHandler(onMemberJoin) + s.AddHandler(util.InteractionErrorHandler("on-vetting-req", onVettingRequest)) + s.AddHandler(util.InteractionErrorHandler("on-vetting-resp", onVettingResponse)) + + return nil +} diff --git a/internal/util/util.go b/internal/util/util.go new file mode 100644 index 0000000..b4eb49b --- /dev/null +++ b/internal/util/util.go @@ -0,0 +1,82 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package util + +import ( + "fmt" + "time" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/logger/log" +) + +// Pointer returns a pointer to v. This is useful +// for creating pointers to literal values, as Go doesn't +// allow that by default. +func Pointer[T any](v T) *T { + return &v +} + +// FormatJucheTime formats the given time in Juche calendar format, +// using pyongyang time if it's available, and otherwise UTC. +func FormatJucheTime(t time.Time) string { + tz, err := time.LoadLocation("Asia/Pyongyang") + if err != nil { + tz = time.UTC + } + t = t.In(tz) + return fmt.Sprintf("%02d:%02d %02d-%02d Juche %d", t.Hour(), t.Minute(), t.Day(), t.Month(), t.Year()-1911) +} + +// RespondEphemeral responds to an interaction with an ephemeral message. +func RespondEphemeral(s *discordgo.Session, i *discordgo.Interaction, content string) error { + return s.InteractionRespond(i, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseChannelMessageWithSource, + Data: &discordgo.InteractionResponseData{ + Flags: discordgo.MessageFlagsEphemeral, + Content: content, + }, + }) +} + +// Respond responds to an interaction with a message. +func Respond(s *discordgo.Session, i *discordgo.Interaction, content string) error { + return s.InteractionRespond(i, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseChannelMessageWithSource, + Data: &discordgo.InteractionResponseData{ + Content: content, + }, + }) +} + +// InteractionErrorHandler takes an InteractionCreate event handler that returns an error, +// and returns a regular handler that handles any error by responding with an ephemeral +// message and logging to stderr. +func InteractionErrorHandler(name string, fn func(s *discordgo.Session, i *discordgo.InteractionCreate) error) func(s *discordgo.Session, i *discordgo.InteractionCreate) { + return func(s *discordgo.Session, i *discordgo.InteractionCreate) { + err := fn(s, i) + if err != nil { + log.Warn("Error in interaction handler").Str("name", name).Err(err).Send() + err = RespondEphemeral(s, i.Interaction, "ERROR: "+err.Error()) + if err != nil { + log.Warn("Error responding with error").Err(err).Send() + } + } + } +} diff --git a/internal/xsync/mutex.go b/internal/xsync/mutex.go new file mode 100644 index 0000000..3489a95 --- /dev/null +++ b/internal/xsync/mutex.go @@ -0,0 +1,43 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package xsync + +import "sync" + +// KeyedMutex is a mutex implementation using several independent keys +type KeyedMutex struct { + mutexes sync.Map +} + +// Lock locks a mutex with the given key. If a mutex with that key +// doesn't exist, a new one is created. +func (m *KeyedMutex) Lock(key string) { + value, _ := m.mutexes.LoadOrStore(key, &sync.Mutex{}) + mtx := value.(*sync.Mutex) + mtx.Lock() +} + +// Unlock unlocks a mutex with the given key if it exists. +func (m *KeyedMutex) Unlock(key string) { + value, ok := m.mutexes.Load(key) + if ok { + mtx := value.(*sync.Mutex) + mtx.Unlock() + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..c11e8b6 --- /dev/null +++ b/main.go @@ -0,0 +1,117 @@ +/* + * owobot - The coolest Discord bot ever written + * Copyright (C) 2023 owobot Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package main + +import ( + "context" + "os" + "os/signal" + "syscall" + + "github.com/bwmarrin/discordgo" + "go.elara.ws/logger" + "go.elara.ws/logger/log" + "go.elara.ws/owobot/internal/db" + "go.elara.ws/owobot/internal/systems/commands" + "go.elara.ws/owobot/internal/systems/eventlog" + "go.elara.ws/owobot/internal/systems/guilds" + "go.elara.ws/owobot/internal/systems/members" + "go.elara.ws/owobot/internal/systems/polls" + "go.elara.ws/owobot/internal/systems/reactions" + "go.elara.ws/owobot/internal/systems/roles" + "go.elara.ws/owobot/internal/systems/starboard" + "go.elara.ws/owobot/internal/systems/tickets" + "go.elara.ws/owobot/internal/systems/vetting" +) + +func init() { + log.Logger = logger.NewPretty(os.Stderr) +} + +func main() { + ctx := context.Background() + ctx, cancel := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) + defer cancel() + + cfg, err := loadEnv() + if err != nil { + log.Fatal("Error loading environment variables").Err(err).Send() + } + + err = db.Init(ctx, cfg.DBPath+"?_pragma=busy_timeout(30000)") + if err != nil { + log.Fatal("Error initializing database").Err(err).Send() + } + + s, err := discordgo.New("Bot " + cfg.Token) + if err != nil { + log.Fatal("Error creating new session").Err(err).Send() + } + + s.StateEnabled = true + s.State.TrackMembers = true + s.State.TrackRoles = true + s.Identify.Intents |= discordgo.IntentMessageContent | discordgo.IntentGuildMembers + + err = s.Open() + if err != nil { + log.Fatal("Error opening a connection to discord").Err(err).Send() + } + + if cfg.Activity.Type != -1 && cfg.Activity.Name != "" { + err = s.UpdateStatusComplex(discordgo.UpdateStatusData{Activities: []*discordgo.Activity{ + {Type: cfg.Activity.Type, Name: cfg.Activity.Name}, + }}) + if err != nil { + log.Error("Error updating status").Err(err).Send() + } + } + + initSystems( + s, + starboard.Init, + members.Init, + guilds.Init, + tickets.Init, + eventlog.Init, + polls.Init, + vetting.Init, + reactions.Init, + roles.Init, + commands.Init, // The commands system should always go last + ) + + log.Info("Everything is initialized, the bot is ready!").Send() + + select { + case <-ctx.Done(): + log.Info("Context canceled, shutting down...").Send() + s.Close() + db.Close() + } +} + +func initSystems(s *discordgo.Session, fns ...func(*discordgo.Session) error) { + for i, fn := range fns { + err := fn(s) + if err != nil { + log.Warn("Error initializing system").Int("index", i).Err(err).Send() + } + } +}