├── .github ├── CODEOWNERS ├── linters │ └── .python-black └── workflows │ ├── analyze.yml │ ├── build.yml │ ├── deploy.yml │ ├── lint.yml │ ├── release.yml │ └── stale.yml ├── .gitignore ├── .readthedocs.yaml ├── LICENSE ├── README.rst ├── discord └── ext │ └── ipc │ ├── __init__.py │ ├── client.py │ ├── errors.py │ └── server.py ├── docs ├── Makefile ├── conf.py ├── index.rst └── modules │ ├── client.rst │ ├── errors.rst │ ├── examples.rst │ └── server.rst ├── examples ├── basic-ipc │ ├── bot.py │ └── webserver.py └── cog_based_ipc │ ├── bot.py │ ├── cogs │ └── ipc.py │ └── webserver.py ├── requirements.txt └── setup.py /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @Ext-Creators/ext-ipc 2 | /.github/workflows/ @ShineyDev 3 | /docs/ @Ext-Creators/documentation 4 | -------------------------------------------------------------------------------- /.github/linters/.python-black: -------------------------------------------------------------------------------- 1 | [tool.black] 2 | line-length = 100 3 | -------------------------------------------------------------------------------- /.github/workflows/analyze.yml: -------------------------------------------------------------------------------- 1 | name: Analyze 2 | 3 | on: 4 | pull_request: 5 | push: 6 | schedule: 7 | - cron: "0 0 * * 0" 8 | 9 | jobs: 10 | job: 11 | name: Analyze 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v2 17 | 18 | - name: Init CodeQL 19 | uses: github/codeql-action/init@v1 20 | 21 | - name: Analyze 22 | uses: github/codeql-action/analyze@v1 23 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: [pull_request, push] 4 | 5 | jobs: 6 | job: 7 | strategy: 8 | fail-fast: false 9 | matrix: 10 | python-version: [3.6, 3.7, 3.8, 3.9] 11 | 12 | name: Build 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - name: Checkout 17 | uses: actions/checkout@v2 18 | 19 | - name: Set up Python ${{ matrix.python-version }} 20 | uses: actions/setup-python@v2 21 | with: 22 | python-version: ${{ matrix.python-version }} 23 | 24 | - name: Install dependencies 25 | run: |- 26 | python -m pip install --upgrade pip 27 | python -m pip install --upgrade setuptools wheel 28 | 29 | - name: Build 30 | run: python setup.py sdist bdist_wheel 31 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy 2 | 3 | on: 4 | push: 5 | release: 6 | types: [ released ] 7 | 8 | jobs: 9 | job: 10 | name: Deploy 11 | runs-on: ubuntu-latest 12 | 13 | env: 14 | AUTH_EMAIL: 30989490+ShineyDev@users.noreply.github.com 15 | AUTH_LOGIN: ShineyDev 16 | AUTH_TOKEN: ${{ secrets.DOCS_TOKEN }} 17 | 18 | COMMIT_MESSAGE: update docs for ${{ github.repository }} 19 | 20 | PULL_INSTALL: .[docs] 21 | PULL_PATH: docs 22 | 23 | PUSH_REPOSITORY: ${{ github.repository_owner }}/docs 24 | PUSH_ROOT_PATH: "`x=${{ github.event.repository.name }}; echo ${x#discord-ext-}`" 25 | PUSH_LATEST_PATH: latest 26 | PUSH_STABLE_PATH: stable 27 | 28 | PYTHON_VERSION: 3.9 29 | SPHINX_OPTIONS: -b dirhtml -a -E -n -T -W --keep-going 30 | 31 | steps: 32 | - name: Checkout ${{ github.repository }} 33 | uses: actions/checkout@v2 34 | with: 35 | path: ${{ github.event.repository.name }} 36 | 37 | - name: Checkout ${{ env.PUSH_REPOSITORY }} 38 | uses: actions/checkout@v2 39 | with: 40 | path: docs 41 | repository: ${{ env.PUSH_REPOSITORY }} 42 | token: ${{ env.AUTH_TOKEN }} 43 | 44 | - name: Set up Python ${{ env.PYTHON_VERSION }} 45 | uses: actions/setup-python@v2 46 | with: 47 | python-version: ${{ env.PYTHON_VERSION }} 48 | 49 | - name: Install 50 | working-directory: ./${{ github.event.repository.name }} 51 | run: | 52 | python -m pip install --upgrade pip 53 | python -m pip install --upgrade ${{ env.PULL_INSTALL }} 54 | - name: Build 55 | if: ${{ github.event_name == 'push' }} 56 | run: | 57 | if [ -d ./docs/${{ env.PUSH_ROOT_PATH }}/${{ env.PUSH_LATEST_PATH }} ]; then rm -r ./docs/${{ env.PUSH_ROOT_PATH }}/${{ env.PUSH_LATEST_PATH }}; fi 58 | python -m sphinx ${{ env.SPHINX_OPTIONS }} ./${{ github.event.repository.name }}/${{ env.PULL_PATH }} ./docs/${{ env.PUSH_ROOT_PATH }}/${{ env.PUSH_LATEST_PATH }} 59 | x=${{ env.PUSH_ROOT_PATH }}/${{ env.PUSH_LATEST_PATH }}; y=$x; while [ $y != ${y%/*} ]; do y=${y%/*}; echo '' > ./docs/$y/index.html; done 60 | if [ ! -f ./docs/index.json ]; then echo {} > ./docs/index.json ; fi 61 | jq 'if has("'"${{ env.PUSH_ROOT_PATH }}"'") then (.'"${{ env.PUSH_ROOT_PATH }}"'.latest = "${{ env.PUSH_LATEST_PATH }}" | .'"${{ env.PUSH_ROOT_PATH }}"'.stable = "${{ env.PUSH_STABLE_PATH }}") else (.'"${{ env.PUSH_ROOT_PATH }}"' = {latest: "${{ env.PUSH_LATEST_PATH }}", stable: "${{ env.PUSH_STABLE_PATH }}", tags: []}) end' ./docs/index.json > ./docs/temp.json 62 | mv ./docs/temp.json ./docs/index.json 63 | - name: Build 64 | if: ${{ github.event_name == 'release' }} 65 | run: | 66 | if [ -d ./docs/${{ env.PUSH_ROOT_PATH }}/${{ github.event.release.tag_name }} ]; then rm -r ./docs/${{ env.PUSH_ROOT_PATH }}/${{ github.event.release.tag_name }}; fi 67 | python -m sphinx ${{ env.SPHINX_OPTIONS }} ./${{ github.event.repository.name }}/${{ env.PULL_PATH }} ./docs/${{ env.PUSH_ROOT_PATH }}/${{ github.event.release.tag_name }} 68 | if [ -h ./docs/${{ env.PUSH_ROOT_PATH }}/${{ env.PUSH_STABLE_PATH }} ]; then rm ./docs/${{ env.PUSH_ROOT_PATH }}/${{ env.PUSH_STABLE_PATH }}; fi 69 | ln -s ${{ github.event.release.tag_name }} ./docs/${{ env.PUSH_ROOT_PATH }}/${{ env.PUSH_STABLE_PATH }} 70 | if [ ! -f ./docs/index.json ]; then echo {} > ./docs/index.json ; fi 71 | jq 'if has("'"${{ env.PUSH_ROOT_PATH }}"'") then (.'"${{ env.PUSH_ROOT_PATH }}"'.latest = "${{ env.PUSH_LATEST_PATH }}" | .'"${{ env.PUSH_ROOT_PATH }}"'.stable = "${{ env.PUSH_STABLE_PATH }}" | .'"${{ env.PUSH_ROOT_PATH }}"'.tags |= . + ["${{ github.event.release.tag_name }}"]) else (.'"${{ env.PUSH_ROOT_PATH }}"' = {latest: "${{ env.PUSH_LATEST_PATH }}", stable: "${{ env.PUSH_STABLE_PATH }}", tags: ["${{ github.event.release.tag_name }}"]}) end' ./docs/index.json > ./docs/temp.json 72 | mv ./docs/temp.json ./docs/index.json 73 | - name: Push 74 | continue-on-error: true 75 | working-directory: docs 76 | run: | 77 | git config user.name ${{ env.AUTH_LOGIN }} 78 | git config user.email ${{ env.AUTH_EMAIL }} 79 | git add . 80 | git commit -m "${{ env.COMMIT_MESSAGE }}" 81 | git push 82 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: [pull_request, push] 4 | 5 | jobs: 6 | job: 7 | name: Lint 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v2 13 | 14 | - name: Lint 15 | uses: github/super-linter@v3 16 | env: 17 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 18 | VALIDATE_PYTHON_BLACK: true 19 | VALIDATE_YAML: true 20 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | release: 5 | types: [released] 6 | 7 | jobs: 8 | job: 9 | name: Upload 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v2 15 | 16 | - name: Set up Python 3.9 17 | uses: actions/setup-python@v2 18 | with: 19 | python-version: 3.9 20 | 21 | - name: Install dependencies 22 | run: |- 23 | python -m pip install --upgrade pip 24 | python -m pip install --upgrade setuptools twine wheel 25 | 26 | - name: Build 27 | run: python setup.py sdist bdist_wheel 28 | 29 | - name: Upload to PyPI 30 | env: 31 | TWINE_USERNAME: __token__ 32 | TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} 33 | run: twine upload dist/* 34 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Stale 2 | 3 | on: 4 | schedule: 5 | - cron: "0 0 * * *" 6 | issue_comment: 7 | types: [created] 8 | 9 | jobs: 10 | stale: 11 | if: github.event_name == 'schedule' 12 | 13 | name: Mark as stale 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - name: Stale 18 | uses: actions/stale@v3 19 | with: 20 | repo-token: ${{ secrets.GITHUB_TOKEN }} 21 | days-before-stale: 30 22 | days-before-close: 14 23 | exempt-issue-labels: A:backlog 24 | stale-issue-label: A:stale 25 | stale-issue-message: |- 26 | This issue has been marked as stale due to its inactivity and will be closed in 14 days. 27 | 28 | If you believe the issue should remain open, remove the `A:stale` label or add a comment. 29 | If you believe the issue will continue to be inactive but should remain open, add the `A:backlog` label. 30 | 31 | exempt-pr-labels: A:backlog 32 | stale-pr-label: A:stale 33 | stale-pr-message: |- 34 | This pull request has been marked as stale due to its inactivity and will be closed in 14 days. 35 | 36 | If you believe the pull request should remain open, remove the `A:stale` label or add a comment. 37 | If you believe the pull request will continue to be inactive but should remain open, add the `A:backlog` label. 38 | 39 | unstale: 40 | if: github.event_name == 'issue_comment' && contains(github.event.issue.labels.*.name, 'A:stale') && github.event.issue.user.type != 'Bot' 41 | 42 | name: Unmark as stale 43 | runs-on: ubuntu-latest 44 | 45 | steps: 46 | - name: Unstale 47 | uses: actions/github-script@v3 48 | with: 49 | github-token: ${{ secrets.GITHUB_TOKEN }} 50 | script: |- 51 | github.issues.removeLabel({ 52 | issue_number: context.issue.number, 53 | owner: context.repo.owner, 54 | repo: context.repo.repo, 55 | name: 'A:stale' 56 | }) 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # python cache 2 | __pycache__/ 3 | 4 | # python package-index 5 | build/ 6 | dist/ 7 | *.egg-info/ 8 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | python: 4 | install: 5 | - method: pip 6 | path: . 7 | extra_requirements: 8 | - docs 9 | 10 | sphinx: 11 | builder: dirhtml 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020-present Ext-Creators 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. raw :: html 2 | 3 |

As of the 28th August 2021 discord-ext-ipc is no-longer maintained.

4 |
5 | 6 | .. raw:: html 7 | 8 |

9 | 10 | Analyze Status 12 | 13 | 14 | 15 | Build Status 17 | 18 | 19 | 20 | Deploy Status 22 | 23 | 24 | 25 | Lint Status 27 | 28 |

29 | 30 | ---------- 31 | 32 | .. raw:: html 33 | 34 |

discord-ext-ipc

35 |

A discord.py extension for inter-process communication.

36 |
Copyright 2020-present Ext-Creators
37 | 38 | 39 | Installation 40 | ------------ 41 | 42 | **Python >=3.5.3 is required.** 43 | 44 | .. code-block:: sh 45 | 46 | pip install --upgrade discord-ext-ipc 47 | 48 | 49 | See Also 50 | -------- 51 | 52 | - The `documentation `_. 53 | - The `usage examples `_. 54 | - The `Ext-Creators Discord `_. 55 | -------------------------------------------------------------------------------- /discord/ext/ipc/__init__.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | from discord.ext.ipc.client import Client 4 | from discord.ext.ipc.server import Server 5 | from discord.ext.ipc.errors import * 6 | 7 | 8 | _VersionInfo = collections.namedtuple("_VersionInfo", "major minor micro release serial") 9 | 10 | version = "2.1.1" 11 | version_info = _VersionInfo(2, 1, 1, "final", 0) 12 | -------------------------------------------------------------------------------- /discord/ext/ipc/client.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | import typing 4 | 5 | import aiohttp 6 | from discord.ext.ipc.errors import * 7 | 8 | log = logging.getLogger(__name__) 9 | 10 | 11 | class Client: 12 | """ 13 | Handles webserver side requests to the bot process. 14 | 15 | Parameters 16 | ---------- 17 | host: str 18 | The IP or host of the IPC server, defaults to localhost 19 | port: int 20 | The port of the IPC server. If not supplied the port will be found automatically, defaults to None 21 | secret_key: Union[str, bytes] 22 | The secret key for your IPC server. Must match the server secret_key or requests will not go ahead, defaults to None 23 | """ 24 | 25 | def __init__(self, host="localhost", port=None, multicast_port=20000, secret_key=None): 26 | """Constructor""" 27 | self.loop = asyncio.get_event_loop() 28 | 29 | self.secret_key = secret_key 30 | 31 | self.host = host 32 | self.port = port 33 | 34 | self.session = None 35 | 36 | self.websocket = None 37 | self.multicast = None 38 | 39 | self.multicast_port = multicast_port 40 | 41 | @property 42 | def url(self): 43 | return "ws://{0.host}:{1}".format(self, self.port if self.port else self.multicast_port) 44 | 45 | async def init_sock(self): 46 | """Attempts to connect to the server 47 | 48 | Returns 49 | ------- 50 | :class:`~aiohttp.ClientWebSocketResponse` 51 | The websocket connection to the server 52 | """ 53 | log.info("Initiating WebSocket connection.") 54 | self.session = aiohttp.ClientSession() 55 | 56 | if not self.port: 57 | log.debug( 58 | "No port was provided - initiating multicast connection at %s.", 59 | self.url, 60 | ) 61 | self.multicast = await self.session.ws_connect(self.url, autoping=False) 62 | 63 | payload = {"connect": True, "headers": {"Authorization": self.secret_key}} 64 | log.debug("Multicast Server < %r", payload) 65 | 66 | await self.multicast.send_json(payload) 67 | recv = await self.multicast.receive() 68 | 69 | log.debug("Multicast Server > %r", recv) 70 | 71 | if recv.type in (aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSED): 72 | log.error( 73 | "WebSocket connection unexpectedly closed. Multicast Server is unreachable." 74 | ) 75 | raise NotConnected("Multicast server connection failed.") 76 | 77 | port_data = recv.json() 78 | self.port = port_data["port"] 79 | 80 | self.websocket = await self.session.ws_connect(self.url, autoping=False, autoclose=False) 81 | log.info("Client connected to %s", self.url) 82 | 83 | return self.websocket 84 | 85 | async def request(self, endpoint, **kwargs): 86 | """Make a request to the IPC server process. 87 | 88 | Parameters 89 | ---------- 90 | endpoint: str 91 | The endpoint to request on the server 92 | **kwargs 93 | The data to send to the endpoint 94 | """ 95 | log.info("Requesting IPC Server for %r with %r", endpoint, kwargs) 96 | if not self.session: 97 | await self.init_sock() 98 | 99 | payload = { 100 | "endpoint": endpoint, 101 | "data": kwargs, 102 | "headers": {"Authorization": self.secret_key}, 103 | } 104 | 105 | await self.websocket.send_json(payload) 106 | 107 | log.debug("Client > %r", payload) 108 | 109 | recv = await self.websocket.receive() 110 | 111 | log.debug("Client < %r", recv) 112 | 113 | if recv.type == aiohttp.WSMsgType.PING: 114 | log.info("Received request to PING") 115 | await self.websocket.ping() 116 | 117 | return await self.request(endpoint, **kwargs) 118 | 119 | if recv.type == aiohttp.WSMsgType.PONG: 120 | log.info("Received PONG") 121 | return await self.request(endpoint, **kwargs) 122 | 123 | if recv.type == aiohttp.WSMsgType.CLOSED: 124 | log.error( 125 | "WebSocket connection unexpectedly closed. IPC Server is unreachable. Attempting reconnection in 5 seconds." 126 | ) 127 | 128 | await self.session.close() 129 | 130 | await asyncio.sleep(5) 131 | 132 | await self.init_sock() 133 | 134 | return await self.request(endpoint, **kwargs) 135 | 136 | return recv.json() 137 | -------------------------------------------------------------------------------- /discord/ext/ipc/errors.py: -------------------------------------------------------------------------------- 1 | from discord import DiscordException 2 | 3 | 4 | class IPCError(DiscordException): 5 | """Base IPC exception class""" 6 | 7 | pass 8 | 9 | 10 | class NoEndpointFoundError(IPCError): 11 | """Raised upon requesting an invalid endpoint""" 12 | 13 | pass 14 | 15 | 16 | class ServerConnectionRefusedError(IPCError): 17 | """Raised upon a server refusing to connect / not being found""" 18 | 19 | pass 20 | 21 | 22 | class JSONEncodeError(IPCError): 23 | """Raise upon un-serializable objects are given to the IPC""" 24 | 25 | pass 26 | 27 | 28 | class NotConnected(IPCError): 29 | """Raised upon websocket not connected""" 30 | 31 | pass 32 | -------------------------------------------------------------------------------- /discord/ext/ipc/server.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import aiohttp.web 4 | from discord.ext.ipc.errors import * 5 | 6 | log = logging.getLogger(__name__) 7 | 8 | 9 | def route(name=None): 10 | """ 11 | Used to register a coroutine as an endpoint when you don't have 12 | access to an instance of :class:`.Server` 13 | 14 | Parameters 15 | ---------- 16 | name: str 17 | The endpoint name. If not provided the method name will be 18 | used. 19 | """ 20 | 21 | def decorator(func): 22 | if not name: 23 | Server.ROUTES[func.__name__] = func 24 | else: 25 | Server.ROUTES[name] = func 26 | 27 | return func 28 | 29 | return decorator 30 | 31 | 32 | class IpcServerResponse: 33 | def __init__(self, data): 34 | self._json = data 35 | self.length = len(data) 36 | 37 | self.endpoint = data["endpoint"] 38 | 39 | for key, value in data["data"].items(): 40 | setattr(self, key, value) 41 | 42 | def to_json(self): 43 | return self._json 44 | 45 | def __repr__(self): 46 | return "".format(self) 47 | 48 | def __str__(self): 49 | return self.__repr__() 50 | 51 | 52 | class Server: 53 | """The IPC server. Usually used on the bot process for receiving 54 | requests from the client. 55 | 56 | Attributes 57 | ---------- 58 | bot: :class:`~discord.ext.commands.Bot` 59 | Your bot instance 60 | host: str 61 | The host to run the IPC Server on. Defaults to localhost. 62 | port: int 63 | The port to run the IPC Server on. Defaults to 8765. 64 | secret_key: str 65 | A secret key. Used for authentication and should be the same as 66 | your client's secret key. 67 | do_multicast: bool 68 | Turn multicasting on/off. Defaults to True 69 | multicast_port: int 70 | The port to run the multicasting server on. Defaults to 20000 71 | """ 72 | 73 | ROUTES = {} 74 | 75 | def __init__( 76 | self, 77 | bot, 78 | host="localhost", 79 | port=8765, 80 | secret_key=None, 81 | do_multicast=True, 82 | multicast_port=20000, 83 | ): 84 | self.bot = bot 85 | self.loop = bot.loop 86 | 87 | self.secret_key = secret_key 88 | 89 | self.host = host 90 | self.port = port 91 | 92 | self._server = None 93 | self._multicast_server = None 94 | 95 | self.do_multicast = do_multicast 96 | self.multicast_port = multicast_port 97 | 98 | self.endpoints = {} 99 | 100 | def route(self, name=None): 101 | """Used to register a coroutine as an endpoint when you have 102 | access to an instance of :class:`.Server`. 103 | 104 | Parameters 105 | ---------- 106 | name: str 107 | The endpoint name. If not provided the method name will be used. 108 | """ 109 | 110 | def decorator(func): 111 | if not name: 112 | self.endpoints[func.__name__] = func 113 | else: 114 | self.endpoints[name] = func 115 | 116 | return func 117 | 118 | return decorator 119 | 120 | def update_endpoints(self): 121 | """Called internally to update the server's endpoints for cog routes.""" 122 | self.endpoints = {**self.endpoints, **self.ROUTES} 123 | 124 | self.ROUTES = {} 125 | 126 | async def handle_accept(self, request): 127 | """Handles websocket requests from the client process. 128 | 129 | Parameters 130 | ---------- 131 | request: :class:`~aiohttp.web.Request` 132 | The request made by the client, parsed by aiohttp. 133 | """ 134 | self.update_endpoints() 135 | 136 | log.info("Initiating IPC Server.") 137 | 138 | websocket = aiohttp.web.WebSocketResponse() 139 | await websocket.prepare(request) 140 | 141 | async for message in websocket: 142 | request = message.json() 143 | 144 | log.debug("IPC Server < %r", request) 145 | 146 | endpoint = request.get("endpoint") 147 | 148 | headers = request.get("headers") 149 | 150 | if not headers or headers.get("Authorization") != self.secret_key: 151 | log.info("Received unauthorized request (Invalid or no token provided).") 152 | response = {"error": "Invalid or no token provided.", "code": 403} 153 | else: 154 | if not endpoint or endpoint not in self.endpoints: 155 | log.info("Received invalid request (Invalid or no endpoint given).") 156 | response = {"error": "Invalid or no endpoint given.", "code": 400} 157 | else: 158 | server_response = IpcServerResponse(request) 159 | try: 160 | attempted_cls = self.bot.cogs.get( 161 | self.endpoints[endpoint].__qualname__.split(".")[0] 162 | ) 163 | 164 | if attempted_cls: 165 | arguments = (attempted_cls, server_response) 166 | else: 167 | arguments = (server_response,) 168 | except AttributeError: 169 | # Support base Client 170 | arguments = (server_response,) 171 | 172 | try: 173 | ret = await self.endpoints[endpoint](*arguments) 174 | response = ret 175 | except Exception as error: 176 | log.error( 177 | "Received error while executing %r with %r", 178 | endpoint, 179 | request, 180 | ) 181 | self.bot.dispatch("ipc_error", endpoint, error) 182 | 183 | response = { 184 | "error": "IPC route raised error of type {}".format( 185 | type(error).__name__ 186 | ), 187 | "code": 500, 188 | } 189 | 190 | try: 191 | await websocket.send_json(response) 192 | log.debug("IPC Server > %r", response) 193 | except TypeError as error: 194 | if str(error).startswith("Object of type") and str(error).endswith( 195 | "is not JSON serializable" 196 | ): 197 | error_response = ( 198 | "IPC route returned values which are not able to be sent over sockets." 199 | " If you are trying to send a discord.py object," 200 | " please only send the data you need." 201 | ) 202 | log.error(error_response) 203 | 204 | response = {"error": error_response, "code": 500} 205 | 206 | await websocket.send_json(response) 207 | log.debug("IPC Server > %r", response) 208 | 209 | raise JSONEncodeError(error_response) 210 | 211 | async def handle_multicast(self, request): 212 | """Handles multicasting websocket requests from the client. 213 | 214 | Parameters 215 | ---------- 216 | request: :class:`~aiohttp.web.Request` 217 | The request made by the client, parsed by aiohttp. 218 | """ 219 | log.info("Initiating Multicast Server.") 220 | websocket = aiohttp.web.WebSocketResponse() 221 | await websocket.prepare(request) 222 | 223 | async for message in websocket: 224 | request = message.json() 225 | 226 | log.debug("Multicast Server < %r", request) 227 | 228 | headers = request.get("headers") 229 | 230 | if not headers or headers.get("Authorization") != self.secret_key: 231 | response = {"error": "Invalid or no token provided.", "code": 403} 232 | else: 233 | response = { 234 | "message": "Connection success", 235 | "port": self.port, 236 | "code": 200, 237 | } 238 | 239 | log.debug("Multicast Server > %r", response) 240 | 241 | await websocket.send_json(response) 242 | 243 | async def __start(self, application, port): 244 | """Start both servers""" 245 | runner = aiohttp.web.AppRunner(application) 246 | await runner.setup() 247 | 248 | site = aiohttp.web.TCPSite(runner, self.host, port) 249 | await site.start() 250 | 251 | def start(self): 252 | """Starts the IPC server.""" 253 | self.bot.dispatch("ipc_ready") 254 | 255 | self._server = aiohttp.web.Application() 256 | self._server.router.add_route("GET", "/", self.handle_accept) 257 | 258 | if self.do_multicast: 259 | self._multicast_server = aiohttp.web.Application() 260 | self._multicast_server.router.add_route("GET", "/", self.handle_multicast) 261 | 262 | self.loop.run_until_complete(self.__start(self._multicast_server, self.multicast_port)) 263 | 264 | self.loop.run_until_complete(self.__start(self._server, self.port)) 265 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | project = "discord-ext-ipc" 4 | copyright = "2020-present, Ext-Creators" 5 | author = "Ext-Creators" 6 | 7 | _version_regex = r"^version = ('|\")((?:[0-9]+\.)*[0-9]+(?:\.?([a-z]+)(?:\.?[0-9])?)?)\1$" 8 | 9 | with open("../discord/ext/ipc/__init__.py") as stream: 10 | match = re.search(_version_regex, stream.read(), re.MULTILINE) 11 | 12 | version = match.group(2) 13 | 14 | if match.group(3) is not None: 15 | try: 16 | import subprocess 17 | 18 | process = subprocess.Popen(["git", "rev-list", "--count", "HEAD"], stdout=subprocess.PIPE) 19 | out, _ = process.communicate() 20 | if out: 21 | version += out.decode("utf-8").strip() 22 | 23 | process = subprocess.Popen(["git", "rev-parse", "--short", "HEAD"], stdout=subprocess.PIPE) 24 | out, _ = process.communicate() 25 | if out: 26 | version += "+g" + out.decode("utf-8").strip() 27 | except (Exception) as e: 28 | pass 29 | 30 | release = version 31 | 32 | 33 | extensions = [ 34 | "sphinx.ext.autodoc", 35 | "sphinx.ext.napoleon", 36 | "sphinx.ext.intersphinx", 37 | "sphinx_rtd_theme", 38 | "sphinxcontrib_trio", 39 | ] 40 | 41 | 42 | autodoc_typehints = "none" 43 | 44 | intersphinx_mapping = { 45 | "aiohttp": ("https://docs.aiohttp.org/en/stable/", None), 46 | "python": ("https://docs.python.org/3", None), 47 | "discord": ("https://discordpy.readthedocs.io/en/latest", None), 48 | } 49 | 50 | highlight_language = "python3" 51 | html_theme = "sphinx_rtd_theme" 52 | master_doc = "index" 53 | pygments_style = "friendly" 54 | source_suffix = ".rst" 55 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Welcome to discord-ext-ipc's documentation! 2 | =========================================== 3 | 4 | .. toctree:: 5 | :numbered: 6 | :maxdepth: 2 7 | :caption: Contents: 8 | 9 | modules/server.rst 10 | modules/client.rst 11 | modules/errors.rst 12 | modules/examples.rst 13 | 14 | 15 | 16 | Indices and tables 17 | ================== 18 | 19 | * :ref:`genindex` 20 | * :ref:`modindex` 21 | * :ref:`search` 22 | -------------------------------------------------------------------------------- /docs/modules/client.rst: -------------------------------------------------------------------------------- 1 | Client Connection 2 | ================= 3 | 4 | The IPC client is very simple. 5 | It will simply connect to your server process and send JSON data. 6 | If you do not supply a port on initialisation, the client will connect to the multicast server 7 | (see the server section) and return the port from said server. 8 | If you do supply a port, it will connect to the server instantly. 9 | 10 | Requests are made by calling ``ipc.client.request(endpoint, **kwargs)`` 11 | and will be sent to the server in the json format specified above. 12 | It will then wait for a response and return the data. 13 | 14 | .. currentmodule:: discord.ext.ipc.client 15 | 16 | .. autoclass:: Client 17 | :members: 18 | -------------------------------------------------------------------------------- /docs/modules/errors.rst: -------------------------------------------------------------------------------- 1 | IPC Errors 2 | ========== 3 | 4 | .. currentmodule:: discord.ext.ipc.errors 5 | 6 | .. autoclass:: IPCError 7 | 8 | .. autoclass:: NoEndpointFoundError 9 | 10 | .. autoclass:: ServerConnectionRefusedError 11 | 12 | .. autoclass:: JSONEncodeError 13 | 14 | .. autoclass:: NotConnected 15 | -------------------------------------------------------------------------------- /docs/modules/examples.rst: -------------------------------------------------------------------------------- 1 | Example Usages 2 | ============== 3 | 4 | Here are some ways to use our package in **your own bot!** For github based examples, see `the examples directory `_. 5 | 6 | 7 | A basic implementation 8 | ---------------------- 9 | 10 | The bot file: 11 | 12 | .. code-block:: python 13 | :linenos: 14 | 15 | import discord 16 | from discord.ext import commands, ipc 17 | 18 | 19 | class MyBot(commands.Bot): 20 | def __init__(self, *args, **kwargs): 21 | super().__init__(*args, **kwargs) 22 | 23 | self.ipc = ipc.Server(self, secret_key="my_secret_key") # create our IPC Server 24 | 25 | async def on_ready(self): 26 | """Called upon the READY event""" 27 | print("Bot is ready.") 28 | 29 | async def on_ipc_ready(self): 30 | """Called upon the IPC Server being ready""" 31 | print("Ipc is ready.") 32 | 33 | async def on_ipc_error(self, endpoint, error): 34 | """Called upon an error being raised within an IPC route""" 35 | print(endpoint, "raised", error) 36 | 37 | 38 | my_bot = MyBot(command_prefix="!", intents=discord.Intents.all()) 39 | 40 | 41 | @my_bot.ipc.route() 42 | async def get_member_count(data): 43 | guild = my_bot.get_guild( 44 | data.guild_id 45 | ) # get the guild object using parsed guild_id 46 | 47 | return guild.member_count # return the member count to the client 48 | 49 | 50 | if __name__ == "__main__": 51 | my_bot.ipc.start() # start the IPC Server 52 | my_bot.run("TOKEN") 53 | 54 | The webserver file: 55 | 56 | .. code-block:: python 57 | :linenos: 58 | 59 | from quart import Quart 60 | from discord.ext import ipc 61 | 62 | 63 | app = Quart(__name__) 64 | ipc_client = ipc.Client( 65 | secret_key="my_secret_key" 66 | ) # secret_key must be the same as your server 67 | 68 | 69 | @app.route("/") 70 | async def index(): 71 | member_count = await ipc_client.request( 72 | "get_member_count", guild_id=12345678 73 | ) # get the member count of server with ID 12345678 74 | 75 | return str(member_count) # display member count 76 | 77 | 78 | if __name__ == "__main__": 79 | app.run() 80 | 81 | 82 | Cog based IPC implementation 83 | ---------------------------- 84 | 85 | The bot file: 86 | 87 | .. code-block:: python 88 | :linenos: 89 | 90 | import discord 91 | from discord.ext import commands, ipc 92 | 93 | 94 | class MyBot(commands.Bot): 95 | def __init__(self, *args, **kwargs): 96 | super().__init__(*args, **kwargs) 97 | 98 | self.ipc = ipc.Server(self, secret_key="my_secret_key") # create our IPC Server 99 | 100 | self.load_extension("cogs.ipc") # load the IPC Route cog 101 | 102 | async def on_ready(self): 103 | """Called upon the READY event""" 104 | print("Bot is ready.") 105 | 106 | async def on_ipc_ready(self): 107 | """Called upon the IPC Server being ready""" 108 | print("Ipc is ready.") 109 | 110 | async def on_ipc_error(self, endpoint, error): 111 | """Called upon an error being raised within an IPC route""" 112 | print(endpoint, "raised", error) 113 | 114 | 115 | my_bot = MyBot(command_prefix="!", intents=discord.Intents.all()) 116 | 117 | 118 | if __name__ == "__main__": 119 | my_bot.ipc.start() # start the IPC Server 120 | my_bot.run("TOKEN") 121 | 122 | The cog file: 123 | 124 | .. code-block:: python 125 | :linenos: 126 | 127 | from discord.ext import commands, ipc 128 | 129 | 130 | class IpcRoutes(commands.Cog): 131 | def __init__(self, bot): 132 | self.bot = bot 133 | 134 | @ipc.server.route() 135 | async def get_member_count(self, data): 136 | guild = self.bot.get_guild( 137 | data.guild_id 138 | ) # get the guild object using parsed guild_id 139 | 140 | return guild.member_count # return the member count to the client 141 | 142 | 143 | def setup(bot): 144 | bot.add_cog(IpcRoutes(bot)) 145 | 146 | The webserver file: 147 | 148 | .. code-block:: python 149 | :linenos: 150 | 151 | from quart import Quart 152 | from discord.ext import ipc 153 | 154 | 155 | app = Quart(__name__) 156 | ipc_client = ipc.Client( 157 | secret_key="my_secret_key" 158 | ) # secret_key must be the same as your server 159 | 160 | 161 | @app.route("/") 162 | async def index(): 163 | member_count = await ipc_client.request( 164 | "get_member_count", guild_id=12345678 165 | ) # get the member count of server with ID 12345678 166 | 167 | return str(member_count) # display member count 168 | 169 | 170 | if __name__ == "__main__": 171 | app.run() 172 | -------------------------------------------------------------------------------- /docs/modules/server.rst: -------------------------------------------------------------------------------- 1 | Server Setup 2 | ============ 3 | 4 | The IPC server is what runs on your bot’s process. 5 | It will run within the same loop as your bot without interfering with your bot’s process. 6 | 7 | The server handles multiple things: 8 | 9 | - Routes 10 | - These routes / endpoints are available to the client and are what your server returns upon requests being made to it. 11 | - Authentication 12 | - The IPC client and server use a secret key authentication system. If your server secret key and the request’s authentication header don’t match, the request will not be carried out. 13 | - Multicasting 14 | - You do not have to specify a port on your client process, only an IP (defaults to localhost). If you do not specify an IP then the client will connect to another server running on port 20000. This will return the port of your main server for the client to connect to. 15 | 16 | 17 | So, how does it work? 18 | The server is simply just a websocket server. 19 | Requests are sent in a JSON payload to and from the server. 20 | For example, a client request could be {'endpoint': 'get_guild_count', 'headers': {...}}. 21 | This JSON is processed upon a request being made, and checks for a registered route matching the name of the endpoint supplied. 22 | It then calls the method linked to said route and returns the payload to the client. 23 | 24 | .. currentmodule:: discord.ext.ipc.server 25 | 26 | .. autofunction:: route 27 | 28 | .. autoclass:: Server 29 | :members: 30 | -------------------------------------------------------------------------------- /examples/basic-ipc/bot.py: -------------------------------------------------------------------------------- 1 | import discord 2 | from discord.ext import commands, ipc 3 | 4 | 5 | class MyBot(commands.Bot): 6 | def __init__(self, *args, **kwargs): 7 | super().__init__(*args, **kwargs) 8 | 9 | self.ipc = ipc.Server(self, secret_key="my_secret_key") # create our IPC Server 10 | 11 | async def on_ready(self): 12 | """Called upon the READY event""" 13 | print("Bot is ready.") 14 | 15 | async def on_ipc_ready(self): 16 | """Called upon the IPC Server being ready""" 17 | print("Ipc is ready.") 18 | 19 | async def on_ipc_error(self, endpoint, error): 20 | """Called upon an error being raised within an IPC route""" 21 | print(endpoint, "raised", error) 22 | 23 | 24 | my_bot = MyBot(command_prefix="!", intents=discord.Intents.all()) 25 | 26 | 27 | @my_bot.ipc.route() 28 | async def get_member_count(data): 29 | guild = my_bot.get_guild(data.guild_id) # get the guild object using parsed guild_id 30 | 31 | return guild.member_count # return the member count to the client 32 | 33 | 34 | if __name__ == "__main__": 35 | my_bot.ipc.start() # start the IPC Server 36 | my_bot.run("TOKEN") 37 | -------------------------------------------------------------------------------- /examples/basic-ipc/webserver.py: -------------------------------------------------------------------------------- 1 | from quart import Quart 2 | from discord.ext import ipc 3 | 4 | 5 | app = Quart(__name__) 6 | ipc_client = ipc.Client(secret_key="my_secret_key") # secret_key must be the same as your server 7 | 8 | 9 | @app.route("/") 10 | async def index(): 11 | member_count = await ipc_client.request( 12 | "get_member_count", guild_id=12345678 13 | ) # get the member count of server with ID 12345678 14 | 15 | return str(member_count) # display member count 16 | 17 | 18 | if __name__ == "__main__": 19 | app.run() 20 | -------------------------------------------------------------------------------- /examples/cog_based_ipc/bot.py: -------------------------------------------------------------------------------- 1 | import discord 2 | from discord.ext import commands, ipc 3 | 4 | 5 | class MyBot(commands.Bot): 6 | def __init__(self, *args, **kwargs): 7 | super().__init__(*args, **kwargs) 8 | 9 | self.ipc = ipc.Server(self, secret_key="my_secret_key") # create our IPC Server 10 | 11 | self.load_extension("cogs.ipc") # load the IPC Route cog 12 | 13 | async def on_ready(self): 14 | """Called upon the READY event""" 15 | print("Bot is ready.") 16 | 17 | async def on_ipc_ready(self): 18 | """Called upon the IPC Server being ready""" 19 | print("Ipc is ready.") 20 | 21 | async def on_ipc_error(self, endpoint, error): 22 | """Called upon an error being raised within an IPC route""" 23 | print(endpoint, "raised", error) 24 | 25 | 26 | my_bot = MyBot(command_prefix="!", intents=discord.Intents.all()) 27 | 28 | 29 | if __name__ == "__main__": 30 | my_bot.ipc.start() # start the IPC Server 31 | my_bot.run("TOKEN") 32 | -------------------------------------------------------------------------------- /examples/cog_based_ipc/cogs/ipc.py: -------------------------------------------------------------------------------- 1 | from discord.ext import commands, ipc 2 | 3 | 4 | class IpcRoutes(commands.Cog): 5 | def __init__(self, bot): 6 | self.bot = bot 7 | 8 | @ipc.server.route() 9 | async def get_member_count(self, data): 10 | guild = self.bot.get_guild(data.guild_id) # get the guild object using parsed guild_id 11 | 12 | return guild.member_count # return the member count to the client 13 | 14 | 15 | def setup(bot): 16 | bot.add_cog(IpcRoutes(bot)) 17 | -------------------------------------------------------------------------------- /examples/cog_based_ipc/webserver.py: -------------------------------------------------------------------------------- 1 | from quart import Quart 2 | from discord.ext import ipc 3 | 4 | 5 | app = Quart(__name__) 6 | ipc_client = ipc.Client(secret_key="my_secret_key") # secret_key must be the same as your server 7 | 8 | 9 | @app.route("/") 10 | async def index(): 11 | member_count = await ipc_client.request( 12 | "get_member_count", guild_id=12345678 13 | ) # get the member count of server with ID 12345678 14 | 15 | return str(member_count) # display member count 16 | 17 | 18 | if __name__ == "__main__": 19 | app.run() 20 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | discord.py 2 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import re 2 | import setuptools 3 | 4 | 5 | classifiers = [ 6 | "Development Status :: 5 - Production/Stable", 7 | "Framework :: AsyncIO", 8 | "Intended Audience :: Developers", 9 | "License :: OSI Approved :: Apache Software License", 10 | "Natural Language :: English", 11 | "Operating System :: OS Independent", 12 | "Programming Language :: Python", 13 | "Programming Language :: Python :: 3", 14 | "Programming Language :: Python :: 3 :: Only", 15 | "Programming Language :: Python :: 3.5", 16 | "Programming Language :: Python :: 3.6", 17 | "Programming Language :: Python :: 3.7", 18 | "Programming Language :: Python :: 3.8", 19 | "Programming Language :: Python :: 3.9", 20 | "Programming Language :: Python :: 3.10", 21 | "Programming Language :: Python :: Implementation :: CPython", 22 | "Topic :: Communications", 23 | "Topic :: Documentation", 24 | "Topic :: Documentation :: Sphinx", 25 | "Topic :: Internet", 26 | "Topic :: Software Development", 27 | "Topic :: Software Development :: Libraries", 28 | "Topic :: Software Development :: Libraries :: Python Modules", 29 | ] 30 | 31 | extras_require = { 32 | "docs": [ 33 | "sphinx", 34 | "sphinxcontrib_trio", 35 | "sphinx-rtd-theme", 36 | ], 37 | } 38 | 39 | with open("requirements.txt") as stream: 40 | install_requires = stream.read().splitlines() 41 | 42 | packages = [ 43 | "discord.ext.ipc", 44 | ] 45 | 46 | project_urls = { 47 | "Documentation": "https://discord-ext-ipc.readthedocs.io", 48 | "Issue Tracker": "https://github.com/Ext-Creators/discord-ext-ipc/issues", 49 | "Source": "https://github.com/Ext-Creators/discord-ext-ipc", 50 | } 51 | 52 | _version_regex = r"^version = ('|\")((?:[0-9]+\.)*[0-9]+(?:\.?([a-z]+)(?:\.?[0-9])?)?)\1$" 53 | 54 | with open("discord/ext/ipc/__init__.py") as stream: 55 | match = re.search(_version_regex, stream.read(), re.MULTILINE) 56 | 57 | version = match.group(2) 58 | 59 | if match.group(3) is not None: 60 | try: 61 | import subprocess 62 | 63 | process = subprocess.Popen(["git", "rev-list", "--count", "HEAD"], stdout=subprocess.PIPE) 64 | out, _ = process.communicate() 65 | if out: 66 | version += out.decode("utf-8").strip() 67 | 68 | process = subprocess.Popen(["git", "rev-parse", "--short", "HEAD"], stdout=subprocess.PIPE) 69 | out, _ = process.communicate() 70 | if out: 71 | version += "+g" + out.decode("utf-8").strip() 72 | except (Exception) as e: 73 | pass 74 | 75 | 76 | setuptools.setup( 77 | author="Ext-Creators", 78 | classifiers=classifiers, 79 | description="A discord.py extension for inter-process communication.", 80 | extras_require=extras_require, 81 | install_requires=install_requires, 82 | license="Apache Software License", 83 | name="discord-ext-ipc", 84 | packages=packages, 85 | project_urls=project_urls, 86 | python_requires=">=3.5.3", 87 | url="https://github.com/Ext-Creators/discord-ext-ipc", 88 | version=version, 89 | ) 90 | --------------------------------------------------------------------------------