Initial commit: APIcord Discord API Emulator
- Core infrastructure: config, state management, models - REST API server (aiohttp) with Discord-compatible endpoints - WebSocket Gateway server (websockets) with Discord Gateway protocol - State management with guilds, channels, users, messages, interactions - Pydantic models for Discord objects (User, Guild, Channel, Message, etc.) - CLI with start, test, reset, export, validate commands - YAML-based test scenario framework - Basic test scenario for /server_status command flow - Unit tests for models and state manager (19 passing) - GPL-3.0 license
This commit is contained in:
commit
5669048f89
38 files changed
+2871
No files matched your search
+43
@@ -0,0 +1,43 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# Virtual environments
|
||||
venv/
|
||||
.env
|
||||
.venv
|
||||
|
||||
# Distribution / packaging
|
||||
dist/
|
||||
build/
|
||||
*.egg-info/
|
||||
src/*.egg-info/
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
logs/
|
||||
|
||||
# State files
|
||||
apicord_state.json
|
||||
|
||||
# Testing
|
||||
.coverage
|
||||
htmlcov/
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
|
||||
# Environment
|
||||
.env
|
||||
.env.local
|
||||
@@ -0,0 +1,232 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
“This License” refers to version 3 of the GNU General Public License.
|
||||
|
||||
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||
|
||||
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
|
||||
|
||||
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
|
||||
|
||||
A “covered work” means either the unmodified Program or a work based on the Program.
|
||||
|
||||
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||
|
||||
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
|
||||
|
||||
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||
|
||||
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
|
||||
|
||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||
|
||||
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||
|
||||
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||
|
||||
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
|
||||
|
||||
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||
|
||||
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
|
||||
|
||||
pterodactyl-discord-bot
|
||||
Copyright (C) 2025 k.eaven
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
||||
|
||||
pterodactyl-discord-bot Copyright (C) 2025 k.eaven
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,55 @@
|
||||
# APIcord
|
||||
|
||||
Discord API Emulator for bot testing.
|
||||
|
||||
A standalone Python CLI program that emulates the Discord API (REST + WebSocket Gateway), enabling self-contained testing of Discord bots without requiring a real Discord connection.
|
||||
|
||||
## Features
|
||||
|
||||
- **REST API Server** - Implements Discord REST API endpoints needed for bot operations
|
||||
- **WebSocket Gateway** - Emulates Discord's Gateway for real-time events (READY, INTERACTION_CREATE, etc.)
|
||||
- **State Management** - In-memory state with guilds, channels, users, messages, and interactions
|
||||
- **Test Scenarios** - YAML-based test scenarios for automated bot testing
|
||||
- **CLI Interface** - Easy-to-use commands for starting, testing, and managing the emulator
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip install -e .
|
||||
# Or for development
|
||||
pip install -e ".[dev]"
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Start emulator with a test scenario
|
||||
apicord start --scenario scenarios/basic_test.yaml
|
||||
|
||||
# Run automated test against a bot
|
||||
apicord test --scenario scenarios/full_test.yaml --bot-path /path/to/bot
|
||||
|
||||
# Start with custom configuration
|
||||
apicord start --port 8080 --guilds 2 --channels 5
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
apicord/
|
||||
├── src/apicord/
|
||||
│ ├── main.py # CLI entry point
|
||||
│ ├── config.py # Configuration management
|
||||
│ ├── rest/ # REST API server (aiohttp)
|
||||
│ ├── gateways/ # WebSocket gateway (websockets)
|
||||
│ ├── state/ # State management
|
||||
│ ├── models/ # Pydantic models for Discord objects
|
||||
│ └── cli/ # CLI commands
|
||||
├── tests/ # Unit tests
|
||||
├── scenarios/ # YAML test scenarios
|
||||
└── pyproject.toml
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
GPL-3.0 - See LICENSE file for details.
|
||||
@@ -0,0 +1,65 @@
|
||||
[project]
|
||||
name = "apicord"
|
||||
version = "0.1.0"
|
||||
description = "Discord API Emulator for bot testing"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
license = {text = "GPL-3.0"}
|
||||
authors = [
|
||||
{name = "Eaven Kimura", email = "kimura.eaven@gmail.com"}
|
||||
]
|
||||
classifiers = [
|
||||
"Development Status :: 3 - Alpha",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
]
|
||||
dependencies = [
|
||||
"aiohttp>=3.9.0",
|
||||
"websockets>=12.0",
|
||||
"pyyaml>=6.0",
|
||||
"click>=8.1.0",
|
||||
"pydantic>=2.5.0",
|
||||
"pydantic-settings>=2.1.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest>=7.4.0",
|
||||
"pytest-asyncio>=0.21.0",
|
||||
"pytest-cov>=4.1.0",
|
||||
"black>=23.0.0",
|
||||
"ruff>=0.1.0",
|
||||
"mypy>=1.5.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
apicord = "apicord.main:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools>=68.0", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
testpaths = ["tests"]
|
||||
python_files = ["test_*.py"]
|
||||
python_classes = ["Test*"]
|
||||
python_functions = ["test_*"]
|
||||
|
||||
[tool.black]
|
||||
line-length = 100
|
||||
target-version = ['py310']
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py310"
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.10"
|
||||
warn_return_any = true
|
||||
warn_unused_configs = true
|
||||
disallow_untyped_defs = true
|
||||
@@ -0,0 +1,82 @@
|
||||
# Basic Test Scenario
|
||||
# Tests the /server_status command flow: dropdown -> button click
|
||||
|
||||
name: "Basic Server Status Test"
|
||||
description: "Test /server_status command and button interactions"
|
||||
|
||||
# Guild setup
|
||||
guilds:
|
||||
- id: "123456789012345678"
|
||||
name: "Test Guild"
|
||||
owner_id: "111111111111111111"
|
||||
channels:
|
||||
- "111111111111111111"
|
||||
roles:
|
||||
- "222222222222222222"
|
||||
|
||||
# Channels
|
||||
channels:
|
||||
- id: "111111111111111111"
|
||||
guild_id: "123456789012345678"
|
||||
name: "general"
|
||||
type: 0 # GUILD_TEXT
|
||||
position: 0
|
||||
|
||||
# Roles
|
||||
roles:
|
||||
- id: "222222222222222222"
|
||||
guild_id: "123456789012345678"
|
||||
name: "Game Server User"
|
||||
color: 3447003
|
||||
hoist: true
|
||||
position: 1
|
||||
permissions: "104324161"
|
||||
managed: false
|
||||
mentionable: true
|
||||
|
||||
# Users
|
||||
users:
|
||||
- id: "333333333333333333"
|
||||
username: "TestUser"
|
||||
discriminator: "1234"
|
||||
bot: false
|
||||
guild_roles:
|
||||
"123456789012345678":
|
||||
- "222222222222222222"
|
||||
|
||||
# Bot
|
||||
bot:
|
||||
id: "444444444444444444"
|
||||
username: "TestBot"
|
||||
discriminator: "0000"
|
||||
token: "test_token_123"
|
||||
|
||||
# Test steps
|
||||
steps:
|
||||
- action: "slash_command"
|
||||
command: "server_status"
|
||||
user: "333333333333333333"
|
||||
guild: "123456789012345678"
|
||||
channel: "111111111111111111"
|
||||
expect:
|
||||
type: "interaction_response"
|
||||
data:
|
||||
type: 4 # CHANNEL_MESSAGE_WITH_SOURCE
|
||||
components: true
|
||||
|
||||
- action: "select_menu"
|
||||
custom_id: "server_dropdown"
|
||||
values: ["server_1"]
|
||||
user: "333333333333333333"
|
||||
expect:
|
||||
type: "message_create"
|
||||
channel: "111111111111111111"
|
||||
components: true
|
||||
|
||||
- action: "button_click"
|
||||
custom_id: "start_button"
|
||||
user: "333333333333333333"
|
||||
expect:
|
||||
type: "interaction_response"
|
||||
data:
|
||||
content_contains: "starting"
|
||||
@@ -0,0 +1,86 @@
|
||||
Metadata-Version: 2.4
|
||||
Name: apicord
|
||||
Version: 0.1.0
|
||||
Summary: Discord API Emulator for bot testing
|
||||
Author-email: Eaven Kimura <kimura.eaven@gmail.com>
|
||||
License: GPL-3.0
|
||||
Classifier: Development Status :: 3 - Alpha
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.10
|
||||
Classifier: Programming Language :: Python :: 3.11
|
||||
Classifier: Programming Language :: Python :: 3.12
|
||||
Requires-Python: >=3.10
|
||||
Description-Content-Type: text/markdown
|
||||
License-File: LICENSE
|
||||
Requires-Dist: aiohttp>=3.9.0
|
||||
Requires-Dist: websockets>=12.0
|
||||
Requires-Dist: pyyaml>=6.0
|
||||
Requires-Dist: click>=8.1.0
|
||||
Requires-Dist: pydantic>=2.5.0
|
||||
Requires-Dist: pydantic-settings>=2.1.0
|
||||
Provides-Extra: dev
|
||||
Requires-Dist: pytest>=7.4.0; extra == "dev"
|
||||
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
|
||||
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
|
||||
Requires-Dist: black>=23.0.0; extra == "dev"
|
||||
Requires-Dist: ruff>=0.1.0; extra == "dev"
|
||||
Requires-Dist: mypy>=1.5.0; extra == "dev"
|
||||
Dynamic: license-file
|
||||
|
||||
# APIcord
|
||||
|
||||
Discord API Emulator for bot testing.
|
||||
|
||||
A standalone Python CLI program that emulates the Discord API (REST + WebSocket Gateway), enabling self-contained testing of Discord bots without requiring a real Discord connection.
|
||||
|
||||
## Features
|
||||
|
||||
- **REST API Server** - Implements Discord REST API endpoints needed for bot operations
|
||||
- **WebSocket Gateway** - Emulates Discord's Gateway for real-time events (READY, INTERACTION_CREATE, etc.)
|
||||
- **State Management** - In-memory state with guilds, channels, users, messages, and interactions
|
||||
- **Test Scenarios** - YAML-based test scenarios for automated bot testing
|
||||
- **CLI Interface** - Easy-to-use commands for starting, testing, and managing the emulator
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip install -e .
|
||||
# Or for development
|
||||
pip install -e ".[dev]"
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Start emulator with a test scenario
|
||||
apicord start --scenario scenarios/basic_test.yaml
|
||||
|
||||
# Run automated test against a bot
|
||||
apicord test --scenario scenarios/full_test.yaml --bot-path /path/to/bot
|
||||
|
||||
# Start with custom configuration
|
||||
apicord start --port 8080 --guilds 2 --channels 5
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
apicord/
|
||||
├── src/apicord/
|
||||
│ ├── main.py # CLI entry point
|
||||
│ ├── config.py # Configuration management
|
||||
│ ├── rest/ # REST API server (aiohttp)
|
||||
│ ├── gateways/ # WebSocket gateway (websockets)
|
||||
│ ├── state/ # State management
|
||||
│ ├── models/ # Pydantic models for Discord objects
|
||||
│ └── cli/ # CLI commands
|
||||
├── tests/ # Unit tests
|
||||
├── scenarios/ # YAML test scenarios
|
||||
└── pyproject.toml
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
GPL-3.0 - See LICENSE file for details.
|
||||
@@ -0,0 +1,24 @@
|
||||
LICENSE
|
||||
README.md
|
||||
pyproject.toml
|
||||
src/apicord/__init__.py
|
||||
src/apicord/config.py
|
||||
src/apicord/main.py
|
||||
src/apicord.egg-info/PKG-INFO
|
||||
src/apicord.egg-info/SOURCES.txt
|
||||
src/apicord.egg-info/dependency_links.txt
|
||||
src/apicord.egg-info/entry_points.txt
|
||||
src/apicord.egg-info/requires.txt
|
||||
src/apicord.egg-info/top_level.txt
|
||||
src/apicord/cli/__init__.py
|
||||
src/apicord/cli/commands.py
|
||||
src/apicord/gateways/__init__.py
|
||||
src/apicord/gateways/server.py
|
||||
src/apicord/models/__init__.py
|
||||
src/apicord/models/discord.py
|
||||
src/apicord/rest/__init__.py
|
||||
src/apicord/rest/server.py
|
||||
src/apicord/state/__init__.py
|
||||
src/apicord/state/manager.py
|
||||
tests/test_models.py
|
||||
tests/test_state_manager.py
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
[console_scripts]
|
||||
apicord = apicord.main:main
|
||||
@@ -0,0 +1,14 @@
|
||||
aiohttp>=3.9.0
|
||||
websockets>=12.0
|
||||
pyyaml>=6.0
|
||||
click>=8.1.0
|
||||
pydantic>=2.5.0
|
||||
pydantic-settings>=2.1.0
|
||||
|
||||
[dev]
|
||||
pytest>=7.4.0
|
||||
pytest-asyncio>=0.21.0
|
||||
pytest-cov>=4.1.0
|
||||
black>=23.0.0
|
||||
ruff>=0.1.0
|
||||
mypy>=1.5.0
|
||||
@@ -0,0 +1 @@
|
||||
apicord
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
APIcord - Discord API Emulator for bot testing.
|
||||
|
||||
A standalone Python CLI program that emulates the Discord API (REST + WebSocket Gateway),
|
||||
enabling self-contained testing of Discord bots without requiring a real Discord connection.
|
||||
"""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__author__ = "Eaven Kimura"
|
||||
__license__ = "GPL-3.0"
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
"""CLI Commands Package"""
|
||||
Binary file not shown.
@@ -0,0 +1,355 @@
|
||||
"""
|
||||
CLI Commands for APIcord.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import click
|
||||
import yaml
|
||||
|
||||
from apicord.config import get_config
|
||||
from apicord.state.manager import StateManager
|
||||
from apicord.rest.server import RESTServer
|
||||
from apicord.gateways.server import GatewayServer
|
||||
|
||||
logger = logging.getLogger("apicord")
|
||||
|
||||
|
||||
@click.command()
|
||||
@click.option(
|
||||
"--scenario",
|
||||
"-s",
|
||||
type=click.Path(exists=True, path_type=Path),
|
||||
help="Path to scenario YAML file",
|
||||
)
|
||||
@click.option(
|
||||
"--guilds",
|
||||
"-g",
|
||||
type=int,
|
||||
default=1,
|
||||
help="Number of guilds to create (if no scenario)",
|
||||
)
|
||||
@click.option(
|
||||
"--channels",
|
||||
"-c",
|
||||
type=int,
|
||||
default=3,
|
||||
help="Number of channels per guild (if no scenario)",
|
||||
)
|
||||
@click.option(
|
||||
"--users",
|
||||
"-u",
|
||||
type=int,
|
||||
default=5,
|
||||
help="Number of test users (if no scenario)",
|
||||
)
|
||||
@click.pass_context
|
||||
def start(ctx: click.Context, scenario: Optional[Path], guilds: int, channels: int, users: int) -> None:
|
||||
"""Start the APIcord emulator server."""
|
||||
config = ctx.obj["config"] if ctx.obj else get_config()
|
||||
|
||||
async def run_server():
|
||||
# Initialize state manager
|
||||
state_manager = StateManager(config)
|
||||
|
||||
# Load scenario if provided
|
||||
if scenario:
|
||||
logger.info(f"Loading scenario from {scenario}")
|
||||
with open(scenario) as f:
|
||||
scenario_data = yaml.safe_load(f)
|
||||
await state_manager.load_scenario(scenario_data)
|
||||
else:
|
||||
logger.info(f"Creating default state: {guilds} guilds, {channels} channels/guild, {users} users")
|
||||
await state_manager.create_default_state(guilds=guilds, channels_per_guild=channels, users=users)
|
||||
|
||||
# Start REST server
|
||||
rest_server = RESTServer(config, state_manager)
|
||||
rest_task = asyncio.create_task(rest_server.start())
|
||||
|
||||
# Start Gateway server
|
||||
gateway_server = GatewayServer(config, state_manager)
|
||||
gateway_task = asyncio.create_task(gateway_server.start())
|
||||
|
||||
logger.info(f"APIcord started!")
|
||||
logger.info(f" REST API: http://{config.host}:{config.rest_port}")
|
||||
logger.info(f" Gateway: ws://{config.host}:{config.gateway_port}")
|
||||
logger.info(f" Bot Token: {config.bot_token}")
|
||||
logger.info("Press Ctrl+C to stop")
|
||||
|
||||
try:
|
||||
await asyncio.gather(rest_task, gateway_task)
|
||||
except KeyboardInterrupt:
|
||||
logger.info("Shutting down...")
|
||||
finally:
|
||||
await rest_server.stop()
|
||||
await gateway_server.stop()
|
||||
if config.persist_state:
|
||||
await state_manager.save_state()
|
||||
logger.info(f"State saved to {config.state_file}")
|
||||
|
||||
asyncio.run(run_server())
|
||||
|
||||
|
||||
@click.command()
|
||||
@click.option(
|
||||
"--scenario",
|
||||
"-s",
|
||||
type=click.Path(exists=True, path_type=Path),
|
||||
required=True,
|
||||
help="Path to test scenario YAML file",
|
||||
)
|
||||
@click.option(
|
||||
"--bot-path",
|
||||
"-b",
|
||||
type=click.Path(exists=True, path_type=Path),
|
||||
required=True,
|
||||
help="Path to bot project directory",
|
||||
)
|
||||
@click.option(
|
||||
"--timeout",
|
||||
"-t",
|
||||
type=int,
|
||||
default=60,
|
||||
help="Test timeout in seconds",
|
||||
)
|
||||
@click.pass_context
|
||||
def test(ctx: click.Context, scenario: Path, bot_path: Path, timeout: int) -> None:
|
||||
"""Run automated test scenario against a bot."""
|
||||
config = ctx.obj["config"] if ctx.obj else get_config()
|
||||
|
||||
async def run_test():
|
||||
logger.info(f"Running test scenario: {scenario}")
|
||||
logger.info(f"Bot path: {bot_path}")
|
||||
|
||||
# Load scenario
|
||||
with open(scenario) as f:
|
||||
scenario_data = yaml.safe_load(f)
|
||||
|
||||
# Initialize state manager with scenario
|
||||
state_manager = StateManager(config)
|
||||
await state_manager.load_scenario(scenario_data)
|
||||
|
||||
# Start emulator servers
|
||||
rest_server = RESTServer(config, state_manager)
|
||||
gateway_server = GatewayServer(config, state_manager)
|
||||
|
||||
rest_task = asyncio.create_task(rest_server.start())
|
||||
gateway_task = asyncio.create_task(gateway_server.start())
|
||||
|
||||
# Give servers time to start
|
||||
await asyncio.sleep(1)
|
||||
|
||||
try:
|
||||
# Run bot in emulator mode
|
||||
logger.info("Starting bot in emulator mode...")
|
||||
bot_process = await asyncio.create_subprocess_exec(
|
||||
sys.executable, "main.py",
|
||||
"--emulator",
|
||||
"--emulator-rest-url", config.get_rest_url(),
|
||||
"--emulator-gateway-url", config.get_gateway_url(),
|
||||
"--emulator-token", config.bot_token,
|
||||
cwd=bot_path,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
|
||||
# Run scenario steps
|
||||
test_result = await run_scenario_steps(scenario_data, state_manager, timeout)
|
||||
|
||||
# Wait for bot to finish (with timeout)
|
||||
try:
|
||||
await asyncio.wait_for(bot_process.wait(), timeout=5.0)
|
||||
except asyncio.TimeoutError:
|
||||
bot_process.terminate()
|
||||
await bot_process.wait()
|
||||
|
||||
# Print result
|
||||
if test_result.passed:
|
||||
logger.info("✅ TEST PASSED")
|
||||
return 0
|
||||
else:
|
||||
logger.error("❌ TEST FAILED")
|
||||
for failure in test_result.failures:
|
||||
logger.error(f" - {failure}")
|
||||
return 1
|
||||
|
||||
finally:
|
||||
await rest_server.stop()
|
||||
await gateway_server.stop()
|
||||
|
||||
result = asyncio.run(run_test())
|
||||
sys.exit(result)
|
||||
|
||||
|
||||
async def run_scenario_steps(scenario_data: dict, state_manager: StateManager, timeout: int) -> "TestResult":
|
||||
"""Execute scenario steps and validate expectations."""
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List
|
||||
|
||||
@dataclass
|
||||
class TestResult:
|
||||
passed: bool = True
|
||||
failures: List[str] = field(default_factory=list)
|
||||
|
||||
result = TestResult()
|
||||
|
||||
steps = scenario_data.get("steps", [])
|
||||
if not steps:
|
||||
logger.warning("No steps defined in scenario")
|
||||
return result
|
||||
|
||||
logger.info(f"Executing {len(steps)} scenario steps...")
|
||||
|
||||
for i, step in enumerate(steps, 1):
|
||||
action = step.get("action")
|
||||
logger.info(f"Step {i}/{len(steps)}: {action}")
|
||||
|
||||
try:
|
||||
if action == "slash_command":
|
||||
await _execute_slash_command(step, state_manager)
|
||||
elif action == "select_menu":
|
||||
await _execute_select_menu(step, state_manager)
|
||||
elif action == "button_click":
|
||||
await _execute_button_click(step, state_manager)
|
||||
elif action == "wait":
|
||||
await asyncio.sleep(step.get("duration", 1))
|
||||
else:
|
||||
logger.warning(f"Unknown action: {action}")
|
||||
|
||||
# Validate expectations
|
||||
if "expect" in step:
|
||||
await _validate_expectation(step["expect"], state_manager)
|
||||
|
||||
except Exception as e:
|
||||
result.passed = False
|
||||
result.failures.append(f"Step {i} ({action}): {str(e)}")
|
||||
logger.error(f"Step {i} failed: {e}")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def _execute_slash_command(step: dict, state_manager: StateManager) -> None:
|
||||
"""Execute a slash command via the emulator."""
|
||||
# This would send an interaction to the bot
|
||||
# Implementation depends on the test framework
|
||||
pass
|
||||
|
||||
|
||||
async def _execute_select_menu(step: dict, state_manager: StateManager) -> None:
|
||||
"""Execute a select menu interaction."""
|
||||
pass
|
||||
|
||||
|
||||
async def _execute_button_click(step: dict, state_manager: StateManager) -> None:
|
||||
"""Execute a button click interaction."""
|
||||
pass
|
||||
|
||||
|
||||
async def _validate_expectation(expect: dict, state_manager: StateManager) -> None:
|
||||
"""Validate an expectation against current state."""
|
||||
pass
|
||||
|
||||
|
||||
@click.command()
|
||||
@click.option(
|
||||
"--state-file",
|
||||
"-f",
|
||||
type=click.Path(path_type=Path),
|
||||
default="apicord_state.json",
|
||||
help="State file to reset",
|
||||
)
|
||||
@click.pass_context
|
||||
def reset(ctx: click.Context, state_file: Path) -> None:
|
||||
"""Reset emulator state."""
|
||||
config = ctx.obj["config"] if ctx.obj else get_config()
|
||||
|
||||
if state_file.exists():
|
||||
state_file.unlink()
|
||||
logger.info(f"Removed state file: {state_file}")
|
||||
else:
|
||||
logger.info(f"State file does not exist: {state_file}")
|
||||
|
||||
# Also clear any in-memory state if running
|
||||
logger.info("State reset complete")
|
||||
|
||||
|
||||
@click.command()
|
||||
@click.option(
|
||||
"--state-file",
|
||||
"-f",
|
||||
type=click.Path(exists=True, path_type=Path),
|
||||
default="apicord_state.json",
|
||||
help="State file to export",
|
||||
)
|
||||
@click.option(
|
||||
"--output",
|
||||
"-o",
|
||||
type=click.Path(path_type=Path),
|
||||
help="Output file (default: stdout)",
|
||||
)
|
||||
@click.pass_context
|
||||
def export(ctx: click.Context, state_file: Path, output: Optional[Path]) -> None:
|
||||
"""Export emulator state to JSON."""
|
||||
config = ctx.obj["config"] if ctx.obj else get_config()
|
||||
|
||||
if not state_file.exists():
|
||||
logger.error(f"State file not found: {state_file}")
|
||||
sys.exit(1)
|
||||
|
||||
with open(state_file) as f:
|
||||
state = json.load(f)
|
||||
|
||||
if output:
|
||||
with open(output, "w") as f:
|
||||
json.dump(state, f, indent=2)
|
||||
logger.info(f"State exported to {output}")
|
||||
else:
|
||||
print(json.dumps(state, indent=2))
|
||||
|
||||
|
||||
@click.command()
|
||||
@click.option(
|
||||
"--scenario",
|
||||
"-s",
|
||||
type=click.Path(exists=True, path_type=Path),
|
||||
required=True,
|
||||
help="Path to scenario YAML file to validate",
|
||||
)
|
||||
@click.pass_context
|
||||
def validate(ctx: click.Context, scenario: Path) -> None:
|
||||
"""Validate a scenario YAML file."""
|
||||
logger.info(f"Validating scenario: {scenario}")
|
||||
|
||||
with open(scenario) as f:
|
||||
try:
|
||||
scenario_data = yaml.safe_load(f)
|
||||
except yaml.YAMLError as e:
|
||||
logger.error(f"Invalid YAML: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
# Validate required fields
|
||||
required_fields = ["name", "steps"]
|
||||
for field in required_fields:
|
||||
if field not in scenario_data:
|
||||
logger.error(f"Missing required field: {field}")
|
||||
sys.exit(1)
|
||||
|
||||
# Validate steps
|
||||
steps = scenario_data.get("steps", [])
|
||||
if not steps:
|
||||
logger.warning("Scenario has no steps")
|
||||
|
||||
valid_actions = {"slash_command", "select_menu", "button_click", "wait"}
|
||||
for i, step in enumerate(steps, 1):
|
||||
action = step.get("action")
|
||||
if action not in valid_actions:
|
||||
logger.error(f"Step {i}: Invalid action '{action}'. Valid actions: {valid_actions}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.info(f"✅ Scenario '{scenario_data.get('name', 'unnamed')}' is valid")
|
||||
logger.info(f" Steps: {len(steps)}")
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
Configuration Management Module
|
||||
|
||||
Handles loading, validation, and access to emulator configuration.
|
||||
Supports both config file and environment variable overrides.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class EmulatorConfig(BaseSettings):
|
||||
"""Emulator configuration loaded from environment variables and config file."""
|
||||
|
||||
# Server settings
|
||||
host: str = Field(default="127.0.0.1", description="Host to bind the emulator server")
|
||||
rest_port: int = Field(default=8080, description="Port for REST API server")
|
||||
gateway_port: int = Field(default=8081, description="Port for WebSocket Gateway")
|
||||
|
||||
# Discord API compatibility
|
||||
api_version: int = Field(default=10, description="Discord API version to emulate")
|
||||
gateway_version: int = Field(default=10, description="Gateway version to emulate")
|
||||
|
||||
# Bot settings (for testing)
|
||||
bot_token: str = Field(default="test_token_123", description="Test bot token")
|
||||
bot_id: str = Field(default="444444444444444444", description="Test bot user ID")
|
||||
bot_username: str = Field(default="TestBot", description="Test bot username")
|
||||
bot_discriminator: str = Field(default="0000", description="Test bot discriminator")
|
||||
|
||||
# State settings
|
||||
persist_state: bool = Field(default=False, description="Persist state to disk")
|
||||
state_file: str = Field(default="apicord_state.json", description="State persistence file")
|
||||
|
||||
# Rate limiting (optional)
|
||||
enable_rate_limits: bool = Field(default=False, description="Enable Discord-style rate limits")
|
||||
rate_limit_requests: int = Field(default=50, description="Requests per rate limit window")
|
||||
rate_limit_window: float = Field(default=1.0, description="Rate limit window in seconds")
|
||||
|
||||
# Logging
|
||||
log_level: str = Field(default="INFO", description="Logging level")
|
||||
log_format: str = Field(default="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
||||
|
||||
# Scenario
|
||||
default_scenario: Optional[str] = Field(default=None, description="Default scenario to load")
|
||||
|
||||
model_config = {
|
||||
"env_prefix": "APICORD_",
|
||||
"env_file": ".env",
|
||||
"env_file_encoding": "utf-8",
|
||||
"extra": "ignore",
|
||||
}
|
||||
|
||||
def get_rest_url(self) -> str:
|
||||
"""Get the REST API base URL."""
|
||||
return f"http://{self.host}:{self.rest_port}"
|
||||
|
||||
def get_gateway_url(self) -> str:
|
||||
"""Get the WebSocket Gateway URL."""
|
||||
return f"ws://{self.host}:{self.gateway_port}"
|
||||
|
||||
|
||||
# Global config instance
|
||||
_config: Optional[EmulatorConfig] = None
|
||||
|
||||
|
||||
def get_config() -> EmulatorConfig:
|
||||
"""Get the global config instance."""
|
||||
global _config
|
||||
if _config is None:
|
||||
_config = EmulatorConfig()
|
||||
return _config
|
||||
|
||||
|
||||
def set_config(config: EmulatorConfig) -> None:
|
||||
"""Set the global config instance."""
|
||||
global _config
|
||||
_config = config
|
||||
@@ -0,0 +1 @@
|
||||
"""WebSocket Gateway Package"""
|
||||
Binary file not shown.
@@ -0,0 +1,285 @@
|
||||
"""
|
||||
WebSocket Gateway Server Module
|
||||
|
||||
Implements the Discord Gateway WebSocket server for real-time events.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import random
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Set
|
||||
|
||||
import websockets
|
||||
from websockets.server import WebSocketServerProtocol
|
||||
|
||||
from apicord.config import EmulatorConfig
|
||||
from apicord.state.manager import StateManager
|
||||
from apicord.models import (
|
||||
User,
|
||||
Guild,
|
||||
Channel,
|
||||
Role,
|
||||
Interaction,
|
||||
InteractionType,
|
||||
GatewayInfo,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("apicord.gateway")
|
||||
|
||||
|
||||
class GatewayConnection:
|
||||
"""Represents a single WebSocket connection to the gateway."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
websocket: WebSocketServerProtocol,
|
||||
config: EmulatorConfig,
|
||||
state: StateManager,
|
||||
) -> None:
|
||||
self.ws = websocket
|
||||
self.config = config
|
||||
self.state = state
|
||||
self.sequence: Optional[int] = None
|
||||
self.session_id: Optional[str] = None
|
||||
self.heartbeat_interval: float = 41250 / 1000 # 41.25 seconds (Discord default)
|
||||
self.heartbeat_task: Optional[asyncio.Task] = None
|
||||
self.identified: bool = False
|
||||
self.user: Optional[User] = None
|
||||
self.guilds: Set[str] = set()
|
||||
self._last_heartbeat_ack: bool = True
|
||||
|
||||
async def handle(self) -> None:
|
||||
"""Main connection handler loop."""
|
||||
logger.info(f"New gateway connection from {self.ws.remote_address}")
|
||||
|
||||
try:
|
||||
# Send HELLO
|
||||
await self._send_hello()
|
||||
|
||||
# Process incoming messages
|
||||
async for message in self.ws:
|
||||
try:
|
||||
data = json.loads(message)
|
||||
await self._handle_message(data)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning(f"Invalid JSON from {self.ws.remote_address}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error handling message: {e}", exc_info=True)
|
||||
|
||||
except websockets.exceptions.ConnectionClosed:
|
||||
logger.info(f"Connection closed: {self.ws.remote_address}")
|
||||
except Exception as e:
|
||||
logger.error(f"Connection error: {e}", exc_info=True)
|
||||
finally:
|
||||
await self._cleanup()
|
||||
|
||||
async def _send_hello(self) -> None:
|
||||
"""Send HELLO payload (opcode 10)."""
|
||||
hello = {
|
||||
"op": 10,
|
||||
"d": {
|
||||
"heartbeat_interval": int(self.heartbeat_interval * 1000),
|
||||
}
|
||||
}
|
||||
await self._send(hello)
|
||||
logger.debug("Sent HELLO")
|
||||
|
||||
# Start heartbeat monitoring
|
||||
self.heartbeat_task = asyncio.create_task(self._heartbeat_monitor())
|
||||
|
||||
async def _heartbeat_monitor(self) -> None:
|
||||
"""Monitor heartbeats and send heartbeats."""
|
||||
while True:
|
||||
try:
|
||||
await asyncio.sleep(self.heartbeat_interval)
|
||||
|
||||
if not self._last_heartbeat_ack:
|
||||
logger.warning("Heartbeat ACK not received, closing connection")
|
||||
await self.ws.close(code=4009, reason="Heartbeat timeout")
|
||||
break
|
||||
|
||||
self._last_heartbeat_ack = False
|
||||
await self._send({"op": 1, "d": self.sequence})
|
||||
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
except Exception as e:
|
||||
logger.error(f"Heartbeat error: {e}")
|
||||
break
|
||||
|
||||
async def _handle_message(self, data: Dict[str, Any]) -> None:
|
||||
"""Handle incoming gateway message."""
|
||||
op = data.get("op")
|
||||
payload = data.get("d")
|
||||
seq = data.get("s")
|
||||
event_name = data.get("t")
|
||||
|
||||
# Update sequence number
|
||||
if seq is not None:
|
||||
self.sequence = seq
|
||||
|
||||
if op == 1: # Heartbeat
|
||||
await self._handle_heartbeat()
|
||||
elif op == 2: # Identify
|
||||
await self._handle_identify(payload)
|
||||
elif op == 3: # Presence Update
|
||||
await self._handle_presence_update(payload)
|
||||
elif op == 4: # Voice State Update
|
||||
pass
|
||||
elif op == 6: # Resume
|
||||
await self._handle_resume(payload)
|
||||
elif op == 11: # Heartbeat ACK
|
||||
self._last_heartbeat_ack = True
|
||||
else:
|
||||
logger.warning(f"Unknown opcode: {op}")
|
||||
|
||||
async def _handle_heartbeat(self) -> None:
|
||||
"""Handle incoming heartbeat (opcode 1)."""
|
||||
self._last_heartbeat_ack = True
|
||||
await self._send({"op": 11}) # Heartbeat ACK
|
||||
logger.debug("Sent heartbeat ACK")
|
||||
|
||||
async def _handle_identify(self, payload: Dict[str, Any]) -> None:
|
||||
"""Handle IDENTIFY payload (opcode 2)."""
|
||||
token = payload.get("token")
|
||||
if token != self.config.bot_token:
|
||||
logger.warning("Invalid token in IDENTIFY")
|
||||
await self.ws.close(code=4004, reason="Invalid token")
|
||||
return
|
||||
|
||||
# Mark as identified
|
||||
self.identified = True
|
||||
self.session_id = f"session_{random.randint(100000, 999999)}"
|
||||
|
||||
# Get bot user
|
||||
self.user = self.state.get_bot_user()
|
||||
|
||||
# Send READY event
|
||||
ready_data = {
|
||||
"v": self.config.gateway_version,
|
||||
"user": self.user.model_dump() if self.user else {},
|
||||
"guilds": [
|
||||
{"id": g.id, "unavailable": False} for g in self.state.list_guilds()
|
||||
],
|
||||
"session_id": self.session_id,
|
||||
"shard": [0, 1],
|
||||
"application": {
|
||||
"id": self.config.bot_id,
|
||||
"flags": 0
|
||||
}
|
||||
}
|
||||
|
||||
await self._send({
|
||||
"op": 0,
|
||||
"t": "READY",
|
||||
"s": self.sequence,
|
||||
"d": ready_data
|
||||
})
|
||||
|
||||
logger.info(f"Bot identified: {self.user.username if self.user else 'Unknown'} ({self.session_id})")
|
||||
|
||||
async def _handle_presence_update(self, payload: Dict[str, Any]) -> None:
|
||||
"""Handle presence update."""
|
||||
# Just acknowledge for now
|
||||
pass
|
||||
|
||||
async def _handle_resume(self, payload: Dict[str, Any]) -> None:
|
||||
"""Handle RESUME payload (opcode 6)."""
|
||||
token = payload.get("token")
|
||||
session_id = payload.get("session_id")
|
||||
seq = payload.get("seq")
|
||||
|
||||
if token != self.config.bot_token or session_id != self.session_id:
|
||||
logger.warning("Invalid RESUME")
|
||||
await self.ws.close(code=4004, reason="Invalid session")
|
||||
return
|
||||
|
||||
self.identified = True
|
||||
self.sequence = seq
|
||||
|
||||
# Send RESUMED event
|
||||
await self._send({
|
||||
"op": 0,
|
||||
"t": "RESUMED",
|
||||
"s": self.sequence,
|
||||
"d": {}
|
||||
})
|
||||
|
||||
logger.info("Session resumed")
|
||||
|
||||
async def _send(self, payload: Dict[str, Any]) -> None:
|
||||
"""Send JSON payload over WebSocket."""
|
||||
await self.ws.send(json.dumps(payload))
|
||||
|
||||
async def send_event(self, event_name: str, data: Dict[str, Any]) -> None:
|
||||
"""Send a gateway event (opcode 0)."""
|
||||
if not self.identified:
|
||||
return
|
||||
|
||||
self.sequence = (self.sequence or 0) + 1
|
||||
payload = {
|
||||
"op": 0,
|
||||
"t": event_name,
|
||||
"s": self.sequence,
|
||||
"d": data
|
||||
}
|
||||
await self._send(payload)
|
||||
|
||||
async def _cleanup(self) -> None:
|
||||
"""Cleanup on connection close."""
|
||||
if self.heartbeat_task:
|
||||
self.heartbeat_task.cancel()
|
||||
try:
|
||||
await self.heartbeat_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
|
||||
class GatewayServer:
|
||||
"""Discord Gateway WebSocket server."""
|
||||
|
||||
def __init__(self, config: EmulatorConfig, state: StateManager) -> None:
|
||||
self.config = config
|
||||
self.state = state
|
||||
self.server: Optional[websockets.WebSocketServer] = None
|
||||
self.connections: Set[GatewayConnection] = set()
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Start the WebSocket gateway server."""
|
||||
self.server = await websockets.serve(
|
||||
self._handle_connection,
|
||||
self.config.host,
|
||||
self.config.gateway_port,
|
||||
ping_interval=20,
|
||||
ping_timeout=10,
|
||||
)
|
||||
logger.info(f"Gateway server started on ws://{self.config.host}:{self.config.gateway_port}")
|
||||
|
||||
async def _handle_connection(self, websocket: WebSocketServerProtocol) -> None:
|
||||
"""Handle new WebSocket connection."""
|
||||
connection = GatewayConnection(websocket, self.config, self.state)
|
||||
self.connections.add(connection)
|
||||
|
||||
try:
|
||||
await connection.handle()
|
||||
finally:
|
||||
self.connections.discard(connection)
|
||||
|
||||
def broadcast_event(self, event_name: str, data: Dict[str, Any]) -> None:
|
||||
"""Broadcast an event to all connected clients."""
|
||||
for conn in self.connections:
|
||||
if conn.identified:
|
||||
asyncio.create_task(conn.send_event(event_name, data))
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Stop the gateway server."""
|
||||
# Close all connections
|
||||
for conn in self.connections:
|
||||
await conn.ws.close(code=1001, reason="Server shutting down")
|
||||
|
||||
if self.server:
|
||||
self.server.close()
|
||||
await self.server.wait_closed()
|
||||
logger.info("Gateway server stopped")
|
||||
@@ -0,0 +1,133 @@
|
||||
"""
|
||||
Main Entry Point for APIcord CLI.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import click
|
||||
|
||||
from apicord.config import EmulatorConfig, get_config, set_config
|
||||
from apicord.cli.commands import start, test, reset, export, validate
|
||||
|
||||
|
||||
def setup_logging(level: str = "INFO", format_str: str = None) -> None:
|
||||
"""Configure application-wide logging."""
|
||||
if format_str is None:
|
||||
format_str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
|
||||
logging.basicConfig(
|
||||
level=getattr(logging, level.upper()),
|
||||
format=format_str,
|
||||
handlers=[
|
||||
logging.StreamHandler(sys.stdout),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@click.group()
|
||||
@click.option(
|
||||
"--config-file",
|
||||
"-c",
|
||||
type=click.Path(exists=True, path_type=Path),
|
||||
help="Path to configuration file (YAML)",
|
||||
)
|
||||
@click.option(
|
||||
"--log-level",
|
||||
"-l",
|
||||
type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]),
|
||||
default="INFO",
|
||||
help="Set logging level",
|
||||
)
|
||||
@click.option(
|
||||
"--host",
|
||||
default="127.0.0.1",
|
||||
help="Host to bind the emulator server",
|
||||
)
|
||||
@click.option(
|
||||
"--rest-port",
|
||||
type=int,
|
||||
default=8080,
|
||||
help="Port for REST API server",
|
||||
)
|
||||
@click.option(
|
||||
"--gateway-port",
|
||||
type=int,
|
||||
default=8081,
|
||||
help="Port for WebSocket Gateway",
|
||||
)
|
||||
@click.option(
|
||||
"--bot-token",
|
||||
default="test_token_123",
|
||||
help="Test bot token",
|
||||
)
|
||||
@click.option(
|
||||
"--persist-state/--no-persist-state",
|
||||
default=False,
|
||||
help="Persist state to disk",
|
||||
)
|
||||
@click.pass_context
|
||||
def cli(
|
||||
ctx: click.Context,
|
||||
config_file: Path = None,
|
||||
log_level: str = "INFO",
|
||||
host: str = "127.0.0.1",
|
||||
rest_port: int = 8080,
|
||||
gateway_port: int = 8081,
|
||||
bot_token: str = "test_token_123",
|
||||
persist_state: bool = False,
|
||||
) -> None:
|
||||
"""APIcord - Discord API Emulator for bot testing.
|
||||
|
||||
A standalone Python CLI program that emulates the Discord API
|
||||
(REST + WebSocket Gateway), enabling self-contained testing of
|
||||
Discord bots without requiring a real Discord connection.
|
||||
"""
|
||||
# Setup logging early
|
||||
setup_logging(log_level)
|
||||
|
||||
# Load config from file if provided, otherwise use env vars and CLI args
|
||||
if config_file:
|
||||
import yaml
|
||||
with open(config_file) as f:
|
||||
file_config = yaml.safe_load(f)
|
||||
config = EmulatorConfig(**file_config)
|
||||
else:
|
||||
config = EmulatorConfig(
|
||||
host=host,
|
||||
rest_port=rest_port,
|
||||
gateway_port=gateway_port,
|
||||
bot_token=bot_token,
|
||||
persist_state=persist_state,
|
||||
log_level=log_level,
|
||||
)
|
||||
|
||||
set_config(config)
|
||||
|
||||
# Store config in context for subcommands
|
||||
ctx.ensure_object(dict)
|
||||
ctx.obj["config"] = config
|
||||
|
||||
|
||||
# Add subcommands
|
||||
cli.add_command(start)
|
||||
cli.add_command(test)
|
||||
cli.add_command(reset)
|
||||
cli.add_command(export)
|
||||
cli.add_command(validate)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Main entry point for the CLI."""
|
||||
try:
|
||||
cli()
|
||||
return 0
|
||||
except Exception as e:
|
||||
logging.getLogger("apicord").critical(f"Fatal error: {e}", exc_info=True)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Pydantic Models for Discord Objects"""
|
||||
|
||||
from apicord.models.discord import (
|
||||
User,
|
||||
BotUser,
|
||||
Role,
|
||||
Channel,
|
||||
ChannelType,
|
||||
Guild,
|
||||
Message,
|
||||
MessageType,
|
||||
Interaction,
|
||||
InteractionType,
|
||||
InteractionCallbackType,
|
||||
ComponentType,
|
||||
ButtonStyle,
|
||||
Snowflake,
|
||||
ScenarioData,
|
||||
ScenarioGuild,
|
||||
ScenarioChannel,
|
||||
ScenarioRole,
|
||||
ScenarioUser,
|
||||
ScenarioBot,
|
||||
GatewayInfo,
|
||||
RESTError,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"User",
|
||||
"BotUser",
|
||||
"Role",
|
||||
"Channel",
|
||||
"ChannelType",
|
||||
"Guild",
|
||||
"Message",
|
||||
"MessageType",
|
||||
"Interaction",
|
||||
"InteractionType",
|
||||
"InteractionCallbackType",
|
||||
"ComponentType",
|
||||
"ButtonStyle",
|
||||
"Snowflake",
|
||||
"ScenarioData",
|
||||
"ScenarioGuild",
|
||||
"ScenarioChannel",
|
||||
"ScenarioRole",
|
||||
"ScenarioUser",
|
||||
"ScenarioBot",
|
||||
"GatewayInfo",
|
||||
"RESTError",
|
||||
]
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,338 @@
|
||||
"""
|
||||
Pydantic Models for Discord Objects
|
||||
|
||||
These models represent the core Discord objects used by the emulator.
|
||||
Based on Discord API documentation.
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
from pydantic import BaseModel, Field
|
||||
from enum import IntEnum
|
||||
|
||||
|
||||
class ChannelType(IntEnum):
|
||||
GUILD_TEXT = 0
|
||||
DM = 1
|
||||
GUILD_VOICE = 2
|
||||
GROUP_DM = 3
|
||||
GUILD_CATEGORY = 4
|
||||
GUILD_NEWS = 5
|
||||
GUILD_STORE = 6
|
||||
GUILD_NEWS_THREAD = 10
|
||||
GUILD_PUBLIC_THREAD = 11
|
||||
GUILD_PRIVATE_THREAD = 12
|
||||
GUILD_STAGE_VOICE = 13
|
||||
GUILD_DIRECTORY = 14
|
||||
GUILD_FORUM = 15
|
||||
|
||||
|
||||
class MessageType(IntEnum):
|
||||
DEFAULT = 0
|
||||
RECIPIENT_ADD = 1
|
||||
RECIPIENT_REMOVE = 2
|
||||
CALL = 3
|
||||
CHANNEL_NAME_CHANGE = 4
|
||||
CHANNEL_ICON_CHANGE = 5
|
||||
CHANNEL_PINNED_MESSAGE = 6
|
||||
USER_JOIN = 7
|
||||
GUILD_BOOST = 8
|
||||
GUILD_BOOST_TIER_1 = 9
|
||||
GUILD_BOOST_TIER_2 = 10
|
||||
GUILD_BOOST_TIER_3 = 11
|
||||
CHANNEL_FOLLOW_ADD = 12
|
||||
GUILD_DISCOVERY_DISQUALIFIED = 14
|
||||
GUILD_DISCOVERY_REQUALIFIED = 15
|
||||
GUILD_DISCOVERY_GRACE_PERIOD_INITIAL_WARNING = 16
|
||||
GUILD_DISCOVERY_GRACE_PERIOD_FINAL_WARNING = 17
|
||||
THREAD_CREATED = 18
|
||||
REPLY = 19
|
||||
CHAT_INPUT_COMMAND = 20
|
||||
THREAD_STARTER_MESSAGE = 21
|
||||
GUILD_INVITE_REMINDER = 22
|
||||
CONTEXT_MENU_COMMAND = 23
|
||||
|
||||
|
||||
class InteractionType(IntEnum):
|
||||
PING = 1
|
||||
APPLICATION_COMMAND = 2
|
||||
MESSAGE_COMPONENT = 3
|
||||
APPLICATION_COMMAND_AUTOCOMPLETE = 4
|
||||
MODAL_SUBMIT = 5
|
||||
|
||||
|
||||
class InteractionCallbackType(IntEnum):
|
||||
PONG = 1
|
||||
CHANNEL_MESSAGE_WITH_SOURCE = 4
|
||||
DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE = 5
|
||||
DEFERRED_UPDATE_MESSAGE = 6
|
||||
UPDATE_MESSAGE = 7
|
||||
APPLICATION_COMMAND_AUTOCOMPLETE_RESULT = 8
|
||||
MODAL = 9
|
||||
|
||||
|
||||
class ComponentType(IntEnum):
|
||||
ACTION_ROW = 1
|
||||
BUTTON = 2
|
||||
SELECT_MENU = 3
|
||||
TEXT_INPUT = 4
|
||||
USER_SELECT = 5
|
||||
ROLE_SELECT = 6
|
||||
MENTIONABLE_SELECT = 7
|
||||
|
||||
|
||||
class ButtonStyle(IntEnum):
|
||||
PRIMARY = 1
|
||||
SECONDARY = 2
|
||||
SUCCESS = 3
|
||||
DANGER = 4
|
||||
LINK = 5
|
||||
|
||||
|
||||
# Base Models
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic_core import core_schema
|
||||
from enum import IntEnum
|
||||
|
||||
|
||||
class Snowflake(str):
|
||||
"""Discord snowflake ID."""
|
||||
|
||||
@classmethod
|
||||
def __get_pydantic_core_schema__(cls, source_type, handler):
|
||||
return core_schema.with_info_plain_validator_function(
|
||||
cls.validate,
|
||||
serialization=core_schema.to_string_ser_schema(),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def validate(cls, v, _info):
|
||||
if isinstance(v, int):
|
||||
return str(v)
|
||||
if isinstance(v, str) and v.isdigit():
|
||||
return v
|
||||
raise ValueError("Snowflake must be a numeric string or integer")
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
"""Discord User object."""
|
||||
id: Snowflake
|
||||
username: str
|
||||
discriminator: str
|
||||
bot: bool = False
|
||||
avatar: Optional[str] = None
|
||||
system: bool = False
|
||||
mfa_enabled: bool = False
|
||||
locale: Optional[str] = None
|
||||
verified: bool = False
|
||||
email: Optional[str] = None
|
||||
flags: int = 0
|
||||
premium_type: int = 0
|
||||
public_flags: int = 0
|
||||
# Guild-specific roles (guild_id -> list of role_ids)
|
||||
guild_roles: Dict[str, List[str]] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class BotUser(User):
|
||||
"""Bot user with additional fields."""
|
||||
bot: bool = True
|
||||
token: Optional[str] = None
|
||||
|
||||
|
||||
class Role(BaseModel):
|
||||
"""Discord Role object."""
|
||||
id: Snowflake
|
||||
name: str
|
||||
color: int = 0
|
||||
hoist: bool = False
|
||||
position: int = 0
|
||||
permissions: str # Bitwise permissions as string
|
||||
managed: bool = False
|
||||
mentionable: bool = False
|
||||
tags: Optional[Dict[str, Any]] = None
|
||||
guild_id: Optional[str] = None
|
||||
|
||||
|
||||
class Channel(BaseModel):
|
||||
"""Discord Channel object."""
|
||||
id: Snowflake
|
||||
type: ChannelType
|
||||
guild_id: Optional[str] = None
|
||||
name: Optional[str] = None
|
||||
topic: Optional[str] = None
|
||||
position: int = 0
|
||||
permission_overwrites: List[Dict[str, Any]] = Field(default_factory=list)
|
||||
nsfw: bool = False
|
||||
parent_id: Optional[str] = None
|
||||
rate_limit_per_user: int = 0
|
||||
# Message tracking
|
||||
message_ids: List[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class Guild(BaseModel):
|
||||
"""Discord Guild object."""
|
||||
id: Snowflake
|
||||
name: str
|
||||
icon: Optional[str] = None
|
||||
owner_id: Snowflake
|
||||
roles: List[str] = Field(default_factory=list) # Role IDs
|
||||
channels: List[str] = Field(default_factory=list) # Channel IDs
|
||||
icon_hash: Optional[str] = None
|
||||
splash: Optional[str] = None
|
||||
discovery_splash: Optional[str] = None
|
||||
features: List[str] = Field(default_factory=list)
|
||||
verification_level: int = 0
|
||||
default_message_notifications: int = 0
|
||||
explicit_content_filter: int = 0
|
||||
mfa_level: int = 0
|
||||
application_id: Optional[str] = None
|
||||
system_channel_id: Optional[str] = None
|
||||
system_channel_flags: int = 0
|
||||
rules_channel_id: Optional[str] = None
|
||||
max_presences: Optional[int] = None
|
||||
max_members: int = 250000
|
||||
vanity_url_code: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
banner: Optional[str] = None
|
||||
premium_tier: int = 0
|
||||
premium_subscription_count: int = 0
|
||||
preferred_locale: str = "en-US"
|
||||
public_updates_channel_id: Optional[str] = None
|
||||
max_video_channel_users: int = 25
|
||||
approximate_member_count: int = 0
|
||||
approximate_presence_count: int = 0
|
||||
welcome_screen: Optional[Dict[str, Any]] = None
|
||||
nsfw_level: int = 0
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
"""Discord Message object."""
|
||||
id: Snowflake
|
||||
channel_id: Snowflake
|
||||
author: User
|
||||
content: str
|
||||
timestamp: str # ISO8601
|
||||
edited_timestamp: Optional[str] = None
|
||||
tts: bool = False
|
||||
mention_everyone: bool = False
|
||||
mentions: List[User] = Field(default_factory=list)
|
||||
mention_roles: List[str] = Field(default_factory=list)
|
||||
mention_channels: List[Dict[str, Any]] = Field(default_factory=list)
|
||||
attachments: List[Dict[str, Any]] = Field(default_factory=list)
|
||||
embeds: List[Dict[str, Any]] = Field(default_factory=list)
|
||||
reactions: List[Dict[str, Any]] = Field(default_factory=list)
|
||||
nonce: Optional[str] = None
|
||||
pinned: bool = False
|
||||
webhook_id: Optional[str] = None
|
||||
type: MessageType = MessageType.DEFAULT
|
||||
activity: Optional[Dict[str, Any]] = None
|
||||
application: Optional[Dict[str, Any]] = None
|
||||
application_id: Optional[str] = None
|
||||
message_reference: Optional[Dict[str, Any]] = None
|
||||
flags: int = 0
|
||||
components: List[Dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
|
||||
class Interaction(BaseModel):
|
||||
"""Discord Interaction object."""
|
||||
id: Snowflake
|
||||
type: InteractionType
|
||||
application_id: Snowflake
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
guild_id: Optional[str] = None
|
||||
channel_id: Optional[str] = None
|
||||
channel: Optional[Channel] = None
|
||||
member: Optional[Dict[str, Any]] = None
|
||||
user: Optional[User] = None
|
||||
token: str
|
||||
version: int = 1
|
||||
message: Optional[Message] = None
|
||||
app_permissions: Optional[str] = None
|
||||
locale: str = "en-US"
|
||||
guild_locale: str = "en-US"
|
||||
responded: bool = False
|
||||
|
||||
|
||||
class InteractionResponse(BaseModel):
|
||||
"""Interaction response payload."""
|
||||
type: InteractionCallbackType
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
# Scenario Models
|
||||
|
||||
class ScenarioGuild(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
icon: Optional[str] = None
|
||||
owner_id: str
|
||||
roles: List[str] = []
|
||||
channels: List[str] = []
|
||||
|
||||
|
||||
class ScenarioChannel(BaseModel):
|
||||
id: str
|
||||
guild_id: str
|
||||
name: str
|
||||
type: ChannelType = ChannelType.GUILD_TEXT
|
||||
position: int = 0
|
||||
|
||||
|
||||
class ScenarioRole(BaseModel):
|
||||
id: str
|
||||
guild_id: str
|
||||
name: str
|
||||
color: int = 0
|
||||
hoist: bool = False
|
||||
position: int = 0
|
||||
permissions: str = "104324161"
|
||||
managed: bool = False
|
||||
mentionable: bool = False
|
||||
|
||||
|
||||
class ScenarioUser(BaseModel):
|
||||
id: str
|
||||
username: str
|
||||
discriminator: str = "0000"
|
||||
bot: bool = False
|
||||
guild_roles: Dict[str, List[str]] = {}
|
||||
|
||||
|
||||
class ScenarioBot(BaseModel):
|
||||
id: str
|
||||
username: str
|
||||
discriminator: str = "0000"
|
||||
token: Optional[str] = None
|
||||
|
||||
|
||||
class ScenarioData(BaseModel):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
guilds: List[ScenarioGuild] = []
|
||||
channels: List[ScenarioChannel] = []
|
||||
roles: List[ScenarioRole] = []
|
||||
users: List[ScenarioUser] = []
|
||||
bot: Optional[ScenarioBot] = None
|
||||
steps: List[Dict[str, Any]] = []
|
||||
|
||||
|
||||
# REST API Response Models
|
||||
|
||||
class GatewayInfo(BaseModel):
|
||||
url: str
|
||||
shards: int
|
||||
session_start_limit: Dict[str, int] = {
|
||||
"total": 1000,
|
||||
"remaining": 999,
|
||||
"reset_after": 3600000,
|
||||
"max_concurrency": 1
|
||||
}
|
||||
|
||||
|
||||
class RESTError(BaseModel):
|
||||
code: int
|
||||
message: str
|
||||
errors: Optional[Dict[str, Any]] = None
|
||||
@@ -0,0 +1 @@
|
||||
"""REST API Server Package"""
|
||||
Binary file not shown.
@@ -0,0 +1,427 @@
|
||||
"""
|
||||
REST API Server Module
|
||||
|
||||
Implements the Discord REST API endpoints needed for bot operations.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aiohttp import web
|
||||
from aiohttp.web_request import Request
|
||||
from aiohttp.web_response import Response
|
||||
|
||||
from apicord.config import EmulatorConfig
|
||||
from apicord.state.manager import StateManager
|
||||
from apicord.models import (
|
||||
GatewayInfo,
|
||||
RESTError,
|
||||
User,
|
||||
Guild,
|
||||
Channel,
|
||||
Role,
|
||||
Message,
|
||||
Interaction,
|
||||
InteractionResponse,
|
||||
InteractionCallbackType,
|
||||
ComponentType,
|
||||
ButtonStyle,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("apicord.rest")
|
||||
|
||||
|
||||
class RESTServer:
|
||||
"""Discord REST API server implementation."""
|
||||
|
||||
def __init__(self, config: EmulatorConfig, state_manager: StateManager) -> None:
|
||||
self.config = config
|
||||
self.state = state_manager
|
||||
self.app = web.Application()
|
||||
self.runner: Optional[web.AppRunner] = None
|
||||
self.site: Optional[web.TCPSite] = None
|
||||
|
||||
# Setup routes
|
||||
self._setup_routes()
|
||||
|
||||
# Middleware
|
||||
self.app.middlewares.append(self._auth_middleware)
|
||||
self.app.middlewares.append(self._rate_limit_middleware)
|
||||
|
||||
def _setup_routes(self) -> None:
|
||||
"""Setup all REST API routes."""
|
||||
# Gateway
|
||||
self.app.router.add_get("/api/v{version}/gateway", self.gateway)
|
||||
self.app.router.add_get("/api/v{version}/gateway/bot", self.gateway_bot)
|
||||
|
||||
# Auth
|
||||
self.app.router.add_post("/api/v{version}/auth/login", self.auth_login)
|
||||
|
||||
# Users
|
||||
self.app.router.add_get("/api/v{version}/users/@me", self.get_current_user)
|
||||
|
||||
# Guilds
|
||||
self.app.router.add_get("/api/v{version}/guilds", self.list_guilds)
|
||||
self.app.router.add_get("/api/v{version}/guilds/{guild_id}", self.get_guild)
|
||||
self.app.router.add_get("/api/v{version}/guilds/{guild_id}/channels", self.get_guild_channels)
|
||||
self.app.router.add_get("/api/v{version}/guilds/{guild_id}/roles", self.get_guild_roles)
|
||||
self.app.router.add_get("/api/v{version}/guilds/{guild_id}/members", self.list_guild_members)
|
||||
|
||||
# Channels
|
||||
self.app.router.add_get("/api/v{version}/channels/{channel_id}", self.get_channel)
|
||||
self.app.router.add_get("/api/v{version}/channels/{channel_id}/messages", self.get_channel_messages)
|
||||
self.app.router.add_post("/api/v{version}/channels/{channel_id}/messages", self.create_message)
|
||||
self.app.router.add_patch("/api/v{version}/channels/{channel_id}/messages/{message_id}", self.update_message)
|
||||
self.app.router.add_delete("/api/v{version}/channels/{channel_id}/messages/{message_id}", self.delete_message)
|
||||
|
||||
# Interactions
|
||||
self.app.router.add_post(
|
||||
"/api/v{version}/interactions/{interaction_id}/{interaction_token}/callback",
|
||||
self.interaction_callback
|
||||
)
|
||||
|
||||
# Webhooks (for components)
|
||||
self.app.router.add_post("/api/v{version}/webhooks/{webhook_id}/{webhook_token}", self.execute_webhook)
|
||||
|
||||
async def _auth_middleware(self, app: web.Application, handler):
|
||||
"""Authentication middleware - validates bot token for protected routes."""
|
||||
async def middleware(request: Request):
|
||||
# Skip auth for gateway and login endpoints
|
||||
if request.path in [f"/api/v{self.config.api_version}/gateway",
|
||||
f"/api/v{self.config.api_version}/gateway/bot",
|
||||
f"/api/v{self.config.api_version}/auth/login"]:
|
||||
return await handler(request)
|
||||
|
||||
# Check Authorization header
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
if not auth_header.startswith("Bot "):
|
||||
return web.json_response(
|
||||
{"message": "401: Unauthorized", "code": 0},
|
||||
status=401
|
||||
)
|
||||
|
||||
token = auth_header[4:] # Remove "Bot " prefix
|
||||
if token != self.config.bot_token:
|
||||
return web.json_response(
|
||||
{"message": "401: Unauthorized", "code": 0},
|
||||
status=401
|
||||
)
|
||||
|
||||
return await handler(request)
|
||||
return middleware
|
||||
|
||||
async def _rate_limit_middleware(self, app: web.Application, handler):
|
||||
"""Rate limiting middleware (optional)."""
|
||||
if not self.config.enable_rate_limits:
|
||||
return handler
|
||||
|
||||
# Simple in-memory rate limiting
|
||||
from collections import defaultdict
|
||||
import time
|
||||
|
||||
requests = defaultdict(list)
|
||||
|
||||
async def middleware(request: Request):
|
||||
client_ip = request.remote
|
||||
now = time.time()
|
||||
|
||||
# Clean old entries
|
||||
cutoff = now - self.config.rate_limit_window
|
||||
requests[client_ip] = [t for t in requests[client_ip] if t > cutoff]
|
||||
|
||||
if len(requests[client_ip]) >= self.config.rate_limit_requests:
|
||||
retry_after = self.config.rate_limit_window
|
||||
return web.json_response(
|
||||
{"message": "You are being rate limited.", "retry_after": retry_after, "global": False},
|
||||
status=429,
|
||||
headers={"Retry-After": str(int(retry_after))}
|
||||
)
|
||||
|
||||
requests[client_ip].append(now)
|
||||
return await handler(request)
|
||||
|
||||
return middleware
|
||||
|
||||
# --- Gateway Endpoints ---
|
||||
|
||||
async def gateway(self, request: Request) -> Response:
|
||||
"""GET /gateway - Returns the WebSocket gateway URL."""
|
||||
info = GatewayInfo(url=self.config.get_gateway_url())
|
||||
return web.json_response(info.model_dump())
|
||||
|
||||
async def gateway_bot(self, request: Request) -> Response:
|
||||
"""GET /gateway/bot - Returns the WebSocket gateway URL and bot info."""
|
||||
info = GatewayInfo(url=self.config.get_gateway_url())
|
||||
return web.json_response(info.model_dump())
|
||||
|
||||
# --- Auth Endpoints ---
|
||||
|
||||
async def auth_login(self, request: Request) -> Response:
|
||||
"""POST /auth/login - Validates bot token (simplified)."""
|
||||
# In real Discord, this would validate email/password
|
||||
# For emulator, we just return success if token matches
|
||||
try:
|
||||
data = await request.json()
|
||||
except Exception:
|
||||
return web.json_response({"message": "Invalid JSON"}, status=400)
|
||||
|
||||
# Return a fake user for the bot
|
||||
bot_user = self.state.get_bot_user()
|
||||
if bot_user:
|
||||
return web.json_response(bot_user.model_dump(exclude={"token"}))
|
||||
|
||||
return web.json_response(
|
||||
RESTError(code=400, message="Invalid credentials").model_dump(),
|
||||
status=400
|
||||
)
|
||||
|
||||
# --- User Endpoints ---
|
||||
|
||||
async def get_current_user(self, request: Request) -> Response:
|
||||
"""GET /users/@me - Returns the bot user."""
|
||||
bot_user = self.state.get_bot_user()
|
||||
if not bot_user:
|
||||
return web.json_response(
|
||||
RESTError(code=404, message="Bot user not found").model_dump(),
|
||||
status=404
|
||||
)
|
||||
return web.json_response(bot_user.model_dump(exclude={"token"}))
|
||||
|
||||
# --- Guild Endpoints ---
|
||||
|
||||
async def list_guilds(self, request: Request) -> Response:
|
||||
"""GET /guilds - Returns list of guilds the bot is in."""
|
||||
guilds = self.state.list_guilds()
|
||||
return web.json_response([g.model_dump() for g in guilds])
|
||||
|
||||
async def get_guild(self, request: Request) -> Response:
|
||||
"""GET /guilds/{guild_id} - Returns a specific guild."""
|
||||
guild_id = request.match_info["guild_id"]
|
||||
guild = self.state.get_guild(guild_id)
|
||||
if not guild:
|
||||
return web.json_response(
|
||||
RESTError(code=10004, message="Unknown Guild").model_dump(),
|
||||
status=404
|
||||
)
|
||||
return web.json_response(guild.model_dump())
|
||||
|
||||
async def get_guild_channels(self, request: Request) -> Response:
|
||||
"""GET /guilds/{guild_id}/channels - Returns channels in a guild."""
|
||||
guild_id = request.match_info["guild_id"]
|
||||
channels = self.state.get_guild_channels(guild_id)
|
||||
return web.json_response([c.model_dump() for c in channels])
|
||||
|
||||
async def get_guild_roles(self, request: Request) -> Response:
|
||||
"""GET /guilds/{guild_id}/roles - Returns roles in a guild."""
|
||||
guild_id = request.match_info["guild_id"]
|
||||
roles = self.state.get_guild_roles(guild_id)
|
||||
return web.json_response([r.model_dump() for r in roles])
|
||||
|
||||
async def list_guild_members(self, request: Request) -> Response:
|
||||
"""GET /guilds/{guild_id}/members - Returns members of a guild."""
|
||||
guild_id = request.match_info["guild_id"]
|
||||
members = self.state.get_guild_members(guild_id)
|
||||
# Return member objects with roles
|
||||
member_list = []
|
||||
for user in members:
|
||||
member = user.model_dump()
|
||||
member["roles"] = user.guild_roles.get(guild_id, [])
|
||||
member["joined_at"] = "2024-01-01T00:00:00.000000+00:00"
|
||||
member["deaf"] = False
|
||||
member["mute"] = False
|
||||
member["pending"] = False
|
||||
member_list.append(member)
|
||||
return web.json_response(member_list)
|
||||
|
||||
# --- Channel Endpoints ---
|
||||
|
||||
async def get_channel(self, request: Request) -> Response:
|
||||
"""GET /channels/{channel_id} - Returns a channel."""
|
||||
channel_id = request.match_info["channel_id"]
|
||||
channel = self.state.get_channel(channel_id)
|
||||
if not channel:
|
||||
return web.json_response(
|
||||
RESTError(code=10003, message="Unknown Channel").model_dump(),
|
||||
status=404
|
||||
)
|
||||
return web.json_response(channel.model_dump())
|
||||
|
||||
async def get_channel_messages(self, request: Request) -> Response:
|
||||
"""GET /channels/{channel_id}/messages - Returns messages in a channel."""
|
||||
channel_id = request.match_info["channel_id"]
|
||||
limit = int(request.query.get("limit", 50))
|
||||
before = request.query.get("before")
|
||||
after = request.query.get("after")
|
||||
around = request.query.get("around")
|
||||
|
||||
messages = self.state.get_channel_messages(channel_id, limit=limit)
|
||||
return web.json_response([m.model_dump() for m in messages])
|
||||
|
||||
async def create_message(self, request: Request) -> Response:
|
||||
"""POST /channels/{channel_id}/messages - Creates a message (with embeds, components)."""
|
||||
channel_id = request.match_info["channel_id"]
|
||||
|
||||
# Handle multipart/form-data (for files) or JSON
|
||||
content_type = request.content_type or ""
|
||||
if "multipart/form-data" in content_type:
|
||||
data = await request.post()
|
||||
# Parse JSON from form fields
|
||||
payload = {}
|
||||
for key, value in data.items():
|
||||
if key == "payload_json":
|
||||
import json
|
||||
payload = json.loads(value)
|
||||
else:
|
||||
payload[key] = value
|
||||
else:
|
||||
payload = await request.json()
|
||||
|
||||
# Create message object
|
||||
from datetime import datetime
|
||||
message = Message(
|
||||
id=str(int(channel_id) + len(self.state.messages) + 1),
|
||||
channel_id=channel_id,
|
||||
author=self.state.get_bot_user() or User(
|
||||
id=self.config.bot_id,
|
||||
username=self.config.bot_username,
|
||||
discriminator=self.config.bot_discriminator,
|
||||
bot=True
|
||||
),
|
||||
content=payload.get("content", ""),
|
||||
timestamp=datetime.utcnow().isoformat() + "Z",
|
||||
embeds=payload.get("embeds", []),
|
||||
components=payload.get("components", []),
|
||||
flags=payload.get("flags", 0),
|
||||
)
|
||||
|
||||
self.state.add_message(message)
|
||||
logger.info(f"Created message {message.id} in channel {channel_id}")
|
||||
|
||||
return web.json_response(message.model_dump(), status=200)
|
||||
|
||||
async def update_message(self, request: Request) -> Response:
|
||||
"""PATCH /channels/{channel_id}/messages/{message_id} - Updates a message."""
|
||||
channel_id = request.match_info["channel_id"]
|
||||
message_id = request.match_info["message_id"]
|
||||
|
||||
payload = await request.json()
|
||||
|
||||
message = self.state.get_message(message_id)
|
||||
if not message or message.channel_id != channel_id:
|
||||
return web.json_response(
|
||||
RESTError(code=10008, message="Unknown Message").model_dump(),
|
||||
status=404
|
||||
)
|
||||
|
||||
# Update fields
|
||||
if "content" in payload:
|
||||
message.content = payload["content"]
|
||||
if "embeds" in payload:
|
||||
message.embeds = payload["embeds"]
|
||||
if "components" in payload:
|
||||
message.components = payload["components"]
|
||||
if "flags" in payload:
|
||||
message.flags = payload["flags"]
|
||||
|
||||
from datetime import datetime
|
||||
message.edited_timestamp = datetime.utcnow().isoformat() + "Z"
|
||||
|
||||
self.state.update_message(message)
|
||||
logger.info(f"Updated message {message_id} in channel {channel_id}")
|
||||
|
||||
return web.json_response(message.model_dump())
|
||||
|
||||
async def delete_message(self, request: Request) -> Response:
|
||||
"""DELETE /channels/{channel_id}/messages/{message_id} - Deletes a message."""
|
||||
channel_id = request.match_info["channel_id"]
|
||||
message_id = request.match_info["message_id"]
|
||||
|
||||
message = self.state.get_message(message_id)
|
||||
if not message or message.channel_id != channel_id:
|
||||
return web.json_response(
|
||||
RESTError(code=10008, message="Unknown Message").model_dump(),
|
||||
status=404
|
||||
)
|
||||
|
||||
self.state.delete_message(message_id)
|
||||
logger.info(f"Deleted message {message_id} from channel {channel_id}")
|
||||
|
||||
return web.Response(status=204)
|
||||
|
||||
# --- Interaction Endpoints ---
|
||||
|
||||
async def interaction_callback(self, request: Request) -> Response:
|
||||
"""POST /interactions/{interaction_id}/{interaction_token}/callback - Responds to an interaction."""
|
||||
interaction_id = request.match_info["interaction_id"]
|
||||
interaction_token = request.match_info["interaction_token"]
|
||||
|
||||
payload = await request.json()
|
||||
response_type = payload.get("type", InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE)
|
||||
|
||||
interaction = self.state.get_interaction(interaction_id)
|
||||
if not interaction or interaction.token != interaction_token:
|
||||
return web.json_response(
|
||||
RESTError(code=10062, message="Unknown interaction").model_dump(),
|
||||
status=404
|
||||
)
|
||||
|
||||
# Mark interaction as responded
|
||||
interaction.responded = True
|
||||
|
||||
# Store the response for the test framework
|
||||
interaction.response = InteractionResponse(type=response_type, data=payload.get("data"))
|
||||
|
||||
logger.info(f"Interaction {interaction_id} responded with type {response_type}")
|
||||
|
||||
return web.json_response({})
|
||||
|
||||
# --- Webhook Endpoints (for components) ---
|
||||
|
||||
async def execute_webhook(self, request: Request) -> Response:
|
||||
"""POST /webhooks/{webhook_id}/{webhook_token} - Executes a webhook (used for components)."""
|
||||
webhook_id = request.match_info["webhook_id"]
|
||||
webhook_token = request.match_info["webhook_token"]
|
||||
|
||||
payload = await request.json()
|
||||
|
||||
# This is used for responding to component interactions (buttons, selects)
|
||||
# Create a followup message
|
||||
from datetime import datetime
|
||||
message = Message(
|
||||
id=str(int(webhook_id) + len(self.state.messages) + 1),
|
||||
channel_id=payload.get("channel_id", "0"),
|
||||
author=self.state.get_bot_user() or User(
|
||||
id=self.config.bot_id,
|
||||
username=self.config.bot_username,
|
||||
discriminator=self.config.bot_discriminator,
|
||||
bot=True
|
||||
),
|
||||
content=payload.get("content", ""),
|
||||
timestamp=datetime.utcnow().isoformat() + "Z",
|
||||
embeds=payload.get("embeds", []),
|
||||
components=payload.get("components", []),
|
||||
flags=payload.get("flags", 0),
|
||||
)
|
||||
|
||||
self.state.add_message(message)
|
||||
logger.info(f"Webhook executed, created message {message.id}")
|
||||
|
||||
return web.json_response(message.model_dump())
|
||||
|
||||
# --- Server Lifecycle ---
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Start the REST server."""
|
||||
self.runner = web.AppRunner(self.app)
|
||||
await self.runner.setup()
|
||||
self.site = web.TCPSite(self.runner, self.config.host, self.config.rest_port)
|
||||
await self.site.start()
|
||||
logger.info(f"REST server started on http://{self.config.host}:{self.config.rest_port}")
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Stop the REST server."""
|
||||
if self.site:
|
||||
await self.site.stop()
|
||||
if self.runner:
|
||||
await self.runner.cleanup()
|
||||
logger.info("REST server stopped")
|
||||
@@ -0,0 +1 @@
|
||||
"""State Management Package"""
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,355 @@
|
||||
"""
|
||||
State Management Module
|
||||
|
||||
Central state management for the emulator, handling guilds, channels, users, messages, and interactions.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from apicord.config import EmulatorConfig
|
||||
from apicord.models import (
|
||||
Guild,
|
||||
Channel,
|
||||
User,
|
||||
Role,
|
||||
Message,
|
||||
Interaction,
|
||||
BotUser,
|
||||
ScenarioData,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("apicord")
|
||||
|
||||
|
||||
class StateManager:
|
||||
"""Manages the emulator's state including guilds, channels, users, and messages."""
|
||||
|
||||
def __init__(self, config: EmulatorConfig) -> None:
|
||||
self.config = config
|
||||
self.guilds: Dict[str, Guild] = {}
|
||||
self.channels: Dict[str, Channel] = {}
|
||||
self.users: Dict[str, User] = {}
|
||||
self.roles: Dict[str, Role] = {}
|
||||
self.messages: Dict[str, Message] = {}
|
||||
self.interactions: Dict[str, Interaction] = {}
|
||||
self.bot_user: Optional[BotUser] = None
|
||||
|
||||
# Initialize bot user
|
||||
self._init_bot_user()
|
||||
|
||||
def _init_bot_user(self) -> None:
|
||||
"""Initialize the bot user."""
|
||||
self.bot_user = BotUser(
|
||||
id=self.config.bot_id,
|
||||
username=self.config.bot_username,
|
||||
discriminator=self.config.bot_discriminator,
|
||||
bot=True,
|
||||
)
|
||||
self.users[self.config.bot_id] = self.bot_user
|
||||
logger.debug(f"Initialized bot user: {self.bot_user.username}#{self.bot_user.discriminator} ({self.bot_user.id})")
|
||||
|
||||
async def create_default_state(
|
||||
self,
|
||||
guilds: int = 1,
|
||||
channels_per_guild: int = 3,
|
||||
users: int = 5,
|
||||
) -> None:
|
||||
"""Create a default test state with guilds, channels, and users."""
|
||||
logger.info(f"Creating default state: {guilds} guilds, {channels_per_guild} channels/guild, {users} users")
|
||||
|
||||
# Create guilds
|
||||
for i in range(guilds):
|
||||
guild_id = str(100000000000000000 + i * 1000)
|
||||
guild = Guild(
|
||||
id=guild_id,
|
||||
name=f"Test Guild {i + 1}",
|
||||
icon=None,
|
||||
owner_id="111111111111111111",
|
||||
roles=[],
|
||||
)
|
||||
self.guilds[guild_id] = guild
|
||||
|
||||
# Create default role @everyone
|
||||
everyone_role = Role(
|
||||
id=f"{guild_id}0",
|
||||
name="@everyone",
|
||||
color=0,
|
||||
hoist=False,
|
||||
position=0,
|
||||
permissions="104324161", # Basic permissions
|
||||
managed=False,
|
||||
mentionable=False,
|
||||
)
|
||||
self.roles[everyone_role.id] = everyone_role
|
||||
guild.roles.append(everyone_role.id)
|
||||
|
||||
# Create "Game Server User" role
|
||||
gsu_role = Role(
|
||||
id=f"{guild_id}1",
|
||||
name="Game Server User",
|
||||
color=3447003, # Blue
|
||||
hoist=True,
|
||||
position=1,
|
||||
permissions="104324161",
|
||||
managed=False,
|
||||
mentionable=True,
|
||||
)
|
||||
self.roles[gsu_role.id] = gsu_role
|
||||
guild.roles.append(gsu_role.id)
|
||||
|
||||
# Create channels
|
||||
channel_types = [
|
||||
("general", 0), # GUILD_TEXT
|
||||
("bot-commands", 0),
|
||||
("voice-chat", 2), # GUILD_VOICE
|
||||
]
|
||||
for j in range(min(channels_per_guild, len(channel_types))):
|
||||
channel_name, channel_type = channel_types[j]
|
||||
channel_id = f"{guild_id}{j + 10}"
|
||||
channel = Channel(
|
||||
id=channel_id,
|
||||
guild_id=guild_id,
|
||||
name=channel_name,
|
||||
type=channel_type,
|
||||
position=j,
|
||||
)
|
||||
self.channels[channel_id] = channel
|
||||
guild.channels.append(channel_id)
|
||||
|
||||
# Create test users
|
||||
for i in range(users):
|
||||
user_id = str(200000000000000000 + i * 1000)
|
||||
user = User(
|
||||
id=user_id,
|
||||
username=f"TestUser{i + 1}",
|
||||
discriminator=f"{1000 + i}",
|
||||
bot=False,
|
||||
)
|
||||
self.users[user_id] = user
|
||||
|
||||
# Add first user to first guild with Game Server User role
|
||||
if i == 0 and guilds > 0:
|
||||
first_guild_id = list(self.guilds.keys())[0]
|
||||
gsu_role_id = f"{first_guild_id}1"
|
||||
if gsu_role_id in self.roles:
|
||||
# Add role to user in that guild
|
||||
if first_guild_id not in user.guild_roles:
|
||||
user.guild_roles[first_guild_id] = []
|
||||
user.guild_roles[first_guild_id].append(gsu_role_id)
|
||||
|
||||
logger.info(f"Created {len(self.guilds)} guilds, {len(self.channels)} channels, {len(self.users)} users")
|
||||
|
||||
async def load_scenario(self, scenario_data: dict) -> None:
|
||||
"""Load state from a scenario definition."""
|
||||
logger.info("Loading scenario state")
|
||||
|
||||
# Parse scenario using Pydantic model
|
||||
scenario = ScenarioData(**scenario_data)
|
||||
|
||||
# Clear existing state
|
||||
self.guilds.clear()
|
||||
self.channels.clear()
|
||||
self.users.clear()
|
||||
self.roles.clear()
|
||||
self.messages.clear()
|
||||
self.interactions.clear()
|
||||
|
||||
# Re-initialize bot user
|
||||
self._init_bot_user()
|
||||
|
||||
# Load guilds
|
||||
for guild_data in scenario.guilds:
|
||||
guild = Guild(**guild_data.model_dump())
|
||||
self.guilds[guild.id] = guild
|
||||
|
||||
# Load channels
|
||||
for channel_data in scenario.channels:
|
||||
channel = Channel(**channel_data.model_dump())
|
||||
self.channels[channel.id] = channel
|
||||
# Add to guild's channel list
|
||||
if channel.guild_id in self.guilds:
|
||||
self.guilds[channel.guild_id].channels.append(channel.id)
|
||||
|
||||
# Load roles
|
||||
for role_data in scenario.roles:
|
||||
role = Role(**role_data.model_dump())
|
||||
self.roles[role.id] = role
|
||||
if role.guild_id in self.guilds:
|
||||
self.guilds[role.guild_id].roles.append(role.id)
|
||||
|
||||
# Load users
|
||||
for user_data in scenario.users:
|
||||
user = User(**user_data.model_dump())
|
||||
self.users[user.id] = user
|
||||
|
||||
# Load bot if specified
|
||||
if scenario.bot:
|
||||
self.bot_user = BotUser(**scenario.bot.model_dump())
|
||||
self.users[self.bot_user.id] = self.bot_user
|
||||
# Update config token if provided
|
||||
if scenario.bot.token:
|
||||
self.config.bot_token = scenario.bot.token
|
||||
|
||||
logger.info(f"Loaded scenario: {len(self.guilds)} guilds, {len(self.channels)} channels, {len(self.users)} users")
|
||||
|
||||
async def save_state(self) -> None:
|
||||
"""Save current state to disk."""
|
||||
if not self.config.persist_state:
|
||||
return
|
||||
|
||||
state = {
|
||||
"guilds": {k: v.model_dump() for k, v in self.guilds.items()},
|
||||
"channels": {k: v.model_dump() for k, v in self.channels.items()},
|
||||
"users": {k: v.model_dump() for k, v in self.users.items()},
|
||||
"roles": {k: v.model_dump() for k, v in self.roles.items()},
|
||||
"messages": {k: v.model_dump() for k, v in self.messages.items()},
|
||||
"interactions": {k: v.model_dump() for k, v in self.interactions.items()},
|
||||
"bot_user": self.bot_user.model_dump() if self.bot_user else None,
|
||||
}
|
||||
|
||||
try:
|
||||
with open(self.config.state_file, "w") as f:
|
||||
json.dump(state, f, indent=2)
|
||||
logger.debug(f"State saved to {self.config.state_file}")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to save state: {e}")
|
||||
|
||||
async def load_state(self) -> bool:
|
||||
"""Load state from disk. Returns True if successful."""
|
||||
if not self.config.persist_state:
|
||||
return False
|
||||
|
||||
state_file = Path(self.config.state_file)
|
||||
if not state_file.exists():
|
||||
return False
|
||||
|
||||
try:
|
||||
with open(state_file) as f:
|
||||
state = json.load(f)
|
||||
|
||||
self.guilds = {k: Guild(**v) for k, v in state.get("guilds", {}).items()}
|
||||
self.channels = {k: Channel(**v) for k, v in state.get("channels", {}).items()}
|
||||
self.users = {k: User(**v) for k, v in state.get("users", {}).items()}
|
||||
self.roles = {k: Role(**v) for k, v in state.get("roles", {}).items()}
|
||||
self.messages = {k: Message(**v) for k, v in state.get("messages", {}).items()}
|
||||
self.interactions = {k: Interaction(**v) for k, v in state.get("interactions", {}).items()}
|
||||
|
||||
if state.get("bot_user"):
|
||||
self.bot_user = BotUser(**state["bot_user"])
|
||||
self.users[self.bot_user.id] = self.bot_user
|
||||
|
||||
logger.info(f"Loaded state from {state_file}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load state: {e}")
|
||||
return False
|
||||
|
||||
# --- Getters ---
|
||||
|
||||
def get_guild(self, guild_id: str) -> Optional[Guild]:
|
||||
return self.guilds.get(guild_id)
|
||||
|
||||
def get_channel(self, channel_id: str) -> Optional[Channel]:
|
||||
return self.channels.get(channel_id)
|
||||
|
||||
def get_user(self, user_id: str) -> Optional[User]:
|
||||
return self.users.get(user_id)
|
||||
|
||||
def get_role(self, role_id: str) -> Optional[Role]:
|
||||
return self.roles.get(role_id)
|
||||
|
||||
def get_message(self, message_id: str) -> Optional[Message]:
|
||||
return self.messages.get(message_id)
|
||||
|
||||
def get_interaction(self, interaction_id: str) -> Optional[Interaction]:
|
||||
return self.interactions.get(interaction_id)
|
||||
|
||||
def get_bot_user(self) -> Optional[BotUser]:
|
||||
return self.bot_user
|
||||
|
||||
# --- Guild operations ---
|
||||
|
||||
def list_guilds(self) -> List[Guild]:
|
||||
return list(self.guilds.values())
|
||||
|
||||
def get_guild_channels(self, guild_id: str) -> List[Channel]:
|
||||
guild = self.guilds.get(guild_id)
|
||||
if not guild:
|
||||
return []
|
||||
return [self.channels[cid] for cid in guild.channels if cid in self.channels]
|
||||
|
||||
def get_guild_roles(self, guild_id: str) -> List[Role]:
|
||||
guild = self.guilds.get(guild_id)
|
||||
if not guild:
|
||||
return []
|
||||
return [self.roles[rid] for rid in guild.roles if rid in self.roles]
|
||||
|
||||
def get_guild_members(self, guild_id: str) -> List[User]:
|
||||
"""Get users who have roles in this guild."""
|
||||
members = []
|
||||
for user in self.users.values():
|
||||
if guild_id in user.guild_roles:
|
||||
members.append(user)
|
||||
return members
|
||||
|
||||
# --- Channel operations ---
|
||||
|
||||
def get_channel_messages(self, channel_id: str, limit: int = 50) -> List[Message]:
|
||||
channel = self.channels.get(channel_id)
|
||||
if not channel:
|
||||
return []
|
||||
msg_ids = channel.message_ids[-limit:]
|
||||
return [self.messages[mid] for mid in msg_ids if mid in self.messages]
|
||||
|
||||
# --- Message operations ---
|
||||
|
||||
def add_message(self, message: Message) -> None:
|
||||
self.messages[message.id] = message
|
||||
# Add to channel's message list
|
||||
if message.channel_id in self.channels:
|
||||
channel = self.channels[message.channel_id]
|
||||
channel.message_ids.append(message.id)
|
||||
|
||||
def update_message(self, message: Message) -> bool:
|
||||
if message.id in self.messages:
|
||||
self.messages[message.id] = message
|
||||
return True
|
||||
return False
|
||||
|
||||
def delete_message(self, message_id: str) -> bool:
|
||||
if message_id in self.messages:
|
||||
message = self.messages[message_id]
|
||||
# Remove from channel
|
||||
if message.channel_id in self.channels:
|
||||
channel = self.channels[message.channel_id]
|
||||
if message_id in channel.message_ids:
|
||||
channel.message_ids.remove(message_id)
|
||||
del self.messages[message_id]
|
||||
return True
|
||||
return False
|
||||
|
||||
# --- Interaction operations ---
|
||||
|
||||
def add_interaction(self, interaction: Interaction) -> None:
|
||||
self.interactions[interaction.id] = interaction
|
||||
|
||||
def get_pending_interactions(self, user_id: str) -> List[Interaction]:
|
||||
return [
|
||||
i for i in self.interactions.values()
|
||||
if i.user_id == user_id and not i.responded
|
||||
]
|
||||
|
||||
# --- Utility ---
|
||||
|
||||
def get_state_summary(self) -> dict:
|
||||
return {
|
||||
"guilds": len(self.guilds),
|
||||
"channels": len(self.channels),
|
||||
"users": len(self.users),
|
||||
"roles": len(self.roles),
|
||||
"messages": len(self.messages),
|
||||
"interactions": len(self.interactions),
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,144 @@
|
||||
"""Tests for Pydantic Models"""
|
||||
|
||||
import pytest
|
||||
from apicord.models.discord import (
|
||||
User,
|
||||
BotUser,
|
||||
Role,
|
||||
Channel,
|
||||
ChannelType,
|
||||
Guild,
|
||||
Message,
|
||||
Interaction,
|
||||
InteractionType,
|
||||
Snowflake,
|
||||
)
|
||||
|
||||
|
||||
class TestSnowflake:
|
||||
def test_snowflake_from_string(self):
|
||||
sf = Snowflake("123456789012345678")
|
||||
assert sf == "123456789012345678"
|
||||
|
||||
def test_snowflake_from_int(self):
|
||||
sf = Snowflake(123456789012345678)
|
||||
assert sf == "123456789012345678"
|
||||
|
||||
def test_snowflake_invalid(self):
|
||||
with pytest.raises(ValueError):
|
||||
Snowflake.validate("invalid", None)
|
||||
|
||||
|
||||
class TestUser:
|
||||
def test_user_creation(self):
|
||||
user = User(
|
||||
id="123456789012345678",
|
||||
username="TestUser",
|
||||
discriminator="1234",
|
||||
bot=False,
|
||||
)
|
||||
assert user.id == "123456789012345678"
|
||||
assert user.username == "TestUser"
|
||||
assert user.discriminator == "1234"
|
||||
assert user.bot is False
|
||||
|
||||
def test_user_with_guild_roles(self):
|
||||
user = User(
|
||||
id="123456789012345678",
|
||||
username="TestUser",
|
||||
discriminator="1234",
|
||||
guild_roles={"111111111111111111": ["222222222222222222"]},
|
||||
)
|
||||
assert "111111111111111111" in user.guild_roles
|
||||
assert "222222222222222222" in user.guild_roles["111111111111111111"]
|
||||
|
||||
|
||||
class TestBotUser:
|
||||
def test_bot_user_creation(self):
|
||||
bot = BotUser(
|
||||
id="444444444444444444",
|
||||
username="TestBot",
|
||||
discriminator="0000",
|
||||
token="test_token_123",
|
||||
)
|
||||
assert bot.id == "444444444444444444"
|
||||
assert bot.bot is True
|
||||
assert bot.token == "test_token_123"
|
||||
|
||||
|
||||
class TestRole:
|
||||
def test_role_creation(self):
|
||||
role = Role(
|
||||
id="222222222222222222",
|
||||
name="Game Server User",
|
||||
color=3447003,
|
||||
permissions="104324161",
|
||||
)
|
||||
assert role.name == "Game Server User"
|
||||
assert role.color == 3447003
|
||||
|
||||
|
||||
class TestChannel:
|
||||
def test_text_channel(self):
|
||||
channel = Channel(
|
||||
id="111111111111111111",
|
||||
type=ChannelType.GUILD_TEXT,
|
||||
guild_id="123456789012345678",
|
||||
name="general",
|
||||
)
|
||||
assert channel.type == ChannelType.GUILD_TEXT
|
||||
assert channel.guild_id == "123456789012345678"
|
||||
assert channel.name == "general"
|
||||
|
||||
def test_voice_channel(self):
|
||||
channel = Channel(
|
||||
id="111111111111111112",
|
||||
type=ChannelType.GUILD_VOICE,
|
||||
guild_id="123456789012345678",
|
||||
name="voice-chat",
|
||||
)
|
||||
assert channel.type == ChannelType.GUILD_VOICE
|
||||
|
||||
|
||||
class TestGuild:
|
||||
def test_guild_creation(self):
|
||||
guild = Guild(
|
||||
id="123456789012345678",
|
||||
name="Test Guild",
|
||||
owner_id="111111111111111111",
|
||||
)
|
||||
assert guild.name == "Test Guild"
|
||||
assert guild.owner_id == "111111111111111111"
|
||||
assert guild.roles == []
|
||||
assert guild.channels == []
|
||||
|
||||
|
||||
class TestMessage:
|
||||
def test_message_creation(self):
|
||||
user = User(
|
||||
id="123456789012345678",
|
||||
username="TestUser",
|
||||
discriminator="1234",
|
||||
)
|
||||
message = Message(
|
||||
id="999999999999999999",
|
||||
channel_id="111111111111111111",
|
||||
author=user,
|
||||
content="Hello, world!",
|
||||
timestamp="2024-01-01T00:00:00.000000+00:00",
|
||||
)
|
||||
assert message.content == "Hello, world!"
|
||||
assert message.author.username == "TestUser"
|
||||
|
||||
|
||||
class TestInteraction:
|
||||
def test_interaction_creation(self):
|
||||
interaction = Interaction(
|
||||
id="888888888888888888",
|
||||
type=InteractionType.APPLICATION_COMMAND,
|
||||
application_id="444444444444444444",
|
||||
token="interaction_token_123",
|
||||
)
|
||||
assert interaction.type == InteractionType.APPLICATION_COMMAND
|
||||
assert interaction.token == "interaction_token_123"
|
||||
assert interaction.responded is False
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Tests for State Manager"""
|
||||
|
||||
import pytest
|
||||
from apicord.config import EmulatorConfig
|
||||
from apicord.state.manager import StateManager
|
||||
from apicord.models.discord import User, Role, Channel, ChannelType, Guild
|
||||
|
||||
|
||||
class TestStateManager:
|
||||
@pytest.fixture
|
||||
def config(self):
|
||||
return EmulatorConfig(
|
||||
bot_token="test_token_123",
|
||||
bot_id="444444444444444444",
|
||||
persist_state=False,
|
||||
)
|
||||
|
||||
@pytest.fixture
|
||||
async def state_manager(self, config):
|
||||
manager = StateManager(config)
|
||||
await manager.create_default_state(guilds=1, channels_per_guild=2, users=3)
|
||||
return manager
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_default_state(self, state_manager):
|
||||
assert len(state_manager.guilds) == 1
|
||||
assert len(state_manager.channels) == 2
|
||||
assert len(state_manager.users) == 4 # 3 test users + bot
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bot_user_created(self, state_manager):
|
||||
bot = state_manager.get_bot_user()
|
||||
assert bot is not None
|
||||
assert bot.id == "444444444444444444"
|
||||
assert bot.username == "TestBot"
|
||||
assert bot.bot is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_guild(self, state_manager):
|
||||
guild = state_manager.get_guild(list(state_manager.guilds.keys())[0])
|
||||
assert guild is not None
|
||||
assert isinstance(guild, Guild)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_channel(self, state_manager):
|
||||
channel = state_manager.get_channel(list(state_manager.channels.keys())[0])
|
||||
assert channel is not None
|
||||
assert isinstance(channel, Channel)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_user(self, state_manager):
|
||||
user = state_manager.get_user(list(state_manager.users.keys())[0])
|
||||
assert user is not None
|
||||
assert isinstance(user, User)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_message(self, state_manager):
|
||||
from apicord.models.discord import Message
|
||||
from datetime import datetime
|
||||
|
||||
channel_id = list(state_manager.channels.keys())[0]
|
||||
message = Message(
|
||||
id="999999999999999999",
|
||||
channel_id=channel_id,
|
||||
author=state_manager.get_bot_user(),
|
||||
content="Test message",
|
||||
timestamp=datetime.utcnow().isoformat() + "Z",
|
||||
)
|
||||
state_manager.add_message(message)
|
||||
|
||||
retrieved = state_manager.get_message(message.id)
|
||||
assert retrieved is not None
|
||||
assert retrieved.content == "Test message"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_state_summary(self, state_manager):
|
||||
summary = state_manager.get_state_summary()
|
||||
assert "guilds" in summary
|
||||
assert "channels" in summary
|
||||
assert "users" in summary
|
||||
assert summary["guilds"] == 1
|
||||
assert summary["channels"] == 2
|
||||
assert summary["users"] == 4 # 3 + bot
|
||||
Reference in new issue
Block a user