diff options
| author | Nakidai <plaza521@inbox.ru> | 2024-09-04 19:34:45 +0300 |
|---|---|---|
| committer | Nakidai <plaza521@inbox.ru> | 2024-09-04 19:37:18 +0300 |
| commit | 5ae48feb9cc03241a5c6b2578a357db5736ba359 (patch) | |
| tree | 75f43caee6f3dd1a942ac25415b3cf8b67f9e4b3 | |
| download | petthecord-5ae48feb9cc03241a5c6b2578a357db5736ba359.tar.gz petthecord-5ae48feb9cc03241a5c6b2578a357db5736ba359.zip | |
Initial commit
| -rw-r--r-- | .gitignore | 176 | ||||
| -rw-r--r-- | LICENSE | 9 | ||||
| -rw-r--r-- | README.md | 9 | ||||
| -rw-r--r-- | pyproject.toml | 22 | ||||
| -rw-r--r-- | src/petthecord/__init__.py | 4 | ||||
| -rw-r--r-- | src/petthecord/bot.py | 21 | ||||
| -rw-r--r-- | src/petthecord/main.py | 36 | ||||
| -rw-r--r-- | src/petthecord/server.py | 37 |
8 files changed, 314 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ad4a1f1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,176 @@ +# Created by https://www.toptal.com/developers/gitignore/api/python +# Edit at https://www.toptal.com/developers/gitignore?templates=python + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +### Python Patch ### +# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration +poetry.toml + +# ruff +.ruff_cache/ + +# LSP config files +pyrightconfig.json + +# End of https://www.toptal.com/developers/gitignore/api/python diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7977ab2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +Copyright 2024 Nakidai + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7755fa4 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +PetTheCord +-- +This is a Web API for petting any user you know which has avatar + +## Usage +`https://example.com/<UserID>.gif` will return you gif that specified user. + +To get UserID you should enable developer mode in your client and "Copy User ID" +option will appear when you do RMB on user. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..5b7db47 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,22 @@ +[build-system] +requires = ["setuptools >= 61.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "petthecord" +description = "Web API for petting any user you want" +readme = "README.md" +version = "v1.0.0" +dependencies = [ + "discord.py==2.4.0", + "aiohttp==3.10.5", + "pet-pet-gif@git+https://github.com/camprevail/pet-pet-gif@28a4a5d18b312bcb84e6dcd461c0e16fc6d2bf16", +] +authors = [{name = "Nakidai", email = "plaza521@inbox.ru"}] +classifiers = [ + "License :: OSI Approved :: BSD License", + "Programming Language :: Python :: 3.12", +] + +[project.scripts] +petthecord = "petthecord:main" diff --git a/src/petthecord/__init__.py b/src/petthecord/__init__.py new file mode 100644 index 0000000..afd0ec5 --- /dev/null +++ b/src/petthecord/__init__.py @@ -0,0 +1,4 @@ +from .main import Bot, main + + +__all__ = ["main"] diff --git a/src/petthecord/bot.py b/src/petthecord/bot.py new file mode 100644 index 0000000..de1277b --- /dev/null +++ b/src/petthecord/bot.py @@ -0,0 +1,21 @@ +from aiohttp.web import AppRunner, TCPSite +from discord import Intents +from discord.ext import commands + +from .server import Server + + +class Bot(commands.Bot): + def __init__(self, host: str = "127.0.0.1", port: int = 8080) -> None: + super().__init__( + command_prefix="!", + intents=Intents.default() + ) + self._host = host + self._port = port + + async def on_ready(self) -> None: + runner = AppRunner(Server(self)) + await runner.setup() + site = TCPSite(runner, self._host, self._port) + await site.start() diff --git a/src/petthecord/main.py b/src/petthecord/main.py new file mode 100644 index 0000000..0e3056f --- /dev/null +++ b/src/petthecord/main.py @@ -0,0 +1,36 @@ +from argparse import ArgumentParser +from os import getenv +from sys import argv, stderr + +from .bot import Bot + + +def main() -> None: + parser = ArgumentParser( + prog="petthecord", + description="Web API for petting any user you want" + ) + parser.add_argument( + "-p", "--port", + default=8000, + type=int, + metavar="PORT", + help="Bind port" + ) + parser.add_argument( + "-i", "--host", + default="127.0.0.1", + metavar="HOST", + help="Bind IP" + ) + args = parser.parse_args() + + bot = Bot() + if (token := getenv("PETTHECORD_TOKEN")) is not None: + bot.run(token) + elif (token_path := getenv("PETTHECORD_TOKEN_FILE")) is not None: + with open(token_path) as f: + token = f.read() + bot.run(token, args.host, args.port) + else: + print(f"{argv[0]}: Neither PETTHECORD_TOKEN nor PETTHECORD_TOKEN_FILE are set", file=stderr) diff --git a/src/petthecord/server.py b/src/petthecord/server.py new file mode 100644 index 0000000..8c3d8a2 --- /dev/null +++ b/src/petthecord/server.py @@ -0,0 +1,37 @@ +from io import BytesIO + +from aiohttp.web import Application, StreamResponse, get, Request, Response +from discord import NotFound, HTTPException +from discord.ext import commands +from petpetgif import petpet + + +class Server(Application): + def __init__(self, client: commands.Bot) -> None: + self.client = client + super().__init__() + + self.add_routes([get("/{uid}", self.root)]) + + async def root(self, request: Request) -> StreamResponse: + try: + uid = int(request.match_info["uid"][:request.match_info["uid"].find('.')]) + except ValueError: + return Response(status=400) + + try: + user = await self.client.fetch_user(uid) + except NotFound: + return Response(status=404) + except HTTPException: + return Response(status=403) + + if user.avatar is None: + return Response(status=404) + + image = await user.avatar.read() + dest = BytesIO() + petpet.make(BytesIO(image), dest) + dest.seek(0) + + return Response(body=dest.getvalue(), content_type="image/png") |