├── .github └── workflows │ └── python-package.yml ├── .gitignore ├── .readthedocs.yaml ├── CHANGELOG.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── docs ├── conf.py ├── configuration.rst ├── developer_guide.rst ├── index.rst ├── installation.rst └── user_guide.rst ├── pyproject.toml ├── src └── err-backend-discord │ ├── __init__.py │ ├── discordlib │ ├── person.py │ └── room.py │ ├── err-backend-discord.plug │ └── err-backend-discord.py ├── test-requirements.txt ├── tests ├── config-ci.py ├── conftest.py ├── test_backend.py ├── test_person.py └── test_room.py └── tox.ini /.github/workflows/python-package.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Discord 5 | 6 | on: 7 | push: 8 | branches: 9 | - master 10 | pull_request: 11 | branches: 12 | - master 13 | 14 | jobs: 15 | build: 16 | 17 | runs-on: ubuntu-latest 18 | strategy: 19 | fail-fast: false 20 | matrix: 21 | python-version: ["3.8", "3.9", "3.10", "3.11"] 22 | 23 | steps: 24 | - uses: actions/checkout@v4 25 | - name: Set up Python ${{ matrix.python-version }} 26 | uses: actions/setup-python@v4 27 | with: 28 | python-version: ${{ matrix.python-version }} 29 | 30 | - name: Install dependencies 31 | run: | 32 | python -m pip install --upgrade pip 33 | pip install -r test-requirements.txt 34 | # Temp fix for errbot py3.8 wheel on pypi missing dependency 35 | pip install graphlib-backport==1.0.3 36 | errbot --init 37 | cp tests/config-ci.py config.py 38 | 39 | - name: Test on ${{ matrix.python-version }} 40 | run: | 41 | tox -e py 42 | 43 | - name: Check Distribution 44 | if: matrix.python-version == 3.10 45 | run: | 46 | tox -e dist-check 47 | 48 | - name: Codestyle 49 | if: matrix.python-version == 3.10 50 | run: | 51 | tox -e codestyle 52 | 53 | - name: Lint - sort 54 | if: matrix.python-version == 3.10 55 | run: | 56 | tox -e sort 57 | 58 | - name: Security 59 | if: matrix.python-version == 3.10 60 | run: | 61 | tox -e security 62 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .venv 2 | __pycache__ 3 | dist 4 | .egg-info 5 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # .readthedocs.yaml 2 | # Read the Docs configuration file 3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 4 | 5 | # Required 6 | version: 2 7 | 8 | # Set the version of Python and other tools you might need 9 | build: 10 | os: ubuntu-22.04 11 | tools: 12 | python: "3.11" 13 | 14 | # Build documentation in the docs/ directory with Sphinx 15 | sphinx: 16 | configuration: docs/conf.py 17 | 18 | # We recommend specifying your dependencies to enable reproducible builds: 19 | # https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html 20 | # python: 21 | # install: 22 | # - requirements: docs/requirements.txt 23 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) 5 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 6 | 7 | ## [4.0.1] Unreleased 8 | 9 | ## [4.0.1] 2024-03-25 10 | 11 | ### Added 12 | 13 | ### Changed 14 | - Fixed variable name error in Person initilisation when using username and discriminator. 15 | - Updated String ID length to accept 18 or more digits. 16 | 17 | ### Removed 18 | 19 | ## [4.0.0] 2022-11-10 20 | 21 | ### Added 22 | - Added upgrade notes section to installation documentation. 23 | - Added intents management. 24 | 25 | ### Changed 26 | - Fixed copy/paste error in documentation. 27 | - Use the v2.0.1 discord python module. 28 | 29 | ### Removed 30 | - Support for python3.7 has been removed to allow the use of the v2.0.1 discord python module. 31 | 32 | ## [3.0.1] 2022-10-19 33 | 34 | ### Changed 35 | - Version bump for pypi release. 36 | 37 | 38 | ## [3.0.0] 2022-10-19 39 | 40 | ### Added 41 | 42 | ### Changed 43 | - Restructured code base to support packaging for pypi. 44 | - Migrated README documentation to readthedocs format. 45 | 46 | ### Removed 47 | 48 | 49 | ## [2.1.0] 2021-09-16 50 | 51 | ### Added 52 | - Support `#channel@guild_id` representation. 53 | 54 | ### Changed 55 | - Use discord client 1.7.3 56 | - Updated file_upload to support discord client v1.7.3. 57 | 58 | 59 | ## [2.0.0] 2021-01-14 60 | 61 | ### Changed 62 | - Use discord client 1.6.0 63 | - Discord client uses Member intents. 64 | 65 | ## [1.0.1] 2019-11-23 66 | ### Changed 67 | - Use discord client 1.2.5 68 | 69 | 70 | ## [1.0.0] 2019-10-18 71 | 72 | ### Added 73 | - Added changelog file. 74 | 75 | ### Changed 76 | - Use discord client 1.2.4 77 | 78 | ### Removed 79 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | err-backend-discord Copyright (C) 2022 errbot contributors 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include src/err-backend-discord/*.plug 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Discord backend for Errbot 2 | 3 | This is the Discord backend for errbot. 4 | 5 | # Documentation 6 | 7 | Visit the [official documentation](https://err-backend-discord.readthedocs.io/) where you'll find information on the following topics: 8 | - Installation 9 | - Configuration 10 | - User Guide 11 | - Developer Guide 12 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # http://www.sphinx-doc.org/en/master/config 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | # 13 | # import os 14 | # import sys 15 | # sys.path.insert(0, os.path.abspath('.')) 16 | 17 | 18 | # -- Project information ----------------------------------------------------- 19 | 20 | project = "errbot-backend-discord" 21 | copyright = "2019-20223, errbot-backend-discord contributors" 22 | author = "errbot-backend-discord contributors" 23 | 24 | # The full version, including alpha/beta/rc tags 25 | release = "4.0.0" 26 | 27 | 28 | # -- General configuration --------------------------------------------------- 29 | 30 | master_doc = "index" 31 | # Add any Sphinx extension module names here, as strings. They can be 32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 33 | # ones. 34 | extensions = [] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ["_templates"] 38 | 39 | # List of patterns, relative to source directory, that match files and 40 | # directories to ignore when looking for source files. 41 | # This pattern also affects html_static_path and html_extra_path. 42 | exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] 43 | 44 | 45 | # -- Options for HTML output ------------------------------------------------- 46 | 47 | # The theme to use for HTML and HTML Help pages. See the documentation for 48 | # a list of builtin themes. 49 | # 50 | # html_theme = 'alabaster' 51 | html_theme = "sphinx_rtd_theme" 52 | 53 | # Add any paths that contain custom static files (such as style sheets) here, 54 | # relative to this directory. They are copied after the builtin static files, 55 | # so a file named "default.css" will overwrite the builtin "default.css". 56 | html_static_path = ["_static"] 57 | -------------------------------------------------------------------------------- /docs/configuration.rst: -------------------------------------------------------------------------------- 1 | .. _configuration: 2 | 3 | Configuration 4 | ======================================================================== 5 | 6 | Errbot 7 | ------------------------------------------------------------------------ 8 | 9 | The configuration requirements for the Discord backend are quite simple. Set the ``BACKEND`` to ``Discord`` and fill in ``BOT_IDENTITY`` dictionary. 10 | :: 11 | 12 | BACKEND = "Discord" 13 | 14 | BOT_IDENTITY = { 15 | "token": "", 16 | "initial_intents": "" 17 | "intents": [] 18 | } 19 | 20 | .. csv-table:: Bot Identity fields 21 | :header: "Key", "Type", "Description" 22 | :widths: 10, 5, 20 23 | 24 | "``token``", "string", "The bot token (generated by you on the Discord application web page.)" 25 | "``initial_intents``", "string", "Initialise the intents with ``'None'`` (no intents enabled), ``'default'`` (all non-privileged intents) or ``'all'`` (all intents)" 26 | "``intents``", "list or integer", "Gateway Intents to be enabled for the bot." 27 | 28 | 29 | Gateway Intents 30 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 31 | 32 | Intents are used to inform Discord what events errbot would like to receive. If the correct permissions have been granted, the connection will be accepted and events will start to be sent to errbot. More information on intents can be seen `here `_. 33 | 34 | .. csv-table:: Intents identification 35 | :header: "Integer value", "String value" 36 | :widths: 10, 20 37 | 38 | "1", "guilds" 39 | "2", "members" 40 | "4", "bans" 41 | "8", "emojis" 42 | "16", "integrations" 43 | "32", "webhooks" 44 | "64", "invites" 45 | "128", "voice_states" 46 | "256", "presences" 47 | "512", "guild_messages" 48 | "4096", "dm_messages" 49 | "1024", "guild_reactions" 50 | "8192", "dm_reactions" 51 | "2048", "guild_typing" 52 | "16384", "dm_typing" 53 | "32768", "message_content" 54 | "65536", "guild_scheduled_events" 55 | "3145728", "auto_moderation" 56 | "1048576", "auto_moderation_configuration" 57 | "2097152", "auto_moderation_execution" 58 | 59 | Errbot configuration accepts intents as additive or subtractive values. If an intent is prefixed with ``-`` it indicates the intent should be disabled. Unprefixed intents are considered additive and will be enabled: 60 | 61 | **List form** Intents can be expressed as a list of integers, list of strings or a mixture. e.g. to enable `guilds`, `bans` and `integrations`: 62 | :: 63 | 64 | BOT_IDENTITY = { 65 | "initial_intents": "none", 66 | "intents": [1, 4, 16] 67 | } 68 | BOT_IDENTITY = { 69 | "initial_intents": "none", 70 | "intents": ["guilds", "bans", 16] 71 | } 72 | BOT_IDENTITY = { 73 | "initial_intents": "none", 74 | "intents": [21] 75 | } 76 | 77 | .. warning:: 78 | 79 | Integer form accepts values of single or multiple intents. Be careful configuring the correct values. If in doubt, only use string form to avoid confusion. 80 | 81 | **Integer form:** Intents can be expressed as a single integer which is the sum of intents to be enabled. e.g. to enable `dm_typing` (``16384``) and `dm_message` (``4096``) the sum of ``16384 + 4096 = 20480``, so the intent integer is ``20480``. 82 | :: 83 | 84 | BOT_IDENTITY = { 85 | "initial_intents": "none", 86 | "intents": 20480 87 | } 88 | 89 | The inverse can be applied by setting all intents and applying ``-20480`` 90 | :: 91 | 92 | BOT_IDENTITY = { 93 | "initial_intents": "all", 94 | "intents": -20480 95 | } 96 | 97 | 98 | Discord 99 | ------------------------------------------------------------------------ 100 | 101 | Discord API terms of use can evolve at any point in time. Fortunately, the team that provides the ``discord`` module does a great job at insulating errbot 102 | from a lot of these subtle changes. However, there are changes that are significant enough to require extra steps to get errbot to work as desired with discord. 103 | 104 | 105 | Gateway Intents 106 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 107 | 108 | Enable **Server members intent** and **Message content intent** for your bot on the Discord website. See `privileged-intents `_ page for the required steps. 109 | 110 | .. warning:: Security is not a one size fits all problem. The above intent settings are provided as help but you are ultimately responsible for understanding and applying the correct intents for your bot and environment. Also be aware that Discord intents change what data is sent to the bot that can affect functionality, check and test your settings well. 111 | 112 | Since message content has become a `privileged intent `_, unverified bots must have message content enabled from the Discord application web page. If the errbot instance is in more than 100 servers (guilds), you must apply for the bot to be verified. 113 | 114 | There have been `workarounds `_ suggested but don't fit will with errbot's operating architecture. At best, they can work in a limited capacity and at worst are not supported at all nor will support be added. If this is a problem for you, you'll need to re-evaluate your use of errbot or consider changing chat platform. 115 | 116 | 117 | Discord application 118 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 119 | 120 | To create a bot user account for use with errbot, you can see the required permission settings in the `oauth2 `_ page. 121 | 122 | Discord provides a `tool `_ that can be used to generate a proper invitation link. 123 | 124 | The reactiflux community have written a quick start guide to `creating a discord bot and getting a token `_ 125 | 126 | -------------------------------------------------------------------------------- /docs/developer_guide.rst: -------------------------------------------------------------------------------- 1 | .. _developer_guide: 2 | 3 | Developer Guide 4 | ======================================================================== 5 | 6 | Source Code 7 | ------------------------------------------------------------------------ 8 | 9 | The source code can be found on github in the `err-backend-discord repository `_ 10 | 11 | Person Class 12 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 13 | 14 | The Discord identity system doesn't map directly to that of errbots. The below table attempts to align them as best possible for practical use. 15 | 16 | 17 | .. csv-table:: Class attributes 18 | :header: "Discord ``ClientUser``", "Description", "Errbot ``Person``", "Description" 19 | :widths: 10, 20, 10, 20 20 | 21 | ``name :str:``, "The user's username.", ``person :str:``, "a backend specific unique identifier representing the person you are talking to." 22 | ``id :int:``, "The user's unique ID.", ``client :str:``, "a backend specific unique identifier representing the device or client the person is using to talk." 23 | ``discriminator :str:``, "The user's discriminator. This is given when the username has conflicts." 24 | ``bot :bool:``, "Specifies if the user is a bot account.", ``nick :str:``, "a backend specific nick returning the nickname of this person if available." 25 | ``system :bool:``, "Specifies if the user is a system user (i.e. represents Discord officially).", ``aclattr :str:``, "returns the unique identifier that will be used for ACL matches." 26 | ``??``, "??", ``fullname :str:``, "the fullname of this user if available." 27 | ``??``, "??", ``email :str:``, "the email of this user if available." 28 | 29 | 30 | Room Occupant Class 31 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 32 | 33 | .. csv-table:: Class attributes 34 | :header: "Discord ``??``", "Description", "Errbot ``RoomOccupant``", "Description" 35 | :widths: 10, 20, 10, 20 36 | 37 | ``??``, "??", ``room :any:``, "the fullname of this user if available." 38 | 39 | 40 | Room Class 41 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 42 | 43 | .. csv-table:: Class attributes 44 | :header: "Discord ``??``", "Description", "Errbot ``Room``", "Description" 45 | :widths: 10, 20, 10, 20 46 | 47 | ``??``, "??", ``join()``, "If the room does not exist yet, this will automatically call `create` on it first." 48 | ``??``, "??", ``leave()``, "Leave the room." 49 | ``??``, "??", ``create()``, "Create the room or do nothing if it already exists." 50 | ``??``, "??", ``destroy()``, "Destroy the room or do nothing if it doesn't exists." 51 | ``??``, "??", ``aclattr :str:``, "returns the unique identifier that will be used for ACL matches." 52 | ``??``, "??", ``exists :bool:``, "Returns ``True`` if the room exists, `False` otherwise." 53 | ``??``, "??", ``joined :bool:``, "Returns ``True`` if the room has been joined, `False` otherwise." 54 | ``??``, "??", ``topic :bool:``, "Returns the topic (a string) if one is set, ``None`` if no topic has been set at all." 55 | ``??``, "??", ``occupants :list:``, "Returns a list of occupant identities." 56 | ``??``, "??", ``invite()``, "Invite one or more people into the room." 57 | 58 | 59 | Identification 60 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 61 | 62 | Full identification requires to following fields: 63 | :: 64 | 65 | "guild_id": "012345678901234567" 66 | "channel_id": "123456789012345678", 67 | "author": { 68 | "username": "bumblebee", 69 | "public_flags": 0, 70 | "id": "234567890123456789", 71 | "discriminator": "0413", 72 | "bot": true, 73 | "avatar_decoration": null, 74 | "avatar": "5dba11479834e662c5e6a71807a3b9c3" 75 | }, 76 | 77 | The following examples show how errbot receives message events for identifier resolution 78 | 79 | user mention text 80 | :: 81 | 82 | frm = username#1234@playground 83 | username = username#1234@playground 84 | text = .whoami <@123456789012345678> 85 | 86 | channel mention text 87 | :: 88 | 89 | frm = username#1234@playground 90 | username = username#1234@playground 91 | text = .whoami <#123456789012345678> 92 | 93 | raw text 94 | :: 95 | 96 | frm = username#1234@channel_name 97 | username = username#1234@channel_name 98 | text = .whoami username#1234@channel_name 99 | 100 | guild mentions don't exists but could be represented with a string like ``<$123456789012345678>`` which would produce the following text identification representation to be resolved. 101 | :: 102 | 103 | #channel_name$guild_vanity_url_code 104 | #channel_name 105 | @username#1234 106 | 107 | 108 | 109 | Contributing 110 | ------------------------------------------------------------------------ 111 | 112 | The process for contributing to the discord backend follows the usual github process as described below: 113 | 114 | 1. Fork the github project to your github account. 115 | 2. Clone the forked repository to your development machine. 116 | 3. Create a branch for changes in your locally cloned repository. 117 | 4. Develop feature/fix/change in your branch. 118 | 5. Push work from your branch to your forked repository 119 | 6. Open pull request from your forked repository to the official err-backend-discord repository. 120 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | 2 | .. title:: err-backend-discord documentation 3 | 4 | Errbot Discord Backend Documentation 5 | ======================================================================== 6 | 7 | Welcome to the ``err-backend-discord`` documentation page. You'll be able to find 8 | installation instructions, configuration information and examples of using some of the backend's features. 9 | 10 | The ``err-backend-discord`` backend lets you connect to the `Discord `_ platform. `A place that makes it easy to talk every day and hang out more often.` 11 | 12 | .. toctree:: 13 | :maxdepth: 2 14 | :caption: Contents: 15 | 16 | installation.rst 17 | configuration.rst 18 | user_guide.rst 19 | developer_guide.rst 20 | 21 | Indices and tables 22 | ================== 23 | 24 | * :ref:`genindex` 25 | * :ref:`modindex` 26 | * :ref:`search` 27 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | .. _installation: 2 | 3 | Installation 4 | ======================================================================== 5 | 6 | Requirements 7 | ------------------------------------------------------------------------ 8 | 9 | * Python 3.8 or later 10 | * Discord.py 2.0.1 or later 11 | 12 | Python Virtual Environment 13 | ------------------------------------------------------------------------ 14 | 15 | The following steps describe how to install errbot and the discord backend into an isolated python virtual environment. 16 | 17 | These instructions assume you have access to discord with a bot account configured. For information on how to setup the bot account see https://discordpy.readthedocs.io/en/stable/discord.html 18 | 19 | 1. Create a virtual environment for errbot. 20 | :: 21 | 22 | python3 -m venv 23 | source /bin/activate 24 | 25 | 2. Install errbot and discord backend. 26 | :: 27 | 28 | pip install errbot err-backend-discord 29 | 30 | 3. Initialise errbot and configure discord. 31 | :: 32 | 33 | errbot --init 34 | 35 | 4. See the :ref:`configuration` section for configuration details. 36 | 37 | Changelog 38 | ======================================================================== 39 | 40 | Changes to the backend are maintained directly in the `github changelog `_ and 41 | you are encourage to review them before upgrading the backend. 42 | 43 | Upgrade notes 44 | ======================================================================== 45 | 46 | v4.0.0 47 | ------------------------------------------------------------------------ 48 | 49 | Enable Message Content intents 50 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 51 | 52 | The backend has been updated to use discord.py v2.0.1. The module has moved from v7 to v10 of the Discord API. Message content intents support has been added. 53 | You must explicitly permit the bot to have access to Message Content via the Discord bot user interface. 54 | 55 | Python 3.7 support has been dropped 56 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 57 | 58 | The v2.0 discord module has dropped support for Python 3.7 so you will be required to upgrade to at least Python 3.8 to run the discord backend. 59 | 60 | 61 | v3.0.1 62 | ------------------------------------------------------------------------ 63 | 64 | The backend code has been restructure to follow the source layout. 65 | 66 | Some of the class definitions were moved into their own files for easier maintenance. 67 | `DiscordSender` and `DiscordPerson` are now located in `discordlib/person.py` while `DiscordRoom`, `DiscordRoomOccupant` and `DiscordCategory` are in `discordlib/room.py` 68 | 69 | If your plugin imports these classes, the import code will need to be updated to use the new location. 70 | -------------------------------------------------------------------------------- /docs/user_guide.rst: -------------------------------------------------------------------------------- 1 | .. _user_guide: 2 | 3 | User Guide 4 | ======================================================================== 5 | 6 | Message destination (User, Channel and Guild) 7 | ------------------------------------------------------------------------ 8 | 9 | Communication with a specific person or group of people requires a method to express the 10 | destination for a message. Security mechanisms also require a method to express people and groups 11 | in a non ambiguous way also. 12 | 13 | Person 14 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 15 | 16 | Human to human communication is performed by a special format: ``username`` followed a ``#`` and 4 digits. 17 | This format is not used by the discord API, which uses 18+ digit identification. 18 | :: 19 | 20 | <@userid> -> Person 21 | @user#discriminator -> Person 22 | 23 | Channel 24 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 25 | 26 | Channel communication is expressed as a hash ``#`` followed by the channel name. The format is not 27 | used by the discord API, which uses an 18+ digit identificaiton. An aspect of channel communication that is 28 | not directy exposed thought the discord API, is when the bot operates in multiple servers a.k.a. guilds. It 29 | is possible that a channel name is not unique between multiple servers, e.g. ``#general`` can exist on server1 30 | and server2, but the bot must be able to target the correct channel. The format that the discord backend has 31 | opted to use is the double ``#``. 32 | 33 | :: 34 | 35 | <#channelid> -> Room 36 | #channel -> Room (a uniquely identified channel on any guild) 37 | #channel#guild_id -> Room (a channel on a specific guild) 38 | 39 | Guild 40 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 41 | 42 | Not available. Such a target will probably not be supported in the future. 43 | 44 | 45 | Troubleshooting 46 | ------------------------------------------------------------------------ 47 | 48 | privileged intents not explicitly enabled in the developer portal 49 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 50 | 51 | :: 52 | 53 | discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead. 54 | 55 | This is caused by a mismatch between the intents requested by errbot-backend-discord and the Discord application intent settings. Give the application the permissions it needs or disable them in the configuration. 56 | 57 | failed to lookup user 58 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 59 | 60 | :: 61 | 62 | ValueError: Failed to get the user <18_digit_id> 63 | 64 | This error can be caused when the bot has not been allowed access to the ``member`` privileged intent. 65 | 66 | Bot ignores all messages 67 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 68 | 69 | When running with debug logs enable, it's possible to see the message event received from Discord. The event field ``content`` is empty. 70 | 71 | :: 72 | 73 | 17:27:06 DEBUG discord.gateway For Shard ID None: WebSocket Event: { "t": "MESSAGE_CREATE", ... "content": "", ... }} 74 | 75 | This indicates the bot has not been allowed access to the ``message_content`` privileged intent. 76 | 77 | 78 | Acknowledgements 79 | ------------------------------------------------------------------------ 80 | 81 | This backend uses the `python-discord `_ module. We are most grateful to the dedicated and talented team that provide such a top class project. 82 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=61.0" 4 | ] 5 | build-backend = "setuptools.build_meta" 6 | 7 | [project] 8 | name = "err-backend-discord" 9 | version = "4.0.1" 10 | authors = [{ name="Errbot maintainers", email="noreply@errbot.io" }] 11 | keywords = [ 12 | "errbot", 13 | "discord", 14 | ] 15 | description = "Discord backend for Errbot" 16 | readme = "README.md" 17 | requires-python = ">=3.8" 18 | 19 | license = {text = "GPL-3.0"} 20 | 21 | classifiers = [ 22 | "Programming Language :: Python :: 3", 23 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 24 | "Operating System :: OS Independent", 25 | ] 26 | 27 | dependencies = [ 28 | "discord.py==2.0.1", 29 | ] 30 | 31 | [project.urls] 32 | "Homepage" = "https://err-backend-discord.readthedocs.io" 33 | "Bug Tracker" = "https://github.com/errbotio/err-backend-discord/issues" 34 | 35 | [tool.setuptools] 36 | # available as beta since setuptools version 61.0.0 37 | include-package-data = true 38 | 39 | [tool.black] 40 | line-length = 100 41 | -------------------------------------------------------------------------------- /src/err-backend-discord/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/errbotio/err-backend-discord/62e8bf00a30286aa36bad95773b558ec0bde861d/src/err-backend-discord/__init__.py -------------------------------------------------------------------------------- /src/err-backend-discord/discordlib/person.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import re 3 | import sys 4 | from abc import ABC, abstractmethod 5 | from typing import List, Optional, Union 6 | 7 | from errbot.backends.base import Person 8 | 9 | log = logging.getLogger(__name__) 10 | 11 | # Discord uses 18 or more digits for user, channel and server (guild) ids. 12 | RE_DISCORD_ID = re.compile(r"^[0-9]{18}") 13 | 14 | try: 15 | import discord 16 | except ImportError: 17 | log.exception("Could not start err-backend-discord") 18 | log.fatal("The required discord module could not be found.") 19 | sys.exit(1) 20 | 21 | 22 | class DiscordSender(ABC, discord.abc.Snowflake): 23 | """ 24 | DiscordSender's client property is used to share a single discord instance 25 | with all classes. It is populated when the backend is initialised. 26 | """ 27 | 28 | client = None 29 | 30 | @abstractmethod 31 | async def send(self, content: str = None, embed: discord.Embed = None): 32 | raise NotImplementedError 33 | 34 | @abstractmethod 35 | def get_discord_object(self) -> discord.abc.Messageable: 36 | raise NotImplementedError 37 | 38 | 39 | class DiscordPerson(Person, DiscordSender): 40 | @classmethod 41 | def resolve_username(cls, username: str, discriminator: str) -> str: 42 | for m in DiscordPerson.client.get_all_members(): 43 | if m.name == username: 44 | # Discord dropped discriminators for user accounts but kept them for bot accounts. 45 | if m.discriminator in ["0", discriminator]: 46 | return m 47 | return None 48 | 49 | def __init__(self, user_id: str = None, username: str = None, discriminator: str = "0"): 50 | """ 51 | @user_id: _must_ be a string representation of a Discord Snowflake (an integer). 52 | @username: Discord username. 53 | @discriminator: Discord discriminator to uniquely identify the username. (default to 0 since discord dropped them for username) 54 | """ 55 | if user_id: 56 | if not re.match(RE_DISCORD_ID, str(user_id)): 57 | raise ValueError(f"Invalid Discord user id {type(user_id)} {user_id}.") 58 | # cast required so that calls to discord module methods are handled correctly. 59 | self._user_id = int(user_id) 60 | else: 61 | if username and discriminator: 62 | member = DiscordPerson.resolve_username(username, discriminator) 63 | if member is None: 64 | raise LookupError( 65 | "The user {}#{} can't be found. If you're certain the username " 66 | "exists, check the spelling is correct and/or the bot has been " 67 | "granted the required intents and permissions to lookup members " 68 | "for the guild.".format( 69 | username, 70 | discriminator, 71 | ) 72 | ) 73 | self._user_id = member.id 74 | else: 75 | raise ValueError("Username/discrimator pair or user id not provided.") 76 | 77 | self.discord_user = DiscordPerson.client.get_user(self._user_id) 78 | if self.discord_user is None: 79 | raise ValueError(f"Failed to get the user {self._user_id}") 80 | 81 | def get_discord_object(self) -> discord.abc.Messageable: 82 | return self.discord_user 83 | 84 | @property 85 | def created_at(self): 86 | return discord.utils.snowflake_time(self.id) 87 | 88 | @property 89 | def person(self) -> str: 90 | return str(self) 91 | 92 | @property 93 | def email(self) -> str: 94 | return "Unavailable" 95 | 96 | @property 97 | def id(self) -> str: 98 | return self._user_id 99 | 100 | @property 101 | def username(self) -> str: 102 | """Return the user name""" 103 | return self.discord_user.name 104 | 105 | nick = username 106 | 107 | @property 108 | def client(self) -> None: 109 | return None 110 | 111 | @property 112 | def fullname(self) -> str: 113 | return f"{self.discord_user.name}#{self.discord_user.discriminator}" 114 | 115 | @property 116 | def aclattr(self) -> str: 117 | return self.fullname 118 | 119 | async def send( 120 | self, 121 | content: str = None, 122 | tts: bool = False, 123 | embed: discord.Embed = None, 124 | file: discord.File = None, 125 | files: List[discord.File] = None, 126 | delete_after: float = None, 127 | nonce: int = None, 128 | allowed_mentions: discord.AllowedMentions = None, 129 | reference: Union[discord.Message, discord.MessageReference] = None, 130 | mention_author: Optional[bool] = None, 131 | ): 132 | await self.discord_user.send( 133 | content=content, 134 | tts=tts, 135 | embed=embed, 136 | file=file, 137 | files=files, 138 | delete_after=delete_after, 139 | nonce=nonce, 140 | allowed_mentions=allowed_mentions, 141 | reference=reference, 142 | mention_author=mention_author, 143 | ) 144 | 145 | def __eq__(self, other): 146 | return isinstance(other, DiscordPerson) and other.aclattr == self.aclattr 147 | 148 | def __str__(self): 149 | return f"{self.fullname}" 150 | -------------------------------------------------------------------------------- /src/err-backend-discord/discordlib/room.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | from typing import List, Optional, Union 4 | 5 | from errbot.backends.base import Room, RoomError, RoomOccupant 6 | 7 | from discordlib.person import DiscordPerson, DiscordSender 8 | 9 | log = logging.getLogger(__name__) 10 | 11 | try: 12 | import discord 13 | except ImportError: 14 | log.exception("Could not start err-backend-discord") 15 | log.fatal("The required discord module could not be found.") 16 | sys.exit(1) 17 | 18 | 19 | class DiscordRoom(Room, DiscordSender): 20 | """ 21 | DiscordRoom objects can be in two states: 22 | 23 | 1. They exist and we have a channel_id of that room 24 | 2. They don't currently exist and we have a channel name and guild 25 | """ 26 | 27 | @classmethod 28 | def from_id(cls, channel_id): 29 | channel = DiscordRoom.client.get_channel(channel_id) 30 | 31 | if channel is None: 32 | raise ValueError(f"Channel id:{channel_id} doesn't exist!") 33 | 34 | return cls(channel.name, channel.guild.id, channel.id) 35 | 36 | def __init__(self, channel_name: str = None, guild_id: str = None, channel_id: str = None): 37 | """ 38 | Allows to specify an existing room (via name + guild or via id) or allows the 39 | creation of a future room by specifying a name and guild to create the channel in. 40 | 41 | :param channel_name: 42 | :param guild_id: 43 | :param channel_id: 44 | """ 45 | self.discord_channel = None 46 | if channel_id: 47 | self._channel_id = int(channel_id) 48 | self.discord_channel = DiscordRoom.client.get_channel(self._channel_id) 49 | elif guild_id and channel_name: 50 | guild = DiscordRoom.client.get_guild(int(guild_id)) 51 | if guild: 52 | channel = [channel for channel in guild.channels if channel_name == channel.name] 53 | if len(channel) == 0: 54 | ValueError(f"Failed to find channel {channel_name} in guild {guild.name}") 55 | if len(channel) > 1: 56 | ValueError( 57 | f"More than one channel matched {channel_name} in guild {guild.name}" 58 | ) 59 | self.discord_channel = channel[0] 60 | else: 61 | raise ValueError(f"Failed to get guild id {guild_id}") 62 | else: 63 | raise ValueError("A channel id or channel name + guild id is required for a Room.") 64 | 65 | def get_discord_object(self): 66 | return self.discord_channel 67 | 68 | def channel_name_to_id(self): 69 | """ 70 | Channel names are non-unique across Discord. Hence we require a guild name to uniquely 71 | identify a room id 72 | 73 | :return: ID of the room 74 | """ 75 | matching = [ 76 | channel 77 | for channel in DiscordRoom.client.get_all_channels() 78 | if self._channel_name == channel.name 79 | and channel.guild.id == self._guild_id 80 | and isinstance(channel, discord.TextChannel) 81 | ] 82 | 83 | if len(matching) == 0: 84 | raise ValueError(f"Failed to look up {channel} on server/guild {self._guild_id}!") 85 | 86 | if len(matching) > 1: 87 | log.warning( 88 | "Multiple matching channels for channel" 89 | f"name {self._channel_name} in guild id {self._guild_id}" 90 | ) 91 | 92 | return int(matching[0].id) 93 | 94 | @property 95 | def created_at(self): 96 | return discord.utils.snowflake_time(self.id) 97 | 98 | def invite(self, *args) -> None: 99 | if not self.exists: 100 | raise RuntimeError("Can't invite to a non-existent channel") 101 | 102 | for identifier in args: 103 | if not isinstance(identifier, DiscordPerson): 104 | raise RuntimeError("Can't invite non Discord Users") 105 | 106 | asyncio.run_coroutine_threadsafe( 107 | self.discord_channel.set_permissions(identifier.discord_user(), read_messages=True), 108 | loop=DiscordRoom.client.loop, 109 | ) 110 | 111 | @property 112 | def joined(self) -> bool: 113 | log.error("Not implemented") 114 | return True 115 | 116 | def leave(self, reason: str = None) -> None: 117 | """ 118 | Can't just leave a room 119 | :param reason: 120 | :return: 121 | """ 122 | log.error("Not implemented") 123 | 124 | async def create_room(self): 125 | guild = DiscordRoom.client.get_guild(self._guild_id) 126 | 127 | channel = await guild.create_text_channel(self._channel_name) 128 | 129 | log.info(f"Created channel {self._channel_name} in guild {guild.name}") 130 | 131 | self._channel_id = channel.id 132 | 133 | def create(self) -> None: 134 | if self.exists: 135 | log.warning(f"Tried to create {self._channel_name} which already exists.") 136 | raise RoomError("Room exists") 137 | 138 | asyncio.run_coroutine_threadsafe(self.create_room(), loop=DiscordRoom.client.loop).result( 139 | timeout=5 140 | ) 141 | 142 | def destroy(self) -> None: 143 | if not self.exists: 144 | log.warning(f"Tried to destroy {self._channel_name} which doesn't exist.") 145 | raise RoomError("Room doesn't exist") 146 | 147 | asyncio.run_coroutine_threadsafe( 148 | self.discord_channel.delete(reason="Bot deletion command"), 149 | loop=DiscordRoom.client.loop, 150 | ).result(timeout=5) 151 | 152 | def join(self, username: str = None, password: str = None) -> None: 153 | """ 154 | All public channels are already joined. Only private channels can be joined and we 155 | need an invite for that. 156 | :param username: 157 | :param password: 158 | :return: 159 | """ 160 | log.warning( 161 | "Can't join channels. Public channels are automatically joined" 162 | " and private channels are invite only." 163 | ) 164 | 165 | @property 166 | def topic(self) -> str: 167 | if not self.exists: 168 | return "" 169 | 170 | topic = self.discord_channel.topic 171 | topic = "" if topic is None else topic 172 | 173 | return topic 174 | 175 | @property 176 | def occupants(self) -> List[RoomOccupant]: 177 | if not self.exists: 178 | return [] 179 | 180 | occupants = [] 181 | for member in self.discord_channel.members: 182 | occupants.append(DiscordRoomOccupant(member.id, self._channel_id)) 183 | 184 | return occupants 185 | 186 | @property 187 | def exists(self) -> bool: 188 | return None not in [ 189 | self._channel_id, 190 | DiscordRoom.client.get_channel(self._channel_id), 191 | ] 192 | 193 | @property 194 | def guild(self): 195 | """ 196 | Gets the guild_id this channel belongs to. None if it doesn't exist 197 | :return: Guild id or None 198 | """ 199 | return self._guild_id 200 | 201 | @property 202 | def name(self) -> str: 203 | """ 204 | Gets the channels' name 205 | 206 | :return: channels' name 207 | """ 208 | if self._channel_id is None: 209 | return self._channel_name 210 | else: 211 | self._channel_name = DiscordRoom.client.get_channel(self._channel_id).name 212 | return self._channel_name 213 | 214 | @property 215 | def id(self): 216 | """ 217 | Can return none if not created 218 | :return: Channel ID or None 219 | """ 220 | return self._channel_id 221 | 222 | async def send(self, content: str = None, embed: discord.Embed = None): 223 | if not self.exists: 224 | raise RuntimeError("Can't send a message on a non-existent channel") 225 | if not isinstance(self.discord_channel, discord.abc.Messageable): 226 | raise RuntimeError( 227 | f"Channel {self.name}[id:{self._channel_id}] doesn't support sending text messages" 228 | ) 229 | 230 | await self.discord_channel.send(content=content, embed=embed) 231 | 232 | def __str__(self): 233 | return f"<#{self.id}>" 234 | 235 | def __eq__(self, other: "DiscordRoom"): 236 | if not isinstance(other, DiscordRoom): 237 | return False 238 | 239 | return None not in [other.id, self.id] and other.id == self.id 240 | 241 | 242 | class DiscordRoomOccupant(DiscordPerson, RoomOccupant): 243 | def __init__(self, user_id: str, channel_id: str): 244 | super().__init__(user_id) 245 | 246 | self._channel = DiscordRoom.from_id(channel_id) 247 | 248 | @property 249 | def room(self) -> DiscordRoom: 250 | return self._channel 251 | 252 | async def send(self, content: str = None, embed: discord.Embed = None): 253 | await self.room.send(content=content, embed=embed) 254 | 255 | def __eq__(self, other): 256 | return ( 257 | isinstance(other, DiscordRoomOccupant) 258 | and other.id == self.id 259 | and other.room.id == self.room.id 260 | ) 261 | 262 | def __str__(self): 263 | return f"{super().__str__()}@{self._channel.name}" 264 | 265 | 266 | class DiscordCategory(DiscordRoom): 267 | def channel_name_to_id(self): 268 | """ 269 | Channel names are non-unique across Discord. Hence we require a guild name to 270 | uniquely identify a room id. 271 | 272 | :return: ID of the room 273 | """ 274 | matching = [ 275 | channel 276 | for channel in DiscordCategory.client.get_all_channels() 277 | if self._channel_name == channel.name 278 | and channel.guild.id == self._guild_id 279 | and isinstance(channel, discord.CategoryChannel) 280 | ] 281 | 282 | if len(matching) == 0: 283 | return None 284 | 285 | if len(matching) > 1: 286 | log.warning( 287 | "Multiple matching channels for channel name" 288 | f" {self._channel_name} in guild id {self._guild_id}" 289 | ) 290 | 291 | return matching[0].id 292 | 293 | def create_subchannel(self, name: str) -> DiscordRoom: 294 | category = self.get_discord_object() 295 | 296 | if not isinstance(category, discord.CategoryChannel): 297 | raise RuntimeError("Category is not a discord category object") 298 | 299 | text_channel = asyncio.run_coroutine_threadsafe( 300 | category.create_text_channel(name), loop=DiscordCategory.client.loop 301 | ).result(timeout=5) 302 | 303 | return DiscordRoom.from_id(text_channel.id) 304 | 305 | async def create_room(self): 306 | guild = DiscordCategory.client.get_guild(self._guild_id) 307 | 308 | channel = await guild.create_category(self._channel_name) 309 | 310 | log.info(f"Created category {self._channel_name} in guild {guild.name}") 311 | 312 | self._channel_id = channel.id 313 | 314 | def join(self, username: str = None, password: str = None) -> None: 315 | raise RuntimeError("Can't join categories") 316 | 317 | def leave(self, reason: str = None) -> None: 318 | raise RuntimeError("Can't leave categories") 319 | 320 | @property 321 | def joined(self) -> bool: 322 | raise RuntimeError("Can't join categories") 323 | 324 | @property 325 | def topic(self) -> str: 326 | raise RuntimeError("Can't set category topic") 327 | 328 | @property 329 | def occupants(self) -> List[RoomOccupant]: 330 | raise NotImplementedError("Not implemented yet") 331 | 332 | def invite(self, *args) -> None: 333 | raise RuntimeError("Can't invite to categories") 334 | -------------------------------------------------------------------------------- /src/err-backend-discord/err-backend-discord.plug: -------------------------------------------------------------------------------- 1 | [Core] 2 | Name = Discord 3 | Module = err-backend-discord 4 | 5 | [Documentation] 6 | Description = Discord backend for Errbot. 7 | -------------------------------------------------------------------------------- /src/err-backend-discord/err-backend-discord.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | import sys 4 | 5 | from errbot.backends.base import AWAY, DND, OFFLINE, ONLINE, Message, Person, Presence 6 | from errbot.core import ErrBot 7 | 8 | from discordlib.person import DiscordPerson, DiscordSender 9 | from discordlib.room import DiscordCategory, DiscordRoom, DiscordRoomOccupant 10 | 11 | log = logging.getLogger("errbot-backend-discord") 12 | 13 | try: 14 | import discord 15 | except ImportError: 16 | log.exception("Could not start err-backend-discord") 17 | log.fatal("The required discord module could not be found.") 18 | sys.exit(1) 19 | 20 | COLOURS = { 21 | "red": 0xFF0000, 22 | "green": 0x008000, 23 | "yellow": 0xFFA500, 24 | "blue": 0x0000FF, 25 | "white": 0xFFFFFF, 26 | "cyan": 0x00FFFF, 27 | } 28 | 29 | 30 | class DiscordBackend(ErrBot): 31 | """ 32 | Discord backend for Errbot. 33 | """ 34 | 35 | client = None 36 | 37 | def __init__(self, config): 38 | super().__init__(config) 39 | 40 | self.token = config.BOT_IDENTITY.get("token", None) 41 | self.initial_intents = config.BOT_IDENTITY.get("initial_intents", "default") 42 | self.intents = config.BOT_IDENTITY.get("intents", None) 43 | 44 | if not self.token: 45 | log.fatal( 46 | "You need to set a token entry in the BOT_IDENTITY" 47 | " setting of your configuration." 48 | ) 49 | sys.exit(1) 50 | 51 | self.bot_identifier = None 52 | 53 | def set_message_size_limit(self, limit=2000, hard_limit=2000): 54 | """ 55 | Discord supports up to 2000 characters per message. 56 | """ 57 | super().set_message_size_limit(limit, hard_limit) 58 | 59 | async def on_error(self, event, *args, **kwargs): 60 | super().on_error(event, *args, **kwargs) 61 | # A stub entry in case special error handling is required. 62 | pass 63 | 64 | async def on_ready(self): 65 | """ 66 | Discord client ready event handler 67 | """ 68 | # Call connect only after successfully connected and ready to service Discord events. 69 | self.connect_callback() 70 | 71 | log.debug( 72 | f"Logged in as {DiscordBackend.client.user.name}, {DiscordBackend.client.user.id}" 73 | ) 74 | if self.bot_identifier is None: 75 | self.bot_identifier = DiscordPerson(DiscordBackend.client.user.id) 76 | 77 | for channel in DiscordBackend.client.get_all_channels(): 78 | log.debug(f"Found channel: {channel}") 79 | 80 | async def on_message_edit(self, before, after): 81 | """ 82 | Edit message event handler 83 | """ 84 | log.warning("Message editing not supported.") 85 | 86 | async def on_message(self, msg: discord.Message): 87 | """ 88 | Message event handler 89 | """ 90 | err_msg = Message(msg.content, extras=msg.embeds) 91 | 92 | # if the message coming in is from a webhook, it will not have a username 93 | # this will cause the whole process to fail. In those cases, return without 94 | # processing. 95 | 96 | if msg.author.bot: 97 | return 98 | 99 | if isinstance(msg.channel, discord.abc.PrivateChannel): 100 | err_msg.frm = DiscordPerson(msg.author.id) 101 | err_msg.to = self.bot_identifier 102 | else: 103 | err_msg.to = DiscordRoom.from_id(msg.channel.id) 104 | err_msg.frm = DiscordRoomOccupant(msg.author.id, msg.channel.id) 105 | 106 | if self.process_message(err_msg): 107 | # Message contains a command 108 | recipient = err_msg.frm 109 | 110 | if not isinstance(recipient, DiscordSender): 111 | raise ValueError("Message object from is not a DiscordSender") 112 | 113 | async with recipient.get_discord_object().typing(): 114 | self._dispatch_to_plugins("callback_message", err_msg) 115 | 116 | if msg.mentions: 117 | self.callback_mention( 118 | err_msg, 119 | [DiscordRoomOccupant(mention.id, msg.channel.id) for mention in msg.mentions], 120 | ) 121 | 122 | def is_from_self(self, msg: Message) -> bool: 123 | """ 124 | Test if message is from the bot instance. 125 | """ 126 | if not isinstance(msg.frm, DiscordPerson): 127 | return False 128 | 129 | return msg.frm.id == self.bot_identifier.id 130 | 131 | async def on_member_update(self, before, after): 132 | """ 133 | Member update event handler 134 | """ 135 | if before.status != after.status: 136 | person = DiscordPerson(after.id) 137 | 138 | log.debug(f"Person {person} changed status to {after.status} from {before.status}") 139 | if after.status == discord.Status.online: 140 | self.callback_presence(Presence(person, ONLINE)) 141 | elif after.status == discord.Status.offline: 142 | self.callback_presence(Presence(person, OFFLINE)) 143 | elif after.status == discord.Status.idle: 144 | self.callback_presence(Presence(person, AWAY)) 145 | elif after.status == discord.Status.dnd: 146 | self.callback_presence(Presence(person, DND)) 147 | else: 148 | log.debug("Unrecognised member update, ignoring...") 149 | 150 | def query_room(self, room): 151 | """ 152 | Query room. 153 | 154 | This method implicitly assume the bot is in one guild server. 155 | 156 | ##category -> a category 157 | #room -> Creates a room 158 | 159 | :param room: 160 | :return: 161 | """ 162 | if len(DiscordBackend.client.guilds) == 0: 163 | log.error(f"Unable to join room '{room}' because no guilds were found!") 164 | return None 165 | 166 | guild = DiscordBackend.client.guilds[0] 167 | 168 | room_name = room 169 | if room_name.startswith("##"): 170 | return DiscordCategory(room_name[2:], guild.id) 171 | elif room_name.startswith("#"): 172 | return DiscordRoom(room_name[1:], guild.id) 173 | else: 174 | return DiscordRoom(room_name, guild.id) 175 | 176 | def send_message(self, msg: Message): 177 | super().send_message(msg) 178 | 179 | if not isinstance(msg.to, DiscordSender): 180 | raise RuntimeError( 181 | f"{msg.to} doesn't support sending messages." 182 | f" Expected DiscordSender object but got {type(msg.to)}." 183 | ) 184 | 185 | log.debug( 186 | f"Message to:{msg.to}({type(msg.to)}) from:{msg.frm}({type(msg.frm)})," 187 | f" is_direct:{msg.is_direct} extras: {msg.extras} size: {len(msg.body)}" 188 | ) 189 | 190 | for message in [ 191 | msg.body[i : i + self.message_size_limit] 192 | for i in range(0, len(msg.body), self.message_size_limit) 193 | ]: 194 | asyncio.run_coroutine_threadsafe( 195 | msg.to.send(content=message), loop=DiscordBackend.client.loop 196 | ) 197 | 198 | def send_card(self, card): 199 | recipient = card.to 200 | 201 | if not isinstance(recipient, DiscordSender): 202 | raise RuntimeError( 203 | f"{recipient} doesn't support sending messages." 204 | f" Expected {DiscordSender} but got {type(recipient)}" 205 | ) 206 | 207 | if card.color: 208 | color = COLOURS.get(card.color, int(card.color.replace("#", "0x"), 16)) 209 | else: 210 | color = None 211 | 212 | # Create Embed object 213 | em = discord.Embed(title=card.title, description=card.body, color=color) 214 | 215 | if card.image: 216 | em.set_image(url=card.image) 217 | 218 | if card.thumbnail: 219 | em.set_thumbnail(url=card.thumbnail) 220 | 221 | if card.fields: 222 | for key, value in card.fields: 223 | em.add_field(name=key, value=value, inline=True) 224 | 225 | asyncio.run_coroutine_threadsafe( 226 | recipient.send(embed=em), loop=DiscordBackend.client.loop 227 | ).result(5) 228 | 229 | def build_reply(self, mess, text=None, private=False, threaded=False): 230 | response = self.build_message(text) 231 | 232 | if mess.is_direct: 233 | response.frm = self.bot_identifier 234 | response.to = mess.frm 235 | else: 236 | if not isinstance(mess.frm, DiscordRoomOccupant): 237 | raise RuntimeError("Non-Direct messages must come from a room occupant") 238 | 239 | response.frm = DiscordRoomOccupant(self.bot_identifier.id, mess.frm.room.id) 240 | response.to = DiscordPerson(mess.frm.id) if private else mess.to 241 | return response 242 | 243 | def config_intents(self): 244 | """ 245 | Process discord intents configuration for bot. 246 | """ 247 | 248 | def apply_as_int(bot_intents, intent): 249 | if intent >= 0: 250 | bot_intents._set_flag(intent, True) 251 | else: 252 | intent *= -1 253 | bot_intents._set_flag(intent, False) 254 | return bot_intents 255 | 256 | def apply_as_str(bot_intents, intent): 257 | toggle = True 258 | if intent.startswith("-"): 259 | toggle = False 260 | intent = intent[1:] 261 | 262 | if hasattr(bot_intents, intent): 263 | setattr(bot_intents, intent, toggle) 264 | else: 265 | log.warning("Unknown intent '%s'.", intent) 266 | return bot_intents 267 | 268 | bot_intents = { 269 | "none": discord.Intents.none, 270 | "default": discord.Intents.default, 271 | "all": discord.Intents.all, 272 | }.get(self.initial_intents, discord.Intents.default)() 273 | 274 | if isinstance(self.intents, list): 275 | for intent in self.intents: 276 | if isinstance(intent, int): 277 | bot_intents = apply_as_int(bot_intents, intent) 278 | elif isinstance(intent, str): 279 | bot_intents = apply_as_str(bot_intents, intent) 280 | else: 281 | log.warning("Unknown intent type %s for '%s'", type(intent), str(intent)) 282 | elif isinstance(self.intents, int): 283 | bot_intents = apply_as_int(bot_intents, self.intents) 284 | else: 285 | if self.intents is not None: 286 | log.warning( 287 | "Unsupported intent type %s for '%s'", 288 | type(self.intents), 289 | str(self.intents), 290 | ) 291 | 292 | log.info( 293 | "Enabled intents - {}".format(", ".join([i[0] for i in list(bot_intents) if i[1]])) 294 | ) 295 | log.info( 296 | "Disabled intents - {}".format( 297 | ", ".join([i[0] for i in list(bot_intents) if i[1] is False]) 298 | ) 299 | ) 300 | return bot_intents 301 | 302 | def initialise_client(self): 303 | """ 304 | Initialise discord client. This function is called whenever the serve_once 305 | is restarted. This involves initialising the intents, callback handlers 306 | and dependency injection for classes that use the discord client. 307 | """ 308 | 309 | bot_intents = self.config_intents() 310 | DiscordBackend.client = discord.Client(intents=bot_intents) 311 | 312 | # Register discord event coroutines. 313 | for func in [ 314 | self.on_ready, 315 | self.on_message, 316 | self.on_member_update, 317 | self.on_message_edit, 318 | self.on_member_update, 319 | ]: 320 | DiscordBackend.client.event(func) 321 | 322 | # Use dependency injection to make discord client available to submodule classes. 323 | DiscordCategory.client = DiscordBackend.client 324 | DiscordRoomOccupant.client = DiscordBackend.client 325 | DiscordRoom.client = DiscordBackend.client 326 | DiscordPerson.client = DiscordBackend.client 327 | DiscordSender.client = DiscordBackend.client 328 | 329 | def serve_once(self): 330 | """ 331 | Initialise discord client and establish connection. 332 | """ 333 | 334 | async def start_client(token): 335 | """ 336 | Start the discord client using asynchronous event loop. 337 | """ 338 | async with DiscordBackend.client: 339 | await DiscordBackend.client.start(token) 340 | 341 | try: 342 | self.initialise_client() 343 | 344 | # Discord.py 2.0's client.run convenience method traps KeyboardInterrupt so it can not be used. 345 | # The documented manual method is used here so errbot can handle KeyboardInterrupt exceptions. 346 | asyncio.run(start_client(self.token)) 347 | 348 | except KeyboardInterrupt: 349 | self.disconnect_callback() 350 | return True 351 | 352 | def change_presence(self, status: str = ONLINE, message: str = ""): 353 | log.debug(f'Presence changed to {status} and activity "{message}".') 354 | activity = discord.Activity(name=message) 355 | DiscordBackend.client.change_presence(status=status, activity=activity) 356 | 357 | def prefix_groupchat_reply(self, message, identifier: Person): 358 | message.body = f"@{identifier.nick} {message.body}" 359 | 360 | def rooms(self): 361 | return [ 362 | DiscordRoom.from_id(channel.id) for channel in DiscordBackend.client.get_all_channels() 363 | ] 364 | 365 | @property 366 | def mode(self): 367 | return "discord" 368 | 369 | def build_identifier(self, text: str): 370 | """ 371 | Guilds in Discord represent an isolated collection of users and channels, 372 | and are often referred to as "servers" in the UI. 373 | 374 | Valid forms of strreps: 375 | <@userid> -> Person 376 | <#channelid> -> Room 377 | @user#discriminator -> Person 378 | #channel -> Room (a uniquely identified channel on any guild) 379 | #channel#guild_id -> Room (a channel on a specific guild) 380 | 381 | :param text: The text the represents an Identifier 382 | :return: Identifier 383 | 384 | Room Example: 385 | #general@12345678901234567 -> Sends a message to the 386 | #general channel of the guild with id 12345678901234567 387 | """ 388 | if not text: 389 | raise ValueError("A string must be provided to build an identifier.") 390 | 391 | log.debug(f"Build_identifier {text}") 392 | 393 | # Mentions are wrapped by <> 394 | if text.startswith("<") and text.endswith(">"): 395 | text = text[1:-1] 396 | if text.startswith("@"): 397 | return DiscordPerson(user_id=text[1:]) 398 | elif text.startswith("#"): 399 | # channel id 400 | return DiscordRoom(channel_id=text[1:]) 401 | else: 402 | raise ValueError(f"Unsupport identification {text}") 403 | # Raw text channel name start with # 404 | elif text.startswith("#"): 405 | if "@" in text: 406 | channel_name, guild_id = text.split("@", 1) 407 | return DiscordRoom(channel_name[1:], guild_id) 408 | else: 409 | return DiscordRoom(text[1:]) 410 | # Raw text username starts with @ 411 | elif text.startswith("@"): 412 | text = text[1:] 413 | if "#" in text: 414 | user, discriminator = text.split("#",1) 415 | return DiscordPerson(username=user, discriminator=discriminator) 416 | 417 | raise ValueError(f"Invalid representation {text}") 418 | 419 | def upload_file(self, msg, filename): 420 | with open(filename, "r") as f: 421 | dest = None 422 | if msg.is_direct: 423 | dest = DiscordPerson(msg.frm.id).get_discord_object() 424 | else: 425 | dest = msg.to.get_discord_object() 426 | 427 | log.info(f"Sending file {filename} to user {msg.frm}") 428 | asyncio.run_coroutine_threadsafe( 429 | dest.send(file=discord.File(f, filename=filename)), 430 | loop=self.client.loop, 431 | ) 432 | 433 | def history(self, channelname, before=None): 434 | mychannel = discord.utils.get(self.client.get_all_channels(), name=channelname) 435 | 436 | async def gethist(mychannel, before=None): 437 | return [i async for i in self.client.logs_from(mychannel, limit=10, before=before)] 438 | 439 | future = asyncio.run_coroutine_threadsafe(gethist(mychannel, before), loop=self.client.loop) 440 | return future.result(timeout=None) 441 | -------------------------------------------------------------------------------- /test-requirements.txt: -------------------------------------------------------------------------------- 1 | errbot 2 | mock 3 | pytest 4 | tox 5 | -------------------------------------------------------------------------------- /tests/config-ci.py: -------------------------------------------------------------------------------- 1 | # config for continus integration testing. 2 | # Don't use this for sensible defaults 3 | import logging 4 | 5 | BOT_DATA_DIR = "/tmp" 6 | BOT_EXTRA_PLUGIN_DIR = None 7 | BOT_EXTRA_BACKEND_DIR = f"{BOT_DATA_DIR}/backends/" 8 | AUTOINSTALL_DEPS = True 9 | BOT_LOG_FILE = "/tmp/err.log" 10 | BOT_LOG_LEVEL = logging.DEBUG 11 | BOT_LOG_SENTRY = False 12 | SENTRY_DSN = "" 13 | SENTRY_LOGLEVEL = BOT_LOG_LEVEL 14 | BOT_ASYNC = True 15 | BOT_IDENTITY = { 16 | "username": "err@localhost", 17 | "password": "changeme", 18 | } 19 | 20 | BOT_ADMINS = ("gbin@localhost",) 21 | CHATROOM_PRESENCE = () 22 | CHATROOM_FN = "Err" 23 | BOT_PREFIX = "!" 24 | DIVERT_TO_PRIVATE = () 25 | CHATROOM_RELAY = {} 26 | REVERSE_CHATROOM_RELAY = {} 27 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | source_path = "../src/err-backend-discord" 5 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), source_path))) 6 | -------------------------------------------------------------------------------- /tests/test_backend.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import os 4 | import pdb 5 | import sys 6 | from tempfile import mkdtemp 7 | 8 | 9 | import importlib # Use importlib because of "-" in module name. 10 | import pytest 11 | 12 | from discordlib.room import DiscordRoom 13 | 14 | from errbot.backends.base import Message 15 | from errbot.bootstrap import bot_config_defaults 16 | 17 | from mock import MagicMock 18 | 19 | log = logging.getLogger(__name__) 20 | 21 | try: 22 | DiscordBackend = importlib.import_module("err-backend-discord").DiscordBackend 23 | 24 | class MockedDiscordBackend(DiscordBackend): 25 | def __init__(self, *args, **kwargs): 26 | super().__init__(*args, **kwargs) 27 | self.test_msgs = [] 28 | self.bot_identifier = MagicMock() 29 | 30 | except SystemExit: 31 | log.exception("Can't import discord backend for testing") 32 | 33 | 34 | @pytest.fixture 35 | def backend(): 36 | # make up a config. 37 | tempdir = mkdtemp() 38 | # reset the config every time 39 | sys.modules.pop("errbot.config-template", None) 40 | __import__("errbot.config-template") 41 | config = sys.modules["errbot.config-template"] 42 | bot_config_defaults(config) 43 | config.BOT_DATA_DIR = tempdir 44 | config.BOT_LOG_FILE = os.path.join(tempdir, "log.txt") 45 | config.BOT_EXTRA_PLUGIN_DIR = [] 46 | config.BOT_LOG_LEVEL = logging.DEBUG 47 | config.BOT_IDENTITY = BOT_IDENTITY = { 48 | "token": "token_abcd", 49 | "initial_intents": "default", 50 | "intents": [], 51 | } 52 | config.BOT_ASYNC = False 53 | config.BOT_PREFIX = "!" 54 | config.CHATROOM_FN = "test_room" 55 | 56 | discord_backend = MockedDiscordBackend(config) 57 | return discord_backend 58 | 59 | 60 | def todo_build_identifier(backend): 61 | raise NotImplementedError 62 | 63 | 64 | def todo_extract_identifiers(backend): 65 | raise NotImplementedError 66 | 67 | 68 | def todo_send_message(backend): 69 | raise NotImplementedError 70 | -------------------------------------------------------------------------------- /tests/test_person.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import os 4 | import sys 5 | 6 | from errbot.backends.base import RoomDoesNotExistError 7 | 8 | import pytest 9 | from mock import MagicMock 10 | 11 | from discordlib.person import DiscordPerson 12 | 13 | log = logging.getLogger(__name__) 14 | 15 | 16 | @pytest.fixture 17 | def person(): 18 | return MagicMock() 19 | 20 | 21 | def test_wrong_userid(): 22 | raise NotImplementedError 23 | 24 | 25 | def test_create_person_without_args(): 26 | DiscordPerson(user_id="0123456789012345678") 27 | 28 | 29 | def test_create_person_with_username_only(): 30 | DiscordPerson(username="someone") 31 | 32 | 33 | def test_create_person_with_discriminator_only(): 34 | DiscordPerson(discriminator="#1234") 35 | 36 | 37 | def test_create_person_with_id(): 38 | DiscordPerson(user_id="0123456789012345678") 39 | 40 | 41 | def test_create_person_username_and_discriminator(): 42 | DiscordPerson(username="someone", discriminator="1234") 43 | 44 | 45 | def todo_wrong_channelid(): 46 | raise NotImplementedError 47 | 48 | 49 | def todo_username(): 50 | raise NotImplementedError 51 | 52 | 53 | def todo_username_not_found(): 54 | raise NotImplementedError 55 | 56 | 57 | def todo_fullname(): 58 | raise NotImplementedError 59 | 60 | 61 | def todo_fullname_not_found(): 62 | raise NotImplementedError 63 | 64 | 65 | def todo_email(): 66 | raise NotImplementedError 67 | 68 | 69 | def todo_email_not_found(): 70 | raise NotImplementedError 71 | 72 | 73 | def todo_channelname(): 74 | raise NotImplementedError 75 | 76 | 77 | def todo_channelname_channel_not_found(): 78 | raise NotImplementedError 79 | 80 | 81 | def todo_domain(): 82 | raise NotImplementedError 83 | 84 | 85 | def todo_aclattr(): 86 | raise NotImplementedError 87 | 88 | 89 | def todo_person(): 90 | raise NotImplementedError 91 | 92 | 93 | def todo_to_string(): 94 | raise NotImplementedError 95 | 96 | 97 | def todo_equal(): 98 | raise NotImplementedError 99 | 100 | 101 | def todo_hash(): 102 | raise NotImplementedError 103 | -------------------------------------------------------------------------------- /tests/test_room.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import pytest 4 | from mock import MagicMock 5 | 6 | from discordlib.room import DiscordRoom 7 | 8 | log = logging.getLogger(__name__) 9 | 10 | 11 | @pytest.fixture 12 | def discord_room(): 13 | room = DiscordRoom 14 | setattr(room, "client", MagicMock()) 15 | return room 16 | 17 | 18 | def test_create_room_without_arguments(): 19 | with pytest.raises(ValueError) as excinfo: 20 | DiscordRoom() 21 | assert "A name or channel id + guild id is required to create a Room." in str(excinfo.value) 22 | 23 | 24 | def test_create_room_with_name_only(): 25 | with pytest.raises(ValueError) as excinfo: 26 | DiscordRoom(channel_name="#testing_ground") 27 | assert "A name or channel id + guild id is required to create a Room." in str(excinfo.value) 28 | 29 | 30 | def test_create_room_with_guild_only(): 31 | with pytest.raises(ValueError) as excinfo: 32 | DiscordRoom(guild_id="1234567890123456789") 33 | assert "A name or channel id + guild id is required to create a Room." in str(excinfo.value) 34 | 35 | 36 | def test_create_room_with_id(discord_room): 37 | room = discord_room(channel_id="1234567890132456789") 38 | assert room.id == 1234567890132456789 39 | 40 | 41 | def test_create_room_with_name_and_guild_id(discord_room): 42 | room = discord_room(channel_name="#testing_ground", guild_id="2345678901234567890") 43 | assert room.id == 1234567890132456789 44 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py38,py39,py310,py311,codestyle,dist-check,sort,security 3 | skip_missing_interpreters = True 4 | isolated_build = True 5 | 6 | [testenv] 7 | deps = -r {toxinidir}/test-requirements.txt 8 | 9 | commands = pytest -v tests/ 10 | recreate = true 11 | 12 | [testenv:codestyle] 13 | deps = 14 | black 15 | commands = 16 | black --check src/ tests/ 17 | 18 | [testenv:dist-check] 19 | deps = 20 | twine 21 | build 22 | commands = 23 | python -m build --outdir {toxworkdir} 24 | twine check {toxworkdir}/* 25 | 26 | [testenv:sort] 27 | deps = 28 | isort 29 | commands = isort --check-only --profile=black src/ tests/ 30 | 31 | [testenv:security] 32 | deps = 33 | bandit 34 | 35 | ; ignoring errors 36 | commands = 37 | - bandit -r src/err-backend-discord/ 38 | --------------------------------------------------------------------------------