.
diff --git a/tests/README.md b/tests/README.md
new file mode 100644
index 000000000..57baa9340
--- /dev/null
+++ b/tests/README.md
@@ -0,0 +1,145 @@
+## Killua Discord Bot
+
+
+
+
+
+
+
+
+
+
+Games, Moderation, todo lists and much more.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+## What is Killua?
+
+I started Killua as a way to learn python and different programming concepts. It definitely was not the easiest way to do it, but it got me to a good level of python knowledge plus having a cool bot! As a result, I greatly appreciate issues, PRs and contributions enhancing my code.
+
+## Links
+
+* [Website](https://killua.dev)
+* [Support server](https://discord.gg/Jkd29QvhBP)
+* [Invite link](https://discord.com/oauth2/authorize?client_id=756206646396452975&scope=bot&permissions=268723414&applications.commands)
+* [Patreon](https://patreon.com/kilealkuri)
+
+## Programming concepts list
+
+As explained previously, I use Killua as a tool to learn more about python and programming. Here is a list of programming concepts Killua uses and which ones it is planned to use at some point in the future.
+
+* [x] OOP (Object Oriented Programming)
+* [x] Web scraping
+* [x] IPC (Inter Process Communication)
+* [x] Providing and requesting REST-APIs
+* [x] Image manipulation
+* [x] Asyncronous Programming
+* [x] logging
+* [x] NonSQL databases
+* [x] Python `typing` library
+* [x] GitHub PRs, branches, issues, todo-lists, CLI
+* [x] caching
+* [ ] Website with backend
+* [ ] CSS
+* [ ] Threading
+* [ ] Github workflows
+
+## Contributors
+
+I would like to give a big thank you to everyone who has helped me on this journey, each in their different way.
+
+* [WhoAmI](https://github.com/WhoAmI1000)
+
+> Who has been with the project since the start, creating the website and supporting it through Patreon.
+
+* [MNW](https://linktr.ee/Michaelnw_mnw)
+
+> An incredibly talented artist who made many artworks which make Killua look and feel so much better for little to no price.
+
+* [ClashCrafter](https://github.com/FlorianStrobl)
+
+> Contributed initial parts of the web scraping code.
+
+* [danii](https://github.com/danii)
+
+> Helped to change the incredibly bad mess of everything in one file into an organised, dynamic system and helped out with git commands.
+
+* [DerUSBStick](https://github.com/DerUSBstick)
+
+> He contributed a lot to one of the best looking commands, `book` which uses image generation to make your collection book filled with cards!
+
+* [Scarf](https://odaibako.net/u/ano_furi)
+
+> Helped write some of the action texts, topics, 8ball responses and would you rather questions.
+
+* [Scientia](https://github.com/ScientiaEtVeritas)
+
+> Gave me the original idea for this bot and helped me in the early stages, enduring lots of pings and stupid questions.
+
+## Running Killua locally
+
+First, set up a virtual environment. Do so with `python3 -m venv env; source env/bin/activate`. To leave the virtual environment after you are done, simply run `deactivate`
+
+`requirements.txt` contains the libraries you'll need. To install them use `pip3 install -r requirements.txt`
+
+You will need a Mongodb account. Why do I use mongodb and not SQL? In my opinion, mongo is easier to use and you can manually add and remove data.
+
+You will have to create a mongodb account [here](https://www.mongodb.com), then follow the instructions in [`setup.py`](https://github/Kile/Killua/blob/main/setup.py) and then run `python3 setup.py` or choose the "setup database" option in the menu to get the database set up
+
+You will also need a file named `config.json` having the layout like this:
+
+```plaintext
+{
+ "token": "token",
+
+ "mongodb": "your-mongodb-token",
+ "pxlapi": "pxlapi-token",
+ "patreon": "patreon-api-token",
+ "dbl_token": "dbl-token",
+ "topgg_token": "topgg-token",
+ "password": "vote-pages-password",
+ "port": 8000,
+ "ipc": "ipc-token"
+}
+```
+
+You can finally run the bot in development or production environment in a menu by running `./run.sh`
+
+**If you add any commands, please make sure to also add tests for it. A document explaining how tests for Killua work can be found** [**here**](https://github.com/Kile/Killua/blob/main/killua/tests/README.md)
+
+If you don't like me using one of your images for the hug command, please contact me on discord `Kile#0606` or on `kile@killua.dev`
+
+If you have any further questions, join my discord server or dm me!
+
+
+
+
+
+
diff --git a/tests/data.json b/tests/data.json
new file mode 100644
index 000000000..2e411cfd6
--- /dev/null
+++ b/tests/data.json
@@ -0,0 +1,692 @@
+[
+ {
+ "id": "756206646396452975",
+ "timestamp": "1624715214",
+ "guild": 1520
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1624745771",
+ "guild": 1530
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1625276911",
+ "guild": 1540
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1625362813",
+ "guild": 1550
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1625542307",
+ "guild": 1540
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1625720636",
+ "guild": 1550
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1625895552",
+ "guild": 1560
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1626251729",
+ "guild": 1570
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1626729226",
+ "guild": 1590
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1627058472",
+ "guild": 1600
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1627784468",
+ "guild": 1630
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1627872385",
+ "guild": 1640
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1628308645",
+ "guild": 1650
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1628661194",
+ "guild": 1660
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1628750299",
+ "guild": 1650
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1628838191",
+ "guild": 1660
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1629102618",
+ "guild": 1670
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1629368729",
+ "guild": 1680
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1629632911",
+ "guild": 1690
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1629722696",
+ "guild": 1700
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1629814434",
+ "guild": 1710
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1629997438",
+ "guild": 1720
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1630086523",
+ "guild": 1730
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1630264531",
+ "guild": 1740
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1630790237",
+ "guild": 1750
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1631058457",
+ "guild": 1760
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1631236055",
+ "guild": 1770
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1631409168",
+ "guild": 1780
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1631504813",
+ "guild": 1770
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1631585904",
+ "guild": 1780
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1631674899",
+ "guild": 1770
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1631762422",
+ "guild": 1780
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1632029166",
+ "guild": 1790
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1632117307",
+ "guild": 1800
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1632381716",
+ "guild": 1820
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1632554734",
+ "guild": 1830
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1635639148",
+ "guild": 1880
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1635824044",
+ "guild": 1890
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1635911747",
+ "guild": 1900
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1636090604",
+ "guild": 1910
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1636188518",
+ "guild": 1920
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1638167658",
+ "guild": 1960
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1638255124",
+ "guild": 1950
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1632997836",
+ "guild": 1840
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1633177338",
+ "guild": 1840
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1633446552",
+ "guild": 1850
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1633284352",
+ "guild": 1830
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1633357791",
+ "guild": 1840
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1633089025",
+ "guild": 1830
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1633537987",
+ "guild": 1840
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1633818640",
+ "guild": 1850
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1634183980",
+ "guild": 1860
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1636631501",
+ "guild": 1930
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1636901996",
+ "guild": 1940
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1636991007",
+ "guild": 1950
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1635084049",
+ "guild": 1860
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1634806768",
+ "guild": 1850
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1638615243",
+ "guild": 1960
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1638983187",
+ "guild": 1950
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1639075738",
+ "guild": 1960
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1639353279",
+ "guild": 1950
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1639433787",
+ "guild": 1960
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1642436535",
+ "guild": 1990
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1641524591",
+ "guild": 1970
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1641696988",
+ "guild": 1980
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1642613010",
+ "guild": 2000
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1642799893",
+ "guild": 2010
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1644643479",
+ "guild": 2070
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1644729342",
+ "guild": 2080
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1644896167",
+ "guild": 2070
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1645017364",
+ "guild": 2080
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1645274669",
+ "guild": 2090
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1643073548",
+ "guild": 2020
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1643264089",
+ "guild": 2040
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1643614641",
+ "guild": 2050
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1643195085",
+ "guild": 2030
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1644531659",
+ "guild": 2080
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1644072514",
+ "guild": 2060
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1644345918",
+ "guild": 2070
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1644167119",
+ "guild": 2050
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1644263439",
+ "guild": 2060
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1645942871",
+ "guild": 2100
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1646809800",
+ "guild": 2100
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1646886860",
+ "guild": 2130
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1646986262",
+ "guild": 2140
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1646455070",
+ "guild": 2110
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1647152844",
+ "guild": 2150
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1647233001",
+ "guild": 2160
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1648850986",
+ "guild": 2220
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1648945943",
+ "guild": 2210
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1648682839",
+ "guild": 2210
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1647412237",
+ "guild": 2160
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1647492517",
+ "guild": 2170
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1648132103",
+ "guild": 2220
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1647331072",
+ "guild": 2170
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1647679614",
+ "guild": 2180
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1648043200",
+ "guild": 2190
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1650405212",
+ "guild": 2230
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1650657665",
+ "guild": 2240
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1651369346",
+ "guild": 2250
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1649668339",
+ "guild": 2200
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1649847122",
+ "guild": 2210
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1650031344",
+ "guild": 2220
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1651550296",
+ "guild": 2260
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1652101561",
+ "guild": 2270
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1652198976",
+ "guild": 2260
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1655676502",
+ "guild": 2360
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1655766417",
+ "guild": 2370
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1655494373",
+ "guild": 2370
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1656227986",
+ "guild": 2380
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1654132170",
+ "guild": 2270
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1654302786",
+ "guild": 2300
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1654677820",
+ "guild": 2330
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1654763503",
+ "guild": 2360
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1654495290",
+ "guild": 2310
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1654211411",
+ "guild": 2290
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1658557921",
+ "guild": 2390
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1657919148",
+ "guild": 2400
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1658003916",
+ "guild": 2390
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1658285695",
+ "guild": 2390
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1658186491",
+ "guild": 2400
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1657729947",
+ "guild": 2390
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1658373766",
+ "guild": 2400
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1658641222",
+ "guild": 2400
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1660494552",
+ "guild": 2400
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1660782790",
+ "guild": 2410
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1659849589",
+ "guild": 2410
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1659949403",
+ "guild": 2400
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1660332759",
+ "guild": 2410
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1661752406",
+ "guild": 2400
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1661848409",
+ "guild": 2410
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1662606937",
+ "guild": 2400
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1663064709",
+ "guild": 2410
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1663879129",
+ "guild": 2420
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1665674782",
+ "guild": 2440
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1665772697",
+ "guild": 2430
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1664641423",
+ "guild": 2430
+ },
+ {
+ "id": "756206646396452975",
+ "timestamp": "1667191901",
+ "guild": 2440
+ }
+]
\ No newline at end of file
diff --git a/tests/killua/__init__.py b/tests/killua/__init__.py
new file mode 100644
index 000000000..83f58ad1d
--- /dev/null
+++ b/tests/killua/__init__.py
@@ -0,0 +1,109 @@
+from . import cogs
+import discord
+import aiohttp
+import asyncio
+import logging
+
+from .tests import run_tests
+from .migrate import migrate
+from .download import download
+from .bot import BaseBot as Bot, get_prefix
+# This needs to be in a seperate file from the __init__ file to
+# avoid relative import errors when subclassing it in the testing module
+from .webhook.api import app
+from .static.constants import TOKEN, PORT
+
+import killua.args as args_file
+
+async def main():
+ start_time = time.time()
+ args_file.Args.get_args()
+ args = args_file.Args
+
+ # Set up logger from command line arguments
+ log_level = getattr(logging, args.log.upper())
+ logging.basicConfig(
+ level=log_level,
+ datefmt='%I:%M:%S',
+ format="[%(asctime)s] %(levelname)s: %(message)s"
+ )
+ logger = logging.getLogger('killua')
+ logger.info(f"Starting Killua bot with log level: {args.log.upper()}")
+
+ # Check if MongoDB is running before proceeding
+ try:
+ logger.info("Checking MongoDB connection...")
+ # Set a shorter timeout for faster startup
+ DB.const.database.client.server_info()
+ logger.info("MongoDB connection successful")
+ except Exception as e:
+ logger.critical(f"MongoDB connection failed: {e}")
+ logger.critical("Please make sure MongoDB is running and the connection string is correct in config.json")
+ logger.critical("Bot cannot start without a database connection. Exiting...")
+ return 1
+
+ if args.migrate:
+ logger.info("Running database migration")
+ return migrate()
+
+ if args.test is not None:
+ logger.info(f"Running tests: {args.test}")
+ return await run_tests(args.test)
+
+ if args.download:
+ logger.info("Running download operation")
+ return await download()
+
+ logger.info("Initializing HTTP session")
+ async with aiohttp.ClientSession() as session:
+ logger.info("Setting up Discord intents")
+ intents = discord.Intents(
+ guilds=True,
+ members=True,
+ emojis_and_stickers=True,
+ messages=True,
+ message_content=True
+ )
+
+ # Create the bot instance
+ logger.info("Creating bot instance")
+ bot = Bot(
+ command_prefix=get_prefix,
+ description="The discord bot Killua",
+ case_insensitive=True,
+ intents=intents,
+ session=session
+ )
+ bot.session = session
+
+ # Set development mode
+ bot.is_dev = args.development
+ logger.info(f"Development mode: {bot.is_dev}")
+
+ # Setup cogs
+ logger.info(f"Loading {len(cogs.all_cogs)} cogs...")
+ cog_load_start = time.time()
+ for i, cog_module in enumerate(cogs.all_cogs):
+ try:
+ logger.debug(f"Loading cog {i+1}/{len(cogs.all_cogs)}: {cog_module.__name__}")
+ await bot.add_cog(cog_module.Cog(bot))
+ except Exception as e:
+ logger.error(f"Failed to load cog {cog_module.__name__}: {e}")
+ logger.info(f"Loaded all cogs in {time.time() - cog_load_start:.2f} seconds")
+
+ # Calculate startup time
+ logger.info(f"Bot initialization completed in {time.time() - start_time:.2f} seconds")
+
+ if bot.is_dev: # runs the api locally if the bot is in dev mode
+ logger.info(f"Starting development server on port {PORT}")
+ # Use asyncio.create_task instead of deprecated get_event_loop
+ tasks = [bot.start(TOKEN), app.run_task(host="0.0.0.0", port=PORT)]
+ logger.info("Bot is now running in development mode")
+ done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
+ # Cancel any pending tasks
+ for task in pending:
+ task.cancel()
+ else:
+ # Start the bot in production mode
+ logger.info("Starting bot in production mode")
+ await bot.start(TOKEN)
\ No newline at end of file
diff --git a/tests/killua/__main__.py b/tests/killua/__main__.py
new file mode 100644
index 000000000..50947b055
--- /dev/null
+++ b/tests/killua/__main__.py
@@ -0,0 +1,5 @@
+from . import main
+from asyncio import run
+
+if __name__ == "__main__":
+ run(main())
\ No newline at end of file
diff --git a/tests/killua/args.py b/tests/killua/args.py
new file mode 100644
index 000000000..978e91e08
--- /dev/null
+++ b/tests/killua/args.py
@@ -0,0 +1,32 @@
+import argparse
+
+from typing import Optional
+
+class _Args:
+
+ development: Optional[bool] = None
+ migrate: Optional[bool] = None
+ test: Optional[bool] = None
+ log: Optional[str] = None
+
+ @classmethod
+ def get_args(cls) -> None:
+
+ parser = argparse.ArgumentParser(description="CLI arguments for the bot")
+ parser.add_argument("-d", "--development", help="Run the bot in development mode", action="store_const", const=True)
+ parser.add_argument("-m", "--migrate", help="Migrates the database setup from a previous version to the current one", action="store_const", const=True)
+ parser.add_argument("-t", "--test", help="Run the tests", nargs="*", default=None, metavar=("cog", "command"))
+ parser.add_argument("-l", "--log", help="Set the logging level", default="INFO", choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], metavar="level")
+ parser.add_argument("-dl", "--download", help="Download all cards into a file for offline testing", action="store_const", const=True)
+
+ parsed = parser.parse_args()
+
+ cls.development = parsed.development
+ cls.migrate = parsed.migrate
+ cls.test = parsed.test
+ cls.log = parsed.log
+ cls.download = parsed.download
+
+def init():
+ global Args
+ Args = _Args
\ No newline at end of file
diff --git a/tests/killua/bot.py b/tests/killua/bot.py
new file mode 100644
index 000000000..d0b6ec952
--- /dev/null
+++ b/tests/killua/bot.py
@@ -0,0 +1,347 @@
+import logging
+import math
+import asyncio
+import discord
+import jishaku
+import time
+import sys
+
+from typing import Dict, Union, List, Tuple, Coroutine, Any, Optional
+from datetime import date, datetime
+from random import randint, choice
+from discord.ext import commands
+from aiohttp import ClientSession
+
+from killua.static.constants import *
+from killua.static.tips import TIPS
+from killua.utils.db import DB
+from killua.utils.enums import Category
+from killua.utils.functions import get_prefix
+from killua.utils.ui import Modal
+from killua.utils.migrate import migrate_requiring_bot
+
+# Configure root logger
+logging.basicConfig(level=logging.INFO,
+ format='[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s',
+ datefmt='%Y-%m-%d %H:%M:%S')
+
+# Create a logger for this module
+logger = logging.getLogger('killua.bot')
+
+def get_prefix(bot, message):
+ if bot.is_dev:
+ return commands.when_mentioned_or('kil!', 'kil.')(bot, message)
+ try:
+ from .utils.classes import Guild
+
+ g = Guild(message.guild.id)
+ if g is None:
+ return commands.when_mentioned_or('k!')(bot, message)
+ return commands.when_mentioned_or(g.prefix)(bot, message)
+ except Exception:
+ # in case message.guild is `None` or something went wrong getting the prefix the bot still NEEDS to react to mentions and k!
+ return commands.when_mentioned_or('k!')(bot, message)
+
+class BaseBot(commands.AutoShardedBot):
+ def __init__(self, *args, **kwargs):
+ logger.info("Initializing Killua bot...")
+ self.startup_time = time.time()
+
+ # Extract session from kwargs if provided
+ self.session = kwargs.pop('session', None)
+ logger.debug(f"Session provided: {self.session is not None}")
+
+ # Set modern defaults for Discord.py 2.5+
+ kwargs.setdefault('chunk_guilds_at_startup', False)
+ kwargs.setdefault('max_messages', 10000) # Increase message cache for better performance
+ kwargs.setdefault('enable_debug_events', False)
+ kwargs.setdefault('assume_unsync_clock', True) # Better for distributed systems
+
+ logger.info("Calling parent constructor with optimized settings")
+ super().__init__(*args, **kwargs)
+
+ # Bot configuration
+ self.support_server_invite = "https://discord.gg/MKyWA5M"
+ self.invite = "https://discord.com/oauth2/authorize?client_id=756206646396452975&scope=bot%20applications.commands&permissions=268723414"
+ self.is_dev = False
+ logger.info(f"Development mode: {self.is_dev}")
+
+ # Performance optimizations
+ self._command_cache = {}
+ self._formatted_commands_cache = None
+ logger.info("Bot initialization complete")
+
+ async def setup_hook(self):
+ logger.info("Setting up bot hooks and extensions...")
+
+ # Check MongoDB connection first
+ try:
+ logger.info("Testing MongoDB connection...")
+ db_info = DB.const.database.client.server_info()
+ logger.info(f"Connected to MongoDB version: {db_info.get('version', 'unknown')}")
+ except Exception as e:
+ logger.critical(f"MongoDB connection failed: {e}")
+ logger.critical("Please make sure MongoDB is running and the connection string is correct in config.json")
+ logger.critical("Bot cannot start without a database connection. Exiting...")
+ sys.exit(1)
+
+ # Load extensions
+ try:
+ logger.info("Loading jishaku extension...")
+ await self.load_extension("jishaku")
+ logger.info("Successfully loaded jishaku extension")
+ except Exception as e:
+ logger.error(f"Failed to load jishaku: {e}")
+
+ # Sync application commands
+ try:
+ logger.info("Syncing application commands...")
+ await self.tree.sync()
+ logger.info("Successfully synced application commands")
+ except Exception as e:
+ logger.error(f"Failed to sync application commands: {e}")
+
+ # Check for migration
+ try:
+ logger.info("Checking for pending database migrations...")
+ migrate_doc = DB.const.find_one({"_id": "migrate"})
+ if migrate_doc and migrate_doc.get("value", False):
+ logger.info("Running database migration...")
+ migrate_requiring_bot(self)
+ logger.info("Database migration completed successfully")
+ else:
+ logger.info("No pending migrations found")
+ except Exception as e:
+ logger.error(f"Failed to check/run migration: {e}")
+
+ logger.info("Bot setup completed successfully")
+
+ async def close(self):
+ # Clean up resources before closing
+ logger.info("Bot is shutting down, cleaning up resources...")
+
+ # Calculate uptime
+ uptime = time.time() - self.startup_time
+ logger.info(f"Bot was running for {uptime:.2f} seconds")
+
+ # Clear caches
+ logger.debug("Clearing command caches")
+ self._command_cache.clear()
+ self._formatted_commands_cache = None
+
+ # Only close the session if it was created by this instance and not passed in
+ if hasattr(self, 'session') and self.session is not None and not self.session.closed:
+ try:
+ logger.info("Closing HTTP session")
+ await self.session.close()
+ logger.debug("HTTP session closed successfully")
+ except Exception as e:
+ logger.error(f"Error closing session: {e}")
+
+ # Call parent close method
+ logger.info("Calling parent close method")
+ await super().close()
+ logger.info("Bot shutdown complete")
+
+ def __format_command(self, res: Dict[str, list], cmd: commands.Command) -> dict:
+ """Adds a command to a dict of formatted commands"""
+ if cmd.name in ["jishaku", "help"] or cmd.hidden:
+ return res
+
+ res[cmd.extras["category"].value["name"]]["commands"].append(cmd)
+
+ return res
+
+ def get_formatted_commands(self) -> dict:
+ """Gets a dictionary of formatted commands with caching for better performance"""
+ # Return cached result if available
+ if self._formatted_commands_cache is not None:
+ return self._formatted_commands_cache
+
+ # Initialize result dictionary
+ res = {c.value["name"]: {"description": c.value["description"], "emoji": c.value["emoji"], "commands": []} for c in Category}
+
+ # Process commands
+ for cmd in self.commands:
+ if isinstance(cmd, commands.Group) and cmd.name != "jishaku":
+ for c in cmd.commands:
+ res = self.__format_command(res, c)
+ continue
+ res = self.__format_command(res, cmd)
+
+ # Cache the result
+ self._formatted_commands_cache = res
+ return res
+
+ async def find_user(self, ctx: commands.Context, user: str) -> Union[discord.Member, discord.User, None]:
+ """Attempts to create a member or user object from the passed string
+ Optimized for Python 3.11 with better error handling"""
+ # Check if input is empty
+ if not user:
+ return None
+
+ # Try to convert to member first (most common case)
+ try:
+ return await commands.MemberConverter().convert(ctx, user)
+ except commands.MemberNotFound:
+ pass
+
+ # If not a digit ID, return None
+ if not user.isdigit():
+ return None
+
+ # Try to get from cache first (faster)
+ user_id = int(user)
+ res = self.get_user(user_id)
+ if res:
+ return res
+
+ # Fetch from API as last resort
+ try:
+ return await self.fetch_user(user_id)
+ except (discord.NotFound, discord.HTTPException):
+ return None
+
+ def get_lootbox_from_name(self, name: str) -> Union[int, None]:
+ """Gets a lootbox id from its name"""
+ for k, v in LOOTBOXES.items():
+ if name.lower() == v["name"].lower():
+ return k
+
+ def callback_from_command(self, command: Coroutine, message: bool, *args, **kwargs) -> Coroutine[discord.Interaction, Union[discord.Member, discord.Message], None]:
+ """Turn a command function into a context menu callback"""
+ if message:
+ async def callback(interaction: discord.Interaction, message: discord.Message):
+ ctx = await commands.Context.from_interaction(interaction)
+ ctx.message = message
+ ctx.invoked_by_context_menu = True # This is added so we can check inside of the command if it was invoked from a modal
+ await ctx.invoke(command, text=message.content, *args, **kwargs)
+ else:
+ async def callback(interaction: discord.Interaction, member: discord.Member):
+ ctx = await commands.Context.from_interaction(interaction)
+ ctx.invoked_by_context_menu = True
+ await ctx.invoke(command, str(member.id), *args, **kwargs)
+ return callback
+
+ async def get_text_response(
+ self,
+ ctx: commands.Context,
+ text: str,
+ timeout: int = None,
+ timeout_message: str = None,
+ interaction: discord.Interaction = None,
+ *args,
+ **kwargs
+ ) -> Union[str, None]:
+ """Gets a reponse from either a textinput UI or by waiting for a response"""
+
+ if (ctx.interaction and not ctx.interaction.response.is_done()) or interaction:
+ modal = Modal(title="Anser the question(s) and click submit", timeout=timeout)
+ textinput = discord.ui.TextInput(label=text, *args, **kwargs)
+ modal.add_item(textinput)
+
+ if interaction:
+ await interaction.response.send_modal(modal)
+ else:
+ await ctx.interaction.response.send_modal(modal)
+
+ await modal.wait()
+ if modal.timed_out:
+ if timeout_message:
+ await ctx.send(timeout_message, delete_after=5)
+ return
+ await modal.interaction.response.defer()
+
+ return textinput.value
+
+ else:
+ def check(m: discord.Message):
+ return m.author.id == ctx.author.id
+
+ msg = await ctx.send(text)
+ try:
+ confirmmsg: discord.Message = await self.wait_for('message', check=check, timeout=timeout)
+ except asyncio.TimeoutError:
+ if timeout_message:
+ await ctx.send(timeout_message, delete_after=5)
+ res = None
+ else:
+ res = confirmmsg.content
+
+ await msg.delete()
+ try:
+ await confirmmsg.delete()
+ except commands.Forbidden:
+ pass
+
+ return res
+
+ async def update_presence(self):
+ """Update the bot's presence with improved error handling and caching"""
+ logger.debug("Updating bot presence...")
+ try:
+ # Try to get custom presence from database
+ logger.debug("Fetching presence data from database")
+ status = DB.const.find_one({"_id": "presence"})
+ if status and status.get('text'):
+ logger.info(f"Using custom presence: {status['text']}")
+ # Set defaults if missing
+ activity_type = status.get('activity', 'playing')
+ presence_status = status.get('presence', 'online')
+
+ # Create activity object
+ activity = discord.Activity(
+ name=status['text'],
+ type=getattr(discord.ActivityType, activity_type)
+ )
+
+ # Update presence
+ logger.debug(f"Setting presence: {activity.name} ({activity.type.name})")
+ await self.change_presence(
+ activity=activity,
+ status=getattr(discord.Status, presence_status)
+ )
+ return
+
+ # Calculate bot age
+ today = date.today()
+ bot_birthday = date(2020, 9, 17) # The day Killua was born!!
+ days_running = (today - bot_birthday).days
+
+ # Create default activity
+ logger.info(f"Using default presence for {len(self.guilds)} guilds")
+ playing = discord.Activity(
+ name=f'over {len(self.guilds)} guilds | k! | day {days_running}',
+ type=discord.ActivityType.watching
+ )
+
+ # Update presence
+ logger.debug(f"Setting default presence: {playing.name}")
+ await self.change_presence(status=discord.Status.online, activity=playing)
+ logger.info("Presence updated successfully")
+ except Exception as e:
+ logger.error(f"Failed to update presence: {e}")
+
+ async def send_message(self, messageable: discord.abc.Messageable, *args, **kwargs) -> discord.Message:
+ """A helper function sending messages and adding a tip with the probability of 5%"""
+ msg = await messageable.send(*args, **kwargs)
+ if randint(1, 100) < 6: # 5% probability to send a tip afterwards
+ await messageable.send(f"**Tip:** {choice(TIPS).replace('', get_prefix(self, messageable.message)[2]) if hasattr(messageable, 'message') else ('k!' if not self.is_dev else 'kil!')}", ephemeral=True)
+ return msg
+
+ def convert_to_timestamp(self, id: int, args: str = "f") -> str:
+ """Turns a discord snowflake into a discord timestamp string"""
+ return f"> 22) / 1000) + 1420070400}:{args}>"
+
+ def _encrypt(self, n: int, b: int = 10000, smallest: bool = True) -> str:
+ """Changes an integer into base 10000 but with my own characters resembling numbers. It only returns the last 2 characters as they are the most unique"""
+ chars = "".join([chr(i) for i in range(b+1)][::-1])
+ chars = chars.replace(":", "").replace(";", "").replace("-", "").replace(",", "") # These characters are indicators used in the ids so they should be not be available as characters
+
+ if n == 0:
+ return [0]
+ digits = []
+ while n:
+ digits.append(int(n % b))
+ n //= b
+ return "".join([chars[d] for d in digits[::-1]])[-2:] if smallest else "".join([chars[d] for d in digits[::-1]])
\ No newline at end of file
diff --git a/tests/killua/cogs/__init__.py b/tests/killua/cogs/__init__.py
new file mode 100644
index 000000000..429b5ae99
--- /dev/null
+++ b/tests/killua/cogs/__init__.py
@@ -0,0 +1,16 @@
+from importlib.abc import MetaPathFinder
+import pkgutil
+
+# This module's submodules.
+all_cogs = []
+
+for loader, name, pkg in pkgutil.walk_packages(__path__):
+ # Load the module.
+ loader = loader.find_module(name, None) \
+ if isinstance(loader, MetaPathFinder) else loader.find_module(name)
+ module = loader.load_module(name)
+
+ # Make it a global.
+ globals()[name] = module
+ # Put it in the list.
+ all_cogs.append(module)
diff --git a/tests/killua/cogs/actions.py b/tests/killua/cogs/actions.py
new file mode 100644
index 000000000..57776bb9f
--- /dev/null
+++ b/tests/killua/cogs/actions.py
@@ -0,0 +1,295 @@
+import discord
+from discord.ext import commands
+import random
+import asyncio
+from typing import List, Union
+
+from killua.bot import BaseBot
+from killua.utils.checks import check
+from killua.utils.classes import User
+from killua.static.enums import Category
+from killua.utils.interactions import View
+from killua.static.constants import ACTIONS
+
+class SettingsSelect(discord.ui.Select):
+ """Creates a select menu to change action settings"""
+ def __init__(self, options, **kwargs):
+ super().__init__(
+ options=options,
+ **kwargs
+ )
+
+ async def callback(self, interaction: discord.Interaction):
+ self.view.values = interaction.data["values"]
+ for opt in self.options:
+ if opt.value in self.view.values:
+ opt.default = True
+
+class SettingsButton(discord.ui.Button):
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ async def callback(self, interaction: discord.Interaction):
+ if not hasattr(self.view, "values"):
+ return await interaction.response.send_message("You have not changed any settings", ephemeral=True)
+ self.view.timed_out = False
+ self.view.stop()
+
+class Actions(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+ self.session = self.client.session
+
+ async def request_action(self, endpoint: str) -> Union[dict, str]:
+
+ r = await self.session.get(f"https://purrbot.site/api/img/sfw/{endpoint}/gif")
+ if r.status == 200:
+ res = await r.json()
+
+ if res["error"]:
+ return res["message"]
+
+ return res
+ else:
+ return await r.text()
+
+ async def get_image(self, ctx) -> discord.Message: # for endpoints like /blush/gif where you don't want to mention a user
+ image = await self.request_action(ctx.command.name)
+ if isinstance(image, str):
+ return await ctx.send(f':x: {image}')
+ embed = discord.Embed.from_dict({
+ "title": "",
+ "image": {"url": image["link"]},
+ "color": 0x1400ff
+ })
+ return await ctx.send(embed=embed)
+
+ def generate_users(self, members: list, title: str) -> str:
+ if isinstance(members, str):
+ return members
+ memberlist = ''
+ for p, member in enumerate(members):
+ if len(memberlist + member.display_name + title.replace("(a)", "").replace("(u)", "")) > 231: # embed titles have a max lentgh of 256 characters. If the name list contains too many names, stuff breaks. This prevents that and displays the other people as "and x more"
+ memberlist = memberlist + f" *and {len(members)-(p+1)} more*"
+ break
+ if members[-1] == member and len(members) != 1:
+ memberlist = memberlist + f' and {member.display_name}'
+ else:
+ if members[0] == member:
+ memberlist = f'{member.display_name}'
+ else:
+ memberlist = memberlist + f', {member.display_name}'
+ return memberlist
+
+ async def action_embed(self, endpoint: str, author: Union[str, discord.User], members: List[discord.Member], disabled: int = 0) -> discord.Embed:
+ if disabled == len(members):
+ return "All members targetted have disabled this action."
+
+ if endpoint == 'hug':
+ image = {"link": random.choice(ACTIONS[endpoint]["images"])} # This might eventually be deprecated for copyright reasons
+ else:
+ image = await self.request_action(endpoint)
+ if isinstance(image, str):
+ return f':x: {image}'
+
+ text = random.choice(ACTIONS[endpoint]["text"])
+ text = text.replace("", "**" + (author if isinstance(author, str) else author.name) + "**").replace("", "**" + self.generate_users(members, text) + "**")
+
+ embed = discord.Embed.from_dict({
+ "title": text,
+ "image": {"url": image["link"]},
+ "color": 0x1400ff
+ })
+
+ if disabled > 0:
+ embed.set_footer(text=f"{disabled} user{'s' if disabled > 1 else ''} disabled being targetted with this action")
+ return embed
+
+ async def no_argument(self, ctx) -> Union[None, discord.Embed]:
+ await ctx.send(f'You provided no one to {ctx.command.name}.. Should- I {ctx.command.name} you?')
+ def check(m):
+ return m.content.lower() == 'yes' and m.author == ctx.author
+ try:
+ await self.client.wait_for('message', check=check, timeout=60)
+ except asyncio.TimeoutError:
+ pass
+ else:
+ return await self.action_embed(ctx.command.name, 'Killua', ctx.author.name)
+
+ async def do_action(self, ctx, members: List[discord.Member] = None) -> Union[discord.Message, None]:
+ if not members:
+ embed = await self.no_argument(ctx)
+ if not embed:
+ return
+ elif ctx.author == members[0]:
+ return await ctx.send("Sorry... you can\'t use this command on yourself")
+ else:
+ first = User(members[0].id)
+ if len(members) == 1 and (ctx.command.name in first.action_settings) and not first.action_settings[ctx.command.name]:
+ return await ctx.send(f"**{members[0].display_name}** has disabled this action", allowed_mentions=discord.AllowedMentions.none())
+
+ allowed = []
+ disabled = 0
+ for member in members:
+ m = User(member.id)
+ if m.action_settings and ctx.command.name in m.action_settings and m.action_settings[ctx.command.name] is False:
+ disabled+=1
+ else:
+ allowed.append(member)
+ embed = await self.action_embed(ctx.command.name, ctx.author, members, disabled)
+
+ if isinstance(embed, str):
+ return await ctx.send(content=embed)
+ else:
+ return await ctx.bot.send_message(ctx, embed=embed)
+
+ @commands.hybrid_group()
+ async def action(self, _: commands.Context) -> None:
+ """A collection of commands to express feeling through images and gifs"""
+ ...
+
+ @check()
+ @action.command(extras={"category": Category.ACTIONS}, usage="hug ")
+ @discord.app_commands.describe(members="The people to hug")
+ async def hug(self, ctx: commands.Context, members: commands.Greedy[discord.Member] = None):
+ """Hug a user with this command"""
+ return await self.do_action(ctx, members)
+
+ @check()
+ @action.command(extras={"category":Category.ACTIONS}, usage="pat ")
+ @discord.app_commands.describe(members="The people to pat")
+ async def pat(self, ctx: commands.Context, members: commands.Greedy[discord.Member] = None):
+ """Pat a user with this command"""
+ return await self.do_action(ctx, members)
+
+ @check()
+ @action.command(extras={"category":Category.ACTIONS}, usage="poke ")
+ @discord.app_commands.describe(members="The people to poke")
+ async def poke(self, ctx: commands.Context, members: commands.Greedy[discord.Member] = None):
+ """Poke a user with this command"""
+ return await self.do_action(ctx, members)
+
+ @check()
+ @action.command(extras={"category":Category.ACTIONS}, usage="tickle ")
+ @discord.app_commands.describe(members="The people to tickle")
+ async def tickle(self, ctx: commands.Context, members: commands.Greedy[discord.Member] = None):
+ """Tickle a user wi- ha- hahaha- stop- haha"""
+ return await self.do_action(ctx, members)
+
+ @check()
+ @action.command(extras={"category":Category.ACTIONS}, usage="slap ")
+ @discord.app_commands.describe(members="The people to slap")
+ async def slap(self, ctx: commands.Context, members: commands.Greedy[discord.Member] = None):
+ """Slap a user with this command"""
+ return await self.do_action(ctx, members)
+
+ @check()
+ @action.command(extras={"category": Category.ACTIONS}, usage="cuddle")
+ @discord.app_commands.describe(members="The people to cuddle with")
+ async def cuddle(self, ctx: commands.Context, members: commands.Greedy[discord.Member] = None):
+ """Snuggle up to a user and cuddle them with this command"""
+ return await self.do_action(ctx, members)
+
+ @check()
+ @action.command(extras={"category": Category.ACTIONS}, usage="dance")
+ async def dance(self, ctx: commands.Context):
+ """Show off your dance moves!"""
+ return await self.get_image(ctx)
+
+ @check()
+ @action.command(extras={"category": Category.ACTIONS}, usage="neko")
+ async def neko(self, ctx: commands.Context):
+ """uwu"""
+ return await self.get_image(ctx)
+
+ @check()
+ @action.command(extras={"category": Category.ACTIONS}, usage="smile")
+ async def smile(self, ctx: commands.Context):
+ """Show a bright smile with this command"""
+ return await self.get_image(ctx)
+
+ @check()
+ @action.command(extras={"category": Category.ACTIONS}, usage="blush")
+ async def blush(self, ctx: commands.Context):
+ """O-Oh! T-thank you for t-the compliment... You have beautiful fingernails too!"""
+ return await self.get_image(ctx)
+
+ @check()
+ @action.command(extras={"category": Category.ACTIONS}, usage="tail")
+ async def tail(self, ctx: commands.Context):
+ """Wag your tail when you're happy!"""
+ return await self.get_image(ctx)
+
+ def _get_view(self, id: int, current: dict) -> View:
+ options = [discord.SelectOption(label=k, value=k, default=v) for k, v in current.items()]
+ select = SettingsSelect(options, min_values=0, max_values=len(current), custom_id="select")
+ button = SettingsButton(label="Save", style=discord.ButtonStyle.green, emoji="\U0001f4be", custom_id="save")
+ view = View(user_id=id, timeout=100)
+ view.timed_out = True
+
+ view.add_item(select)
+ view.add_item(button)
+
+ return view
+
+ @check()
+ @action.command(extras={"category": Category.ACTIONS}, usage="settings")
+ async def settings(self, ctx: commands.Context):
+ """Change the settings that control who can use what action on you"""
+
+ embed = discord.Embed.from_dict({
+ "title": "Settings",
+ "description": "By unticking a box users will no longer able to use that action on you",
+ "color": 0x1400ff
+ })
+
+ user = User(ctx.author.id)
+ current = user.action_settings
+
+ for action in ACTIONS.keys():
+ if action in current:
+ embed.add_field(name=action, value="â
" if current[action] else "â", inline=False)
+ else:
+ embed.add_field(name=action, value="â
", inline=False)
+ current[action] = True
+
+ view = self._get_view(ctx.author.id, current)
+
+ msg = await ctx.send(embed=embed, view=view)
+
+ await view.wait()
+
+ if view.timed_out:
+ return await view.disable(msg)
+
+ for val in view.values:
+ current[val] = True
+
+ while True:
+ embed.clear_fields()
+
+ for action in ACTIONS.keys():
+ if action in view.values:
+ current[action] = True
+ embed.add_field(name=action, value="â
", inline=False)
+ else:
+ current[action] = False
+ embed.add_field(name=action, value="â", inline=False)
+
+ user.set_action_settings(current)
+ view = self._get_view(ctx.author.id, current)
+
+ await msg.edit(embed=embed, view=view)
+
+ await view.wait()
+
+ if view.timed_out:
+ return await view.disable(msg)
+
+ for val in view.values:
+ current[val] = True
+
+
+Cog = Actions
\ No newline at end of file
diff --git a/tests/killua/cogs/api.py b/tests/killua/cogs/api.py
new file mode 100644
index 000000000..2285d5012
--- /dev/null
+++ b/tests/killua/cogs/api.py
@@ -0,0 +1,118 @@
+import discord
+from discord.ext import commands
+
+from asyncio import create_task
+from zmq import REP, POLLIN, NOBLOCK
+from zmq.asyncio import Context, Poller
+from zmq.auth.asyncio import AsyncioAuthenticator
+
+from killua.bot import BaseBot
+from killua.utils.classes import User, Guild, LootBox
+from killua.static.constants import DB, LOOTBOXES, IPC_TOKEN
+
+from typing import List
+
+class IPCRoutes(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+ create_task(self.start())
+
+ async def start(self):
+ """Starts the zmq server asyncronously and handles incoming requests"""
+ context = Context()
+
+ auth = AsyncioAuthenticator(context)
+ auth.start()
+ auth.configure_plain(domain="*", passwords={"killua": IPC_TOKEN})
+ auth.allow("127.0.0.1")
+
+ socket = context.socket(REP)
+ socket.plain_server = True
+ socket.bind("tcp://*:5555")
+
+ poller = Poller()
+ poller.register(socket, POLLIN)
+
+ while True:
+ socks = dict(await poller.poll())
+
+ if socket in socks and socks[socket] == POLLIN:
+ message = await socket.recv_json(NOBLOCK)
+ res = await getattr(self, message["route"])(message["data"])
+ if res:
+ socket.send_json(res)
+ else:
+ socket.send_json({"status": "ok"})
+
+ def _get_reward(self, user: User, weekend: bool) -> int:
+ """A pretty simple algorithm that adjusts the reward for voting"""
+ if user.votes % 5 == 0:
+ return LootBox.get_random_lootbox()
+ if user.votes*2 > 100:
+ reward = int((user.votes*2)/100)*(150 if weekend else 100)
+ else:
+ reward = 100
+ return reward
+
+ async def handle_vote(self, data: dict) -> None:
+ user_id = data["user"] if "user" in data else data["id"]
+
+ user = User(int(user_id))
+ user.add_vote()
+ reward = self._get_reward(user, data["isWeekend"] if hasattr(data, "isWeekend") else False)
+
+ if reward < 100:
+ user.add_lootbox(reward)
+ text = f"Thank you for voting for Killua! This time you get a :sparkles: special :sparkles: reward: the lootbox {LOOTBOXES[reward]['emoji']} {LOOTBOXES[reward]['name']}. Open it with `/economy open`"
+ else:
+ text = f"Thank you for voting for Killua! Here take {reward} Jenny as a sign of my gratitude. {5-user.votes%5} vote{'s' if 5-user.votes%5 > 1 else ''} away from a :sparkles: special :sparkles: reward"
+ user.add_jenny(reward)
+
+ usr = self.client.get_user(user_id) or await self.client.fetch_user(user_id)
+
+ try:
+ await usr.send(text)
+ except discord.HTTPException:
+ pass
+
+ async def top(self, _) -> List[dict]:
+ """Returns a list of the top 50 users by the amount of jenny they have"""
+ members = DB.teams.find({'id': {'$in': [x.id for x in self.client.users]} })
+ top = sorted(members, key=lambda x: x['points'], reverse=True)[:50]
+ res = []
+ for t in top:
+ u = self.client.get_user(t["id"])
+ res.append({"name": u.name, "tag": u.discriminator, "avatar": str(u.avatar.url), "jenny": t["points"]})
+ return res
+
+ async def commands(self, _) -> dict:
+ """Returns all commands with descriptions etc"""
+ return self.client.get_formatted_commands()
+
+ async def save_user(self, data) -> None:
+ """This functions purpose is not that much getting user data but saving a user in the database"""
+ User(data["user"])
+
+ async def get_discord_user(self, data) -> dict:
+ """Getting additional info about a user with their id"""
+ res = self.client.get_user(data["user"])
+ return {"name": res.name, "tag": res.discriminator, "avatar": str(res.avatar.url), "created_at": res.created_at.strftime('%Y-%m-%dT%H:%M:%SZ')}
+
+ async def get_guild_data(self, data) -> dict:
+ """Getting some info about guild roles and channels for black and whitelisting"""
+ res = self.client.get_guild(int(data["guild"]))
+ return {"roles": [{"name": r.name, "id": str(r.id), "color": r.color.value} for r in res.roles], "channels": [{"name": c.name, "id": c.id} for c in res.channels if isinstance(c, discord.TextChannel)]}
+
+ async def update_guild_cache(self, data) -> None:
+ """Makes sure the local cache is up to date with the db"""
+ guild = Guild(data.id)
+ guild.prefix = data["prefix"]
+ guild.commands = {v for _, v in data.commands.items()}
+
+ async def vote(self, data) -> None:
+ """Registers a vote from either topgg or dbl"""
+ await self.handle_vote(data)
+
+
+Cog = IPCRoutes
\ No newline at end of file
diff --git a/tests/killua/cogs/cards.py b/tests/killua/cogs/cards.py
new file mode 100644
index 000000000..97c307215
--- /dev/null
+++ b/tests/killua/cogs/cards.py
@@ -0,0 +1,632 @@
+import discord
+import math
+import random
+from discord.ext import commands
+from datetime import datetime
+
+from typing import Union, List, Optional, Tuple, Optional, Dict
+
+from killua.bot import BaseBot
+from killua.utils.checks import check
+from killua.utils.paginator import Paginator
+from killua.utils.classes import User, CardNotFound, CheckFailure, Book, NoMatches
+from killua.static.enums import Category, HuntOptions, Items, SellOptions
+from killua.utils.interactions import ConfirmButton
+from killua.static.cards import Card
+from killua.static.constants import ALLOWED_AMOUNT_MULTIPLE, FREE_SLOTS, DEF_SPELLS, VIEW_DEF_SPELLS, PRICES, BOOK_PAGES, LOOTBOXES, DB
+
+
+class Cards(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+ self.cardname_cache = {}
+ self.reward_cache = {
+ "item": [x["_id"] for x in DB.items.find({"type": "normal", "rank": { "$in": ["A", "B", "C"]}})],
+ "spell": [x["_id"] for x in DB.items.find({"type": "spell", "rank": { "$in": ["B", "C"]}})],
+ "monster": {
+ "E": [x["_id"] for x in DB.items.find({"type": "monster", "rank": {"$in": ["E", "G", "H"]}})],
+ "D": [x["_id"] for x in DB.items.find({"type": "monster", "rank": {"$in": ["D", "E", "F"]}})],
+ "C": [x["_id"] for x in DB.items.find({"type": "monster", "rank": {"$in": ["C", "D", "E"]}})]
+ }
+ }
+ self._init_menus()
+
+ def _init_menus(self) -> None:
+ menus = []
+ menus.append(discord.app_commands.ContextMenu(
+ name='meet',
+ callback=self.client.callback_from_command(self.meet, message=False)
+ ))
+
+ for menu in menus:
+ try:
+ self.client.tree.add_command(menu)
+ except discord.app_commands.errors.CommandAlreadyRegistered:
+ pass # Ignoring this
+
+ async def all_cards_autocomplete(
+ self,
+ interaction: discord.Interaction,
+ current: str,
+ ) -> List[discord.app_commands.Choice[str]]:
+ """Autocomplete for all cards"""
+ if not self.cardname_cache:
+ for card in DB.items.find({}):
+ self.cardname_cache[card["_id"]] = card["name"], card["type"]
+
+ name_cards = [(x[0], self.cardname_cache[x[0]][0]) for x in User(interaction.user.id).all_cards if self.cardname_cache[x[0]][0].lower().startswith(current.lower())]
+ id_cards = [(x[0], self.cardname_cache[x[0]][0]) for x in User(interaction.user.id).all_cards if str(x[0]).startswith(current)]
+ name_cards = list(dict.fromkeys(name_cards))
+ id_cards = list(dict.fromkeys(id_cards)) # removing all duplicates from the list
+
+ if current == "": # No ids AND names if the user hasn"t typed anything yet
+ return [discord.app_commands.Choice(name=x[1], value=str(x[0])) for x in name_cards]
+ return [*[discord.app_commands.Choice(name=n, value=str(i)) for i, n in name_cards], *[discord.app_commands.Choice(name=str(i), value=str(i)) for i, _ in id_cards]]
+
+ def _get_single_reward(self, score:int) -> Tuple[int, int]:
+ if score == 1:
+ if random.randint(1, 10) < 5:
+ return 1, random.choice(self.reward_cache["item"])
+ else:
+ return 1, random.choice(self.reward_cache["spell"])
+
+ if score < 3000/10000:
+ rarities = "E"
+ elif score < 7000/10000:
+ rarities = "D"
+ else:
+ rarities = "C"
+
+ amount = random.randint(1, math.ceil(score*10))
+ card = random.choice(self.reward_cache["monster"][rarities])
+ return amount, card
+
+ def _construct_rewards(self, score:int) -> List[Tuple[int, int]]:
+ # reward_score will be minutes/10080 which equals a week. Max rewards will get returned once a user has hunted for a week
+ rewards: List[Tuple[int, int]] = []
+
+ if score >= 1:
+ rewards.append(self._get_single_reward(1))
+ score = 0.7
+
+ for _ in range(math.ceil(random.randint(1, math.ceil(score*10))/1.6)):
+ r = self._get_single_reward(score)
+ rewards.append(r)
+
+ final_rewards: List[Tuple[int, int]] = []
+ for reward in rewards:
+ # This avoid duplicates e.g. 4xPaladins Necklace, 2xPaladins Necklace => 6xPaladins Necklace
+ if reward[1] in (l:= [y for _, y in final_rewards]):
+ index = l.index(reward[1])
+ final_rewards[index] = (final_rewards[index][0]+reward[0], final_rewards[index][1])
+ else:
+ final_rewards.append(reward)
+ return final_rewards
+
+ def _format_rewards(self, rewards:List[Tuple[int, int]], user:User) -> Tuple[List[list], List[str], bool]:
+ """Formats the generated rewards for further use"""
+ formatted_rewards: List[List[int, Dict[str, bool]]] = []
+ formatted_text: List[str] = []
+
+ maxed = False
+ for pos, reward in enumerate(rewards):
+ for i in range(reward[0]):
+ if len([*user.fs_cards,*[x for x in rewards if x[1] > 99 and not user.has_rs_card(x[0])]]) >= 40 and (reward[1] > 99 or (not user.has_rs_card(reward[1]) and reward[1] < 100)):
+ # return formatted_rewards, formatted_text, True # if the free slots are full the process stops
+ maxed = (pos, i) # Returning the exact position where the cards are too much
+ else:
+ formatted_rewards.append([reward[1], {"fake": False, "clone": False}])
+ card = Card(reward[1])
+ if maxed:
+ if not maxed[1] == 0: # If there isn"t 0 of that card that will be added
+ formatted_text.append(f"{maxed[1]}x **{card.name}**{card.emoji}")
+ else:
+ formatted_text.append(f"{reward[0]}x **{card.name}**{card.emoji}")
+
+ return formatted_rewards, formatted_text, maxed
+
+ @commands.hybrid_group()
+ async def cards(self, _: commands.Context):
+ """Commands mimicing the greed island arc of hxh"""
+ ...
+
+ @check(3)
+ @commands.bot_has_permissions(attach_files=True, embed_links=True)
+ @cards.command(extras={"category":Category.CARDS}, usage="book ")
+ @discord.app_commands.describe(page="The page of the book to see")
+ async def book(self, ctx: commands.Context, page: int = 1):
+ """Allows you to take a look at your cards"""
+ user = User(ctx.author.id)
+
+ if len(user.all_cards) == 0:
+ return await ctx.send("You don't have any cards yet!")
+
+ if page:
+ if page > 7+math.ceil(len(user.fs_cards)/18) or page < 1:
+ return await ctx.send(f"Please choose a page number between 1 and {6+math.ceil(len(user.fs_cards)/18)}")
+
+ async def make_embed(page, *_) -> Tuple[discord.Embed, discord.File]:
+ return await Book(self.client.session).create(ctx.author, page)
+ return await Paginator(ctx, page=page, func=make_embed, max_pages=6+math.ceil(len(user.fs_cards)/18), has_file=True).start()
+
+ @check(2)
+ @cards.command(extras={"category":Category.CARDS}, usage="sell ")
+ @discord.app_commands.describe(
+ card="The card to sell",
+ type="The type of card to bulk sell",
+ amount="The amount of the specified card to sell"
+ )
+ @discord.app_commands.autocomplete(card=all_cards_autocomplete)
+ async def sell(self, ctx: commands.Context, card: str = None, type: SellOptions = None, amount: int = 1):
+ """Sell any amount of cards you own"""
+
+ user = User(ctx.author.id)
+
+ if not type and not card:
+ return await ctx.send("You need to specify what exactly to sell", ephemeral=True)
+
+ if type: # always prefers if a type argument was given. However if both a type argument and card argument was given,
+ # both will be attempted to be executed.
+ if type.name == "all":
+ to_be_sold = [x for x in user.fs_cards if not x[1]["clone"] and not x[1]["fake"]]
+ elif type.name == "spells":
+ to_be_sold = [x for x in user.fs_cards if Card(x[0]).type == "spell" and not x[1]["clone"] and not x[1]["fake"]]
+ elif type.name == "monsters":
+ to_be_sold = [x for x in user.fs_cards if Card(x[0]).type == "monster"and not x[1]["clone"] and not x[1]["fake"]]
+ else: to_be_sold = []
+
+ to_be_gained = 0
+
+ for c, _ in to_be_sold:
+ j = int(PRICES[Card(c).rank]/10)
+ if user.is_entitled_to_double_jenny:
+ j *= 2
+ to_be_gained += j
+
+ if to_be_gained == 0:
+ return await ctx.send("You don't have any cards of that type to sell!", ephemeral=True)
+
+ view = ConfirmButton(ctx.author.id, timeout=80)
+ msg = await ctx.send(f"You will receive {to_be_gained} Jenny for selling all {type.name if not type.name == 'all' else 'free slots'} cards, do you want to proceed?", view=view)
+ await view.wait()
+ await view.disable(msg)
+
+ if not view.value:
+ if view.timed_out:
+ return await ctx.send(f"Timed out!")
+ else:
+ return await ctx.send(f"Successfully canceled!")
+ else:
+ user.bulk_remove(to_be_sold)
+ user.add_jenny(to_be_gained)
+ return await ctx.send(f"You sold all your {type.name if not type.name == 'all' else 'free slots cards'} for {to_be_gained} Jenny!")
+ if not card:
+ return
+
+ if amount < 1:
+ amount = 1
+ if len(user.all_cards) == 0:
+ return await ctx.send("You don't have any cards yet!")
+ try:
+ card = Card(card)
+ except CardNotFound:
+ return await ctx.send(f"A card with the id `{card}` does not exist", allowed_mentions=discord.AllowedMentions.none())
+
+ in_possesion = user.count_card(card.id, including_fakes=False)
+
+ if in_possesion < amount:
+ return await ctx.send(f"Seems you don't own enough copies of this card. You own {in_possesion} cop{'y' if in_possesion == 1 else 'ies'} of this card")
+
+ if card == 0:
+ return await ctx.send("You cannot sell this card!")
+
+ jenny = int((PRICES[card.rank]*amount)/10)
+ if user.is_entitled_to_double_jenny:
+ jenny *= 2
+ view = ConfirmButton(ctx.author.id, timeout=80)
+ msg = await ctx.send(f"You will receive {jenny} Jenny for selling {'this card' if amount == 1 else 'those cards'}, do you want to proceed?", view=view)
+ await view.wait()
+ await view.disable(msg)
+
+ if not view.value:
+ if view.timed_out:
+ return await ctx.send(f"Timed out!")
+ else:
+ return await ctx.send(f"Successfully canceled!")
+
+ for _ in range(amount):
+ user.remove_card(card.id, False)
+ user.add_jenny(jenny)
+ await ctx.send(f"Successfully sold {amount} cop{'y' if amount == 1 else 'ies'} of card {card.id} for {jenny} Jenny!")
+
+ async def swap_cards_autocomplete(
+ self,
+ interaction: discord.Interaction,
+ current: str,
+ ) -> List[discord.app_commands.Choice[str]]:
+ """Autocomplete for the swap command"""
+
+ if not self.cardname_cache:
+ for card in DB.items.find({}):
+ self.cardname_cache[card["_id"]] = card["name"], card["type"]
+
+ user = User(interaction.user.id)
+ name_cards = [(x[0], self.cardname_cache[x[0]][0]) for x in user.all_cards if self.cardname_cache[x[0]][0].lower().startswith(current.lower())]
+ id_cards = [(x[0], self.cardname_cache[x[0]][0]) for x in user.all_cards if str(x[0]).startswith(current)]
+
+ name_duplicates = []
+ id_duplicates = []
+ for id, name in name_cards:
+ if user.can_swap(id) and (id, name) not in name_duplicates:
+ name_duplicates.append((id, name))
+
+ for id, name in id_cards:
+ if user.can_swap(id) and (id, name) not in id_duplicates:
+ id_duplicates.append((id, name))
+
+ if current == "": # No ids AND names if the user hasn"t typed anything yet
+ return [discord.app_commands.Choice(name=x[1], value=str(x[0])) for x in name_duplicates]
+ return [*[discord.app_commands.Choice(name=n, value=str(i)) for i, n in name_duplicates], *[discord.app_commands.Choice(name=str(i), value=str(i)) for i, _ in id_duplicates]]
+
+ @check(20)
+ @cards.command(extras={"category":Category.CARDS}, usage="swap ")
+ @discord.app_commands.describe(card="The card to swap out")
+ @discord.app_commands.autocomplete(card=swap_cards_autocomplete)
+ async def swap(self, ctx: commands.Context, card: str):
+ """Allows you to swap cards from your free slots with the restricted slots and the other way around"""
+
+ user = User(ctx.author.id)
+ if len(user.all_cards) == 0:
+ return await ctx.send("You don't have any cards yet!")
+ try:
+ card = Card(card)
+ except CardNotFound:
+ return await ctx.send("Please use a valid card number!")
+
+ if card.id == 0:
+ return await ctx.send("You cannot swap out card No. 0!")
+
+ sw = user.swap(card.id)
+
+ if sw is False:
+ return await ctx.send(f"You don't own a fake and real copy of card `{card.name}` you can swap out!")
+
+ await ctx.send(f"Successfully swapped out card {card.name}")
+
+ @check()
+ @cards.command(extras={"category":Category.CARDS}, usage="hunt ")
+ @discord.app_commands.describe(option="What to do with your hunt")
+ async def hunt(self, ctx: commands.Context, option: HuntOptions = HuntOptions.start):
+ """Go on a hunt! The longer you are on the hunt, the better the rewards!"""
+ option = option.name
+
+ user = User(ctx.author.id)
+ has_effect, value = user.has_effect("hunting")
+
+ if option == "time":
+ if not has_effect:
+ return await ctx.send("You are not on a hunt yet!")
+
+ return await ctx.send(f"You've started hunting .")
+
+ elif option == "end" and has_effect is True:
+ difference = datetime.now() - value
+ if int(difference.seconds/60/60+difference.days*24*60*60) < 12: # I don't think timedelta has an hours or minutes property :c
+ return await ctx.send("You must be at least hunting for twelve hours!")
+
+ await ctx.interaction.response.defer() # The following part may take longer than 3 secons
+
+ minutes = int(difference.seconds/60+difference.days*24*60)
+ score = minutes/10080 # There are 10080 minutes in a week if I'm not completely wrong
+
+ rewards = self._construct_rewards(score)
+ formatted_rewards, formatted_text, hit_limit = self._format_rewards(rewards, user)
+
+ jenny = 0
+ if hit_limit:
+ c, n = hit_limit
+ for pos, card in enumerate(rewards):
+ if pos == c:
+ jenny += PRICES[Card(card[1]).rank] * (card[0]-n)
+ elif pos >= c:
+ jenny += PRICES[Card(card[1]).rank] * card[0]
+
+
+ text = f"You've started hunting . You brought back the following items from your hunt: \n\n"
+
+ if hit_limit:
+ text += f":warning: Your free slot limit has been reached! Make sure you free it up before hunting again. The excess cards have been automatically sold bringing you `{jenny}` Jenny\n\n"
+
+ embed = discord.Embed.from_dict({
+ "title": "Hunt returned!",
+ "description": text + "\n".join(formatted_text),
+ "color": 0x1400ff
+ })
+ user.remove_effect("hunting")
+ user.add_multi(*formatted_rewards)
+ user.add_jenny(jenny)
+ return await ctx.send(embed=embed)
+
+ elif option == "end" and not has_effect:
+ return await ctx.send(f"You aren't on a hunt yet! Start one with `/cards hunt`", allowed_mentions=discord.AllowedMentions.none())
+
+ if has_effect:
+ return await ctx.send(f"You are already on a hunt! Get the results with `/cards hunt end`", allowed_mentions=discord.AllowedMentions.none())
+ user.add_effect("hunting", datetime.now())
+ await ctx.send("You went hunting! Make sure to claim your rewards at least twelve hours from now, but remember, the longer you hunt, the more you get")
+
+ @check(120)
+ @discord.app_commands.describe(user="The user to meet. Must have sent a mesage recently.")
+ @cards.command(aliases=["approach"], extras={"category":Category.CARDS}, usage="meet ")
+ async def meet(self, ctx: commands.Context, user: discord.Member):
+ """Meet a user who has recently sent a message in this channel to enable certain effects"""
+ if hasattr(ctx, "invoked_by_context_menu"):
+ user = await self.client.find_user(ctx, user)
+
+ author = User(ctx.author.id)
+ past_users = list()
+ if user.bot:
+ return await ctx.send("You can't interact with bots with this command", ephemeral=True)
+ async for message in ctx.channel.history(limit=20):
+ if message.author.id not in past_users:
+ past_users.append(message.author.id)
+
+ if not user.id in past_users:
+ return await ctx.send("The user you tried to approach has not send a message in this channel recently", ephemeral=True)
+
+ if user.id in author.met_user:
+ try:
+ await ctx.message.delete()
+ except discord.HTTPException:
+ pass
+ return await ctx.send(f"You already have `{user}` in the list of users you met, {ctx.author.name}", delete_after=2, allowed_mentions=discord.AllowedMentions.none(), ephemeral=True)
+
+ author.add_met_user(user.id)
+ try:
+ await ctx.message.delete()
+ except discord.HTTPException:
+ pass
+ return await ctx.send(f"Done {ctx.author.mention}! Successfully added `{user}` to the list of people you've met", delete_after=5, allowed_mentions=discord.AllowedMentions.none(), ephemeral=hasattr(ctx, "invoked_by_context_menu"))
+
+ @check()
+ @cards.command(extras={"category":Category.CARDS}, usage="discard ")
+ @discord.app_commands.describe(card="The card to discard")
+ @discord.app_commands.autocomplete(card=all_cards_autocomplete)
+ async def discard(self, ctx: commands.Context, card: str):
+ """Discard a card you want to get rid of with this command. Make sure it's in the free slots"""
+
+ user = User(ctx.author.id)
+ try:
+ card = Card(card)
+ except CardNotFound:
+ return await ctx.send("This card does not exist!")
+
+ if not user.has_any_card(card.id):
+ return await ctx.send("You are not in possesion of this card!")
+
+ if card.id == 0:
+ return await ctx.send("You cannot discard this card!")
+
+ view = ConfirmButton(ctx.author.id, timeout=20)
+ msg = await ctx.send(f"Do you really want to throw this card away? (if you want to throw a fake aware, make sure it's in the free slots (unless it's the only copy you own. You can switch cards between free and restricted slots with `{self.client.command_prefix(self.client, ctx.message)[2]}swap `)", view=view, allowed_mentions=discord.AllowedMentions.none())
+ await view.wait()
+ await view.disable(msg)
+
+ if not view.value:
+ if view.timed_out:
+ return await ctx.send(f"Timed out!")
+ else:
+ return await ctx.send(f"Successfully cancelled!")
+
+ try:
+ user.remove_card(card.id, remove_fake=True, restricted_slot=False)
+ # essentially here it first looks for fakes in your free slots and tried to remove them. If it doesn't find any fakes in the free slots, it will remove the first match of the card it finds in free or restricted slots
+ except NoMatches:
+ user.remove_card(card.id)
+ await ctx.send(f"Successfully thrown away card No. `{card.id}`")
+
+ @check()
+ @cards.command(aliases=["read"], extras={"category": Category.CARDS}, usage="cardinfo ")
+ @discord.app_commands.describe(card="The card to get infos about")
+ @discord.app_commands.autocomplete(card=all_cards_autocomplete)
+ async def cardinfo(self, ctx: commands.Context, card: str):
+ """Check card info out about any card you own"""
+ try:
+ c = Card(card)
+ except CardNotFound:
+ return await ctx.send("Invalid card")
+
+ author = User(ctx.author.id)
+ if not author.has_any_card(c.id):
+ return await ctx.send("You don't own a copy of this card so you can't view its infos")
+
+ embed = c._get_analysis_embed(c.id)
+ if c.type == "spell" and c.id not in [*DEF_SPELLS, *VIEW_DEF_SPELLS]:
+ card_class = [c for c in Card.__subclasses__() if c.__name__ == f"Card{card}"][0]
+ usage = f"`{self.client.command_prefix(self.client, ctx.message)[2]}use {card} " + " ".join([f"[{k}: {v.__name__}]" for k, v in card_class.exec.__annotations__.items() if not str(k) == "return"]) + "`"
+ embed.add_field(name="Usage", value=usage, inline=False)
+
+ await ctx.send(embed=embed)
+
+ @check()
+ @cards.command(name="check", extras={"category": Category.CARDS}, usage="check ")
+ @discord.app_commands.describe(card="The card to see how many fakes you own of it")
+ @discord.app_commands.autocomplete(card=all_cards_autocomplete)
+ async def _check(self, ctx: commands.Context, card: str):
+ """Lets you see how many copies of the specified card are fakes"""
+ try:
+ card_obj = Card(card)
+ except CardNotFound:
+ return await ctx.send("Invalid card")
+
+ author = User(ctx.author.id)
+
+ if not author.has_any_card(card_obj.id, only_allow_fakes=True):
+ return await ctx.send("You don't own any copies of this card which are fake")
+
+ text = ""
+
+ if len([x for x in author.rs_cards if x[1]["fake"] is True and x[0] == card_obj.id]) > 0:
+ text += f"The card in your restricted slots is fake"
+
+ if (fs := len([x for x in author.fs_cards if x[1]["fake"] is True and x[0] == card_obj.id])) > 0:
+ text += (" and " if len(text) > 0 else "") + f"{fs} cop{'ies' if fs > 1 else 'y'} of this card in your free slots {'are' if fs > 1 else 'is'} fake"
+
+ await ctx.send(text)
+
+ async def _use_converter(self, ctx: commands.Context, args: str) -> Union[discord.Member, int, str]:
+ if (m := await self.client.find_user(ctx, args)) and not isinstance(m, discord.User):
+ return m
+ elif args.isdigit():
+ return int(args)
+ else:
+ return args
+
+ def _use_check(self, ctx: commands.Context, card: str, args: Optional[Union[discord.Member, int, str]], add_args: Optional[int]) -> None:
+ """Makes sure the inputs are valid if they exist"""
+ try:
+ card: Card = Card(card)
+ except CardNotFound:
+ raise CheckFailure("Invalid card id")
+
+ if not card.id in [x[0] for x in User(ctx.author.id).fs_cards] and not card.id in [1036]:
+ raise CheckFailure("You are not in possesion of this card!")
+
+ if card.type != "spell":
+ raise CheckFailure("You can only use spell cards!")
+
+ if card.id in [*DEF_SPELLS, *VIEW_DEF_SPELLS]:
+ raise CheckFailure("You can only use this card in response to an attack!")
+
+ if args:
+ if isinstance(args, discord.Member):
+ if args.id == ctx.author.id:
+ raise CheckFailure("You can't use spell cards on yourself")
+ elif args.bot:
+ raise CheckFailure("You can't use spell cards on bots")
+
+ if isinstance(args, int):
+ if int(args) < 1:
+ raise CheckFailure("You can't use an integer less than 1")
+
+ if add_args:
+ if add_args < 1:
+ raise CheckFailure("You can't use an integer less than 1")
+
+ async def _use_core(self, ctx: commands.Context, item: int, *args) -> None:
+ """This passes the execution to the right class """
+ card_class = [c for c in Card.__subclasses__() if c.__name__ == f"Card{item}"][0]
+
+ l = []
+ for p, (k, v) in enumerate([x for x in card_class.exec.__annotations__.items() if not str(x[0]) == "return"]):
+ if len(args) > p and isinstance(args[p], v):
+ l.append({k: args[p]})
+ else:
+ l.append(None)
+
+ if None in l:
+ return await ctx.send(f"Invalid arguments provided! Usage: `{self.client.command_prefix(self.client, ctx.message)[2]}use {item} " + " ".join([f"[{k}: {v.__name__}]" for k, v in card_class.exec.__annotations__.items() if not str(k) == "return"]) + "`", allowed_mentions=discord.AllowedMentions.none())
+ kwargs = {k: v for d in l for k, v in d.items()}
+ try:
+ await card_class(ctx, name_or_id=item).exec(**kwargs)
+ except Exception as e:
+ await ctx.send(e.message, allowed_mentions=discord.AllowedMentions.none())
+
+ async def use_cards_autocomplete(
+ self,
+ interaction: discord.Interaction,
+ current: str,
+ ) -> List[discord.app_commands.Choice[str]]:
+ if not self.cardname_cache:
+ for card in DB.items.find({}):
+ self.cardname_cache[card["_id"]] = card["name"], card["type"]
+
+ name_cards = [(x[0], self.cardname_cache[x[0]][0])for x in User(interaction.user.id).all_cards if self.cardname_cache[x[0]][0].lower().startswith(current.lower()) and self.cardname_cache[x[0]][1] == "spell"]
+ id_cards = [(x[0], self.cardname_cache[x[0]][0])for x in User(interaction.user.id).all_cards if str(x[0]).startswith(current) and self.cardname_cache[x[0]][1] == "spell"]
+ name_cards = list(dict.fromkeys(name_cards))
+ id_cards = list(dict.fromkeys(id_cards)) # removing all duplicates from the list
+
+ if current == "": # No ids AND names if the user hasn"t typed anything yet
+ res = [discord.app_commands.Choice(name=x[1], value=str(x[0])) for x in name_cards]
+ else:
+ res = [*[discord.app_commands.Choice(name=n, value=str(i)) for i, n in name_cards], *[discord.app_commands.Choice(name=str(i), value=str(i)) for i, _ in id_cards]]
+ if "booklet".startswith(current):
+ res.append(discord.app_commands.Choice(name="booklet", value="booklet"))
+
+ return res
+
+ @check()
+ @cards.command(extras={"category":Category.CARDS}, usage="use ")
+ @discord.app_commands.describe(
+ item="The card or item to use",
+ target="The target of the spell",
+ args="Additional required arguments by the card"
+ )
+ @discord.app_commands.autocomplete(item=use_cards_autocomplete)
+ async def use(self, ctx: commands.Context, item: str, target: str = None, args: int = None):
+ """Use spell cards you own with this command! Check with cardinfo what arguments are required."""
+
+ if item.lower() == "booklet":
+
+ def make_embed(page, embed, pages):
+ embed.title = "Introduction booklet"
+ embed.description = pages[page-1]
+ embed.set_image(url="https://cdn.discordapp.com/attachments/759863805567565925/834794115148546058/image0.jpg")
+ return embed
+
+ return await Paginator(ctx, BOOK_PAGES, func=make_embed).start()
+
+ try:
+ self._use_check(ctx, item, target, args)
+ except CheckFailure as e:
+ return await ctx.send(e.message)
+
+ args = await self._use_converter(ctx, args)
+ args = [x for x in [target, args] if x]
+
+ await self._use_core(ctx, item, *args)
+
+ @commands.is_owner()
+ @cards.command(extras={"category":Category.CARDS}, usage="gain ", hidden=True)
+ @discord.app_commands.describe(
+ type="The type of item to gain",
+ item="The amount/id of the item to get"
+ )
+ async def gain(self, ctx: commands.Context, type: Items, item: str):
+ """An owner restricted command allowing the user to obtain any card or amount of jenny or any lootbox"""
+ user = User(ctx.author.id)
+ type = type.name
+
+ if type == "card":
+ try:
+ card = Card(item)
+ except CardNotFound:
+ return await ctx.send("Invalid card id")
+ if card.id == 0:
+ return await ctx.send("No")
+ if len(card.owners) >= card.limit * ALLOWED_AMOUNT_MULTIPLE:
+ return await ctx.send("Sorry! Global card limit reached!")
+ if len(user.fs_cards) >= FREE_SLOTS and (item > 99 or item in [x[0] for x in user.rs_cards]):
+ return await ctx.send("Seems like you have no space left in your free slots!")
+ user.add_card(card.id)
+ return await ctx.send(f"Added card '{card.name}' to your inventory")
+
+ if type == "jenny":
+ if not item.isdigit():
+ return await ctx.send("Please provide a valid amount of jenny!")
+ item = int(item)
+ if item < 1:
+ return await ctx.send("Please provide a valid amount of jenny!")
+ if item > 69420:
+ return await ctx.send("Be reasonable.")
+ user.add_jenny()
+ return await ctx.send(f"Added {item} Jenny to your account")
+
+ if type == "lootbox":
+ if not item.isdigit() or not int(item) in list(LOOTBOXES.keys()):
+ return await ctx.send("Invalid lootbox!")
+ user.add_lootbox(int(item))
+ return await ctx.send(f"Done! Added lootbox \"{LOOTBOXES[int(item)]['name']}\" to your inventory")
+
+Cog = Cards
diff --git a/tests/killua/cogs/dev.py b/tests/killua/cogs/dev.py
new file mode 100644
index 000000000..9599dccb7
--- /dev/null
+++ b/tests/killua/cogs/dev.py
@@ -0,0 +1,438 @@
+from discord.ext import commands
+import discord
+
+import math
+from typing import List, Tuple, Union
+from io import BytesIO
+from datetime import datetime, timedelta
+from matplotlib import pyplot as plt
+import numpy as np
+
+from killua.bot import BaseBot
+from killua.utils.checks import check
+from killua.utils.paginator import Paginator
+from killua.utils.classes import User, Guild #lgtm [py/unused-import]
+from killua.utils.interactions import View, Button, Modal
+from killua.static.enums import Category, Activities, Presences, StatsOptions
+from killua.static.cards import Card #lgtm [py/unused-import]
+from killua.static.constants import DB, UPDATE_CHANNEL, GUILD_OBJECT, INFO
+
+class UsagePaginator(Paginator):
+ """A normal paginator with a button that returns to the original help command"""
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.view.add_item(Button(label="Back", style=discord.ButtonStyle.red, custom_id="1"))
+
+ async def start(self):
+ view = await self._start()
+
+ if view.ignore or view.timed_out:
+ return
+
+ await self.view.message.delete()
+ await self.ctx.command.__call__(self.ctx, StatsOptions.usage)
+
+class Dev(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+ self.version_cache = []
+
+ async def version_autocomplete(
+ self,
+ _: discord.Interaction,
+ current: str,
+ ) -> List[discord.app_commands.Choice[str]]:
+
+ if not self.version_cache:
+ self.version_cache = [x["version"] for x in DB.const.find_one({"_id": "updates"})["updates"]]
+
+ return [
+ discord.app_commands.Choice(name=v, value=v)
+ for v in self.version_cache if current.lower() in v.lower()
+ ]
+
+ def _create_piechart(self, data: List[list], ) -> discord.File:
+ """Creates a piechart with the given data"""
+ labels = [x[0] for x in data]
+ values = [x[1] for x in data]
+ buffer = BytesIO()
+ plt.pie(values, labels=labels, autopct="%1.1f%%", shadow=True, textprops={'color':"w"})
+ plt.axis("equal")
+ plt.tight_layout()
+ plt.savefig(buffer, format="png", transparent=True)
+ buffer.seek(0)
+ plt.close()
+ file = discord.File(buffer, filename="piechart.png")
+ return file
+
+ def _create_graph(self, dates: List[datetime], y_points: List[int], label: str) -> BytesIO:
+ """Creates a graph with y over time supplied in the dates list"""
+ plt.style.use("seaborn") # After testing this is the best theme
+ # Plotting the main graph
+ plt.plot(dates, y_points, color="blue")
+ plt.xlabel("Time")
+ plt.ylabel(label)
+
+ # Plot the trend using a linear regression
+ x = np.array([x.timestamp() for x in dates])
+ y = np.array(y_points)
+ m, b = np.polyfit(x, y, 1)
+ plt.plot(dates, m*x + b, linestyle=":", color="grey")
+
+ plt.tight_layout() # Making the actual graph a bit bigger
+ buf = BytesIO()
+ plt.savefig(buf, format='png')
+ buf.seek(0)
+ plt.close()
+
+ return buf
+
+ def _calc_predictions(self, values: List[int]) -> dict:
+ """Calculates various predictions for the given values"""
+
+ #Calculates the average change between one value compared to the next one in the list
+ change = [values[i+1] - values[i] for i in range(len(values)-1)]
+ avg_change = round(sum(change)/len(values), 2)
+ # Calculates the standard deviation of the avergae change
+ std_change = round(math.sqrt(sum([(x - avg_change)**2 for x in change])/len(values)), 2)
+
+ recent_avg = round(sum(values[-10:]) / 10, 2)
+
+ return {
+ "recent_avg": recent_avg,
+ "min": min(values),
+ "max": max(values),
+ "avg_change": avg_change,
+ "std_change": std_change,
+ "median": sorted(values)[len(values) // 2],
+ "mode": max(set(values), key=values.count),
+ }
+
+ def _get_stats_embed(self, data: List[dict], embed: discord.Embed, type: str) -> Tuple[discord.Embed, discord.File]:
+ """Creates an embed with the stats of the given type"""
+ dates = [x["date"] for x in data if type in x]
+ type_list = [x[type] for x in data if type in x]
+
+ embed.title = f"Statistics about {self.client.user.name}'s " + type.replace("_", " ").title()
+
+ if not dates:
+ embed.description = "No data available just yet"
+ return embed
+
+ buffer = self._create_graph(dates, type_list, type.replace("_", " ").title())
+ file = discord.File(buffer, filename=f"{type}.png")
+ add_data = self._calc_predictions(type_list)
+
+ embed.set_image(url=f"attachment://{type}.png")
+ embed.add_field(name=f"Maximum {type} reached", value=add_data["max"]) # This is only really relevant for guilds and users as registered users cannot decrease
+ embed.add_field(name=f"Average {type} last 10 days", value=add_data["recent_avg"])
+ embed.add_field(name=f"Average {type} gained per day", value=add_data["avg_change"])
+ embed.add_field(name=f"\U000003c3 of the average daily {type} gain", value=add_data["std_change"])
+ return embed, file
+
+ async def all_top(self, ctx: commands.Context, top: List[tuple]) -> None:
+ """Shows a list of all top commands"""
+ def make_embed(page, embed, pages):
+ embed.title = "Top command usage"
+
+ if len(pages)-page*10+10 > 10:
+ top = pages[page*10-10:-(len(pages)-page*10)]
+ elif len(pages)-page*10+10 <= 10:
+ top = pages[-(len(pages)-page*10+10):]
+
+ embed.description = "```\n" + "\n".join(["#"+str(n+1)+" /"+k+" with "+str(v)+" uses" for n, (k, v) in enumerate(top, page*10-10)]) + "\n```"
+ return embed
+
+ await UsagePaginator(ctx, top, func=make_embed, max_pages=math.ceil(len(top)/10)).start()
+
+ async def group_top(self, ctx: commands.Context, top: List[tuple], interaction: discord.Interaction) -> None:
+ """Displays a pie chart of the top used commands in a group"""
+ # A list of all valid groups as strings
+ possible_groups = [g.name for g in self.client.commands if not g.parent and g.name != "help"] # The only time a command doesn't have a parent is when it's a group
+ group = await self.client.get_text_response(ctx, "Please enter a command group", interaction=interaction, style=discord.TextStyle.short, placeholder=(", ".join(possible_groups))[:97] + "...")
+ if not group: return
+
+ if not group.lower() in possible_groups:
+ return await ctx.send("That is not a valid group", ephemeral=True)
+ else:
+ top = [(x[0].split(" ")[1], x[1]) for x in top if x[0].startswith(group.lower()) and len(x[0].split(" ")) > 1]
+ rest = 0
+ for x in top[-9:]:
+ rest += x[1]
+
+ if len(top) > 9:
+ real_top = [*top[:9], ("other", rest)]
+ else:
+ real_top = top[:9]
+
+ file = self._create_piechart(real_top)
+ embed = discord.Embed(title=f"Top 10 used commands of group {group}", color=0x1400ff)
+ embed.set_image(url="attachment://piechart.png")
+
+ view = View(ctx.author.id)
+ view.add_item(Button(label="Back", style=discord.ButtonStyle.red, custom_id="back"))
+
+ msg = await ctx.send(embed=embed, file=file, view=view)
+ await view.wait()
+
+ if view.timed_out:
+ await view.disable()
+
+ if view.value:
+ if view.value == "back":
+ await msg.delete()
+ await self.initial_top(ctx)
+
+ async def initial_top(self, ctx: commands.Context) -> None:
+ s = DB.const.find_one({"_id": "usage"})["command_usage"]
+ top = sorted(s.items(), key=lambda x: x[1], reverse=True)
+ rest = 0
+ for x in top[-9:]:
+ rest += x[1]
+
+ # creates a piechart in an embed with the top 10 commands using _create_piechart
+ file = self._create_piechart([*top[:9], ("other", rest)])
+ embed = discord.Embed(title="Top 10 used commands", color=0x1400ff)
+ embed.set_image(url="attachment://piechart.png")
+
+ view = View(ctx.author.id)
+ view.add_item(Button(label="See all", style=discord.ButtonStyle.primary, custom_id="all"))
+ view.add_item(Button(label="See for group", style=discord.ButtonStyle.primary, custom_id="group"))
+
+ msg = await ctx.send(embed=embed, file=file, view=view)
+
+ await view.wait()
+
+ if view.timed_out:
+ await view.disable()
+ else:
+ await msg.delete()
+ if view.value == "all":
+ await self.all_top(ctx, top)
+ elif view.value == "group":
+ await self.group_top(ctx, top, view.interaction)
+
+
+ @commands.hybrid_group()
+ async def dev(self, _: commands.Context):
+ """A collection of commands regarding the development side of Killua"""
+ ...
+
+ #Eval command, unnecessary with the jsk extension but useful for database stuff
+ @commands.is_owner()
+ @commands.command(aliases=["exec"], extras={"category":Category.OTHER}, usage="eval ", hidden=True, with_app_command=False)
+ @discord.app_commands.describe(code="The code to evaluate") # Since this is not an app command this won"t show up but is still added for consistency
+ async def eval(self, ctx: commands.Context, *, code: str):
+ """Standard eval command, owner restricted"""
+ try:
+ await ctx.send(f"```py\n{eval(code)}```")
+ except Exception as e:
+ await ctx.send(str(e))
+
+ @commands.is_owner()
+ @commands.command(extras={"category":Category.OTHER}, usage="say ", hidden=True, with_app_command=False)
+ @discord.app_commands.describe(content="What to say") # Same thing as for the eval command
+ async def say(self, ctx: commands.Context, *, content: str):
+ """Lets Killua say what is specified with this command. Possible abuse leads to this being restricted"""
+
+ await ctx.message.delete()
+ await ctx.send(content, reference=ctx.message.reference)
+
+ @commands.is_owner()
+ @dev.command(aliases=["publish-update", "pu"], extras={"category":Category.OTHER}, usage="publish_update ", hidden=True)
+ @discord.app_commands.guilds(GUILD_OBJECT)
+ async def publish_update(self, ctx: commands.Context):
+ """Allows me to publish Killua updates in a handy format"""
+ if not ctx.interaction:
+ return await ctx.send("This command can only be used with slash commands")
+
+ modal = Modal(title="New update",timeout=None)
+ version = discord.ui.TextInput(label="Version", placeholder="v1.0")
+ image = discord.ui.TextInput(label="Image", default="https://cdn.discordapp.com/attachments/780554158154448916/788071254917120060/killua-banner-update.png", required=False)
+ description = discord.ui.TextInput(label="Description", placeholder="Killua is now open source!", max_length=4000, style=discord.TextStyle.long)
+ modal.add_item(version).add_item(image).add_item(description)
+
+ await ctx.interaction.response.send_modal(modal)
+
+ await modal.wait()
+
+ old: list = DB.const.find_one({"_id": "updates"})["updates"]
+ old_version = old[-1]["version"] if old and "version" in old[-1] else "No version"
+
+ if version.value in [x["version"] for x in old if "version" in x]:
+ return await ctx.send("This is an already existing version", ephemeral=True)
+
+ embed = discord.Embed.from_dict({
+ "title": f"Killua Update `{old_version}` -> `{version}`",
+ "description": description.value,
+ "color": 0x1400ff,
+ "footer": {"text": f"Update by {ctx.author}", "icon_url": str(ctx.author.avatar.url)},
+ "image": {"url": image.value or "https://cdn.discordapp.com/attachments/780554158154448916/788071254917120060/killua-banner-update.png"}
+ })
+
+ data = {"version": version.value, "description": description.value, "published_on": datetime.now(), "published_by": ctx.author.id, "image": image.value}
+ DB.const.update_one({"_id": "updates"}, {"$push": {"updates": data}})
+ self.version_cache.append(version.value)
+
+ await modal.interaction.response.defer()
+
+ if self.client.is_dev: # We do not want to accidentally publish a message when testing
+ return
+ channel = self.client.get_channel(UPDATE_CHANNEL)
+ msg = await channel.send(content= "<@&795422783261114398>", embed=embed)
+ await ctx.send("Published new update " + f"`{old_version}` -> `{version.value}`", ephemeral=True)
+ await msg.publish()
+
+ @check()
+ @dev.command(extras={"category":Category.OTHER}, usage="update ")
+ @discord.app_commands.autocomplete(version=version_autocomplete)
+ @discord.app_commands.describe(version="The version to get information about")
+ async def update(self, ctx: commands.Context, version: str = None):
+ """Allows you to view current and past updates"""
+ if version is None:
+ data = DB.const.find_one({"_id": "updates"})["updates"][-1]
+ else:
+ d = [x for x in DB.const.find_one({"_id": "updates"})["updates"] if "version" in x and x["version"] == version]
+ if len(d) == 0:
+ return await ctx.send("Invalid version!")
+ data = d[0]
+
+ author = self.client.get_user(data["published_by"])
+ embed = discord.Embed.from_dict({
+ "title": f"Infos about version `{data['version']}`",
+ "description": str(data["description"]),
+ "color": 0x1400ff,
+ "image": {"url": data["image"]},
+ "footer": {"icon_url": str(author.avatar.url), "text": f"Published on {data['published_on'].strftime('%b %d %Y %H:%M:%S')}"}
+ })
+ await ctx.send(embed=embed)
+
+ @commands.is_owner()
+ @dev.command(extras={"category":Category.OTHER}, usage="blacklist ", hidden=True)
+ @discord.app_commands.guilds(GUILD_OBJECT)
+ @discord.app_commands.describe(
+ user="The user to blacklist",
+ reason="The reason for the blacklist"
+ )
+ async def blacklist(self, ctx: commands.Context, user: str, *, reason = None):
+ """Blacklisting bad people like Hisoka. Owner restricted"""
+ discord_user: Union[discord.User, None] = await self.client.find_user(user)
+ if not discord_user:
+ return await ctx.send("Invalid user!", ephermal=True)
+ # Inserting the bad person into my database
+ DB.const.update_one({"_id": "blacklist"}, {"$push": {"blacklist": {"id": discord_user.id,"reason": reason or "No reason provided", "date": datetime.now()}}})
+ await ctx.send(f"Blacklisted user `{user}` for reason: {reason}", ephermal=True)
+
+ @commands.is_owner()
+ @dev.command(extras={"category":Category.OTHER}, usage="whitelist ", hidden=True)
+ @discord.app_commands.guilds(GUILD_OBJECT)
+ @discord.app_commands.describe(
+ user="The user to whitelist"
+ )
+ async def whitelist(self, ctx: commands.Context, user: str):
+ """Whitelists a user. Owner restricted"""
+ user: Union[discord.User, None] = await self.client.find_user(user)
+ if not user:
+ return await ctx.send("Invalid user!", ephermal=True)
+
+ to_pull = [d for d in DB.const.find_one({"_id": "blacklist"})["blacklist"] if d["id"] == user.id]
+
+ if not to_pull:
+ return await ctx.send("User is not blacklisted!", ephermal=True)
+
+ DB.const.update_one({"_id": "blacklist"}, {"$pull": {"blacklist": to_pull[0]}})
+ await ctx.send(f"Successfully whitelisted `{user}`")
+
+ @commands.is_owner()
+ @dev.command(aliases=["st", "pr", "status"], extras={"category":Category.OTHER}, usage="pr ", hidden=True)
+ @discord.app_commands.guilds(GUILD_OBJECT)
+ @discord.app_commands.describe(
+ text="The text displayed as the status",
+ activity="The activity Killua is doing",
+ presence="Killua's presence"
+ )
+ async def presence(self, ctx: commands.Context, text: str, activity: Activities = None, presence: Presences = None):
+ """Changes the presence of Killua. Owner restricted"""
+
+ if text == "-rm":
+ DB.const.update_many({"_id": "presence"}, {"$set": {"text": None, "activity": None, "presence": None}})
+ await ctx.send("Done! reset Killua's presence", ephemeral=True)
+ return await self.client.update_presence()
+
+ DB.const.update_many({"_id": "presence"}, {"$set": {"text": text, "presence": presence.name if presence else None, "activity": activity.name if activity else None}})
+ await self.client.update_presence()
+ await ctx.send(f"Successfully changed Killua's status to `{text}`! (I hope people like it >-<)", ephemeral=True)
+
+ @check()
+ @dev.command(extras={"category":Category.OTHER}, usage="stats ")
+ @discord.app_commands.describe(type="The type of stats you want to see")
+ async def stats(self, ctx: commands.Context, type: StatsOptions):
+ """Shows some statistics about the bot such as growth and command usage"""
+ if type == type.usage:
+ await self.initial_top(ctx)
+ elif type == StatsOptions.growth:
+ def make_embed(page, embed, _):
+ embed.clear_fields()
+ embed.description = ""
+
+ data = DB.const.find_one({"_id": "growth"})["growth"]
+
+ if page == 1:
+ # Guild growth
+ return self._get_stats_embed(data, embed, "guilds")
+ elif page == 2:
+ # User growth
+ return self._get_stats_embed(data, embed, "users")
+ elif page == 3:
+ # Registered user growth
+ return self._get_stats_embed(data, embed, "registered_users")
+ elif page == 4:
+ # Daily users
+ return self._get_stats_embed(data, embed, "daily_users")
+
+ return await Paginator(ctx, func=make_embed, max_pages=4, has_file=True).start()
+ else:
+ n_of_commands = 0
+
+ for command in self.client.tree.walk_commands():
+ if not isinstance(command, discord.app_commands.Group) and not command.qualified_name.startswith("jishaku"):
+ n_of_commands += 1
+
+ data = DB.const.find_one({"_id": "updates"})["updates"]
+ bot_version = "`Development`" if self.client.is_dev else (data[-1]["version"] if "version" in data[-1] else "`Unknown`")
+
+ now = datetime.now()
+ diff: timedelta = now - self.client.startup_datetime
+ time = f"{diff.days} days, {int((diff.seconds/60)/60)} hours, {int(diff.seconds/60)-(int((diff.seconds/60)/60)*60)} minutes and {int(diff.seconds)-(int(diff.seconds/60)*60)} seconds"
+
+ embed = discord.Embed.from_dict({
+ "title": "General bot stats",
+ "fields": [
+ {"name": "Bot uptime", "value": time, "inline": True},
+ {"name": "Bot users", "value": str(len(self.client.users)), "inline": True},
+ {"name": "Bot guilds", "value": str(len(self.client.guilds)), "inline": True},
+ {"name": "Registered users", "value": str(DB.teams.count_documents({})), "inline": True},
+ {"name": "Bot commands", "value": str(n_of_commands), "inline": True},
+ {"name": "Owner id", "value": "606162661184372736", "inline": True},
+ {"name": "Latency", "value": f"{int(self.client.latency*100)} ms", "inline": True},
+ {"name": "Shard", "value": f"{self.client.shard_id or 0}/{self.client.shard_count}", "inline": True},
+ {"name": "Bot version", "value": f"{bot_version}", "inline": True},
+ ],
+ "color": 0x1400ff,
+ "timestamp": datetime.utcnow().isoformat()
+ })
+
+ await ctx.send(embed=embed)
+
+ @check()
+ @dev.command(extras={"category":Category.OTHER}, usage="info")
+ async def info(self, ctx: commands.Context):
+ """Get some general information (lore) about the bot"""
+ embed = discord.Embed(title="Infos about the bot", description=INFO)
+ embed.color = 0x1400ff
+ return await ctx.send(embed=embed, ephemeral=True)
+
+Cog = Dev
diff --git a/tests/killua/cogs/economy.py b/tests/killua/cogs/economy.py
new file mode 100644
index 000000000..e2de8aa60
--- /dev/null
+++ b/tests/killua/cogs/economy.py
@@ -0,0 +1,300 @@
+import discord
+from discord.ext import commands
+from typing import Union, List, Tuple
+from datetime import datetime
+from random import randint
+
+from killua.bot import BaseBot
+from killua.utils.checks import check
+from killua.utils.interactions import View
+from killua.utils.interactions import Select
+from killua.utils.classes import User, Guild, LootBox
+from killua.static.enums import Category
+from killua.static.constants import USER_FLAGS, KILLUA_BADGES, GUILD_BADGES, LOOTBOXES, PREMIUM_ALIASES, DB
+
+class Economy(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+ self._init_menus()
+
+ def _init_menus(self) -> None:
+ menus = []
+ menus.append(discord.app_commands.ContextMenu(
+ name='profile',
+ callback=self.client.callback_from_command(self.profile, message=False),
+ # guild_ids=[...],
+ ))
+ menus.append(discord.app_commands.ContextMenu(
+ name='balance',
+ callback=self.client.callback_from_command(self.jenny, message=False),
+ ))
+
+ for menu in menus:
+ self.client.tree.add_command(menu)
+
+
+ async def _get_user(self, user_id: int) -> Union[discord.User, None]:
+ u = self.client.get_user(user_id)
+ if not u:
+ u = await self.client.fetch_user(user_id)
+ return u
+
+ def _fieldify_lootboxes(self, lootboxes: List[int]):
+ """Creates a list of fields from the lootboxes in the passed list"""
+ lbs: List[Tuple[int, int]] = [] # A list containing the a tuple with the amount and id of the lootboxes owned
+ res: List[dict] = [] # The fields to be returned
+
+ for lb in lootboxes:
+ if not lb in (l:= [y for _, y in lbs]):
+ lbs.append((1, lb))
+ else:
+ indx = l.index(lb)
+ lbs[indx] = (lbs[indx][0]+1, lb)
+
+ for lb in lbs:
+ n, i = lb
+ data = LOOTBOXES[i]
+ res.append({"name": f"{n}x {data['emoji']} {data['name']} (id:{i})", "value": data["description"], "inline": False})
+
+ return res
+
+ def _getmember(self, user: Union[discord.Member, discord.User]) -> discord.Embed:
+ """A function to handle getting infos about a user for less messy code """
+ joined = self.client.convert_to_timestamp(user.id)
+
+ info = User(user.id)
+ flags = [USER_FLAGS[x[0]] for x in user.public_flags if x[1]]
+ if (user.avatar and user.avatar.is_animated()) or len([x for x in self.client.guilds if user.id in [y.id for y in x.premium_subscribers]]) > 0: # A very simple nitro check that is not too accurate
+ flags.append(USER_FLAGS["nitro"])
+ badges = [(KILLUA_BADGES[PREMIUM_ALIASES[x]] if x in PREMIUM_ALIASES.keys() else KILLUA_BADGES[x]) for x in info.badges]
+
+ if str(datetime.now()) > str(info.daily_cooldown):
+ cooldown = "Ready to claim!"
+ else:
+ cooldown = f""
+
+ return discord.Embed.from_dict({
+ "title": f"Information about {user}",
+ "description": f"{user.id}\n{' '.join(flags)}",
+ "fields": [
+ {"name": "Killua Badges", "value": " ".join(badges) if len(badges) > 0 else "No badges", "inline": False},
+ {"name": "Jenny", "value": str(info.jenny), "inline": False},
+ {"name": "Account created at", "value": joined, "inline": False},
+ {"name": "daily cooldown", "value": cooldown or "Never claimed `daily` before", "inline": False}
+ ],
+ "thumbnail": {"url": str(user.avatar.url) if user.avatar else None},
+ "image": {"url": user.banner.url if user.banner else None},
+ "color": 0x1400ff
+ })
+
+ def _lb(self, ctx: commands.Context, limit: int = 10) -> dict:
+ """Creates a list of the top members regarding jenny in a server"""
+ members = DB.teams.find({"id": {"$in": [x.id for x in ctx.guild.members]} })
+ top = sorted(members, key=lambda x: x["points"], reverse=True) # Bringing it in a nice lederboard order
+ points = 0
+ for m in top:
+ points += m["points"] # Working out total points in the server
+
+ return {
+ "points": points,
+ "top": [{"name": ctx.guild.get_member(x["id"]), "points": x["points"]} for x in top][:(limit or len(top))]
+ }
+
+ async def lootbox_autocomplete(
+ self,
+ _: discord.Interaction,
+ current:str
+ ) -> List[discord.app_commands.Choice[str]]:
+ """A function to autocomplete the lootbox name"""
+ options = []
+ for id, lb in LOOTBOXES.items():
+ if current in lb["name"]:
+ options.append(discord.app_commands.Choice(name=lb["name"], value=str(id)))
+ return options
+
+ @commands.hybrid_group()
+ async def economy(self, _: commands.Context):
+ """' commands resolving around jenny, lootboxes and the general economy"""
+ ...
+
+ @check()
+ @commands.guild_only()
+ @economy.command(aliases=["server"], extras={"category":Category.ECONOMY}, usage="guild")
+ async def guild(self, ctx: commands.Context):
+ """Displays infos about the current guild"""
+ top = self._lb(ctx, limit=1)
+ guild = Guild(ctx.guild.id)
+ badges = " ".join([GUILD_BADGES[b] for b in guild.badges])
+
+ embed = discord.Embed.from_dict({
+ "title": f"Information about {ctx.guild.name}",
+ "fields": [
+ {"name": "Owner", "value": str(ctx.guild.owner)},
+ {"name": "Killua Badges", "value": (badges if len(badges) > 0 else "No badges")},
+ {"name": "Combined Jenny", "value": top["points"]},
+ {"name": "Richest Member", "value": f"{top['top'][0]['name']} with {top['top'][0]['points']} jenny"},
+ {"name": "Server created at", "value": self.client.convert_to_timestamp(ctx.guild.id)},
+ {"name": "Members", "value": ctx.guild.member_count}
+ ],
+ "description": str(ctx.guild.id),
+ "thumbnail": {"url": str(ctx.guild.icon.url)},
+ "color": 0x1400ff
+ })
+ await self.client.send_message(ctx, embed=embed)
+
+ @check()
+ @commands.guild_only()
+ @economy.command(aliases=["lb", "top"], extras={"category":Category.ECONOMY}, usage="leaderboard")
+ async def leaderboard(self, ctx: commands.Context):
+ """Get a leaderboard of members with the most jenny"""
+ top = self._lb(ctx)
+ if top["points"] == 0:
+ return await ctx.send(f"Nobody here has any jenny! Be the first to claim some with `{self.client.command_prefix(self.client, ctx.message)[2]}daily`!", allowed_mentions=discord.AllowedMentions.none())
+ embed = discord.Embed.from_dict({
+ "title": f"Top users on guild {ctx.guild.name}",
+ "description": "\n".join([f"#{p+1} `{x['name']}` with `{x['points']}` jenny" for p, x in enumerate(top["top"])]),
+ "color": 0x1400ff,
+ "thumbnail": {"url": str(ctx.guild.icon.url)}
+ })
+ await self.client.send_message(ctx, embed=embed)
+
+ @check()
+ @economy.command(aliases=["whois", "p", "user"], extras={"category":Category.ECONOMY}, usage="profile ")
+ @discord.app_commands.describe(user="The user to get infos about")
+ async def profile(self, ctx, user: str = None):
+ """Get infos about a certain discord user with ID or mention"""
+ if user is None:
+ res = ctx.author
+ else:
+ res = await self.client.find_user(ctx, user)
+
+ if not res:
+ return await ctx.send(f"Could not find user `{user}`", allowed_mentions=discord.AllowedMentions.none(), ephemeral=True)
+
+ embed = self._getmember(res)
+ return await self.client.send_message(ctx, embed=embed, ephemeral=hasattr(ctx, "invoked_by_context_menu"))
+
+ @check()
+ @economy.command(aliases=["bal", "balance", "points"], extras={"category":Category.ECONOMY}, usage="balance ")
+ @discord.app_commands.describe(user="The user to see the number of jenny of")
+ async def jenny(self, ctx: commands.Context, user: str = None):
+ """Gives you a users balance"""
+
+ if not user:
+ res = ctx.author
+ else:
+ res = await self.client.find_user(ctx, user)
+
+ if not res:
+ return await ctx.send("User not found", ephemeral=True)
+
+ balance = User(res.id).jenny
+ return await ctx.send(f"{res}'s balance is {balance} Jenny", ephemeral=hasattr(ctx, "invoked_by_context_menu"))
+
+ @check()
+ @economy.command(extras={"category":Category.ECONOMY}, usage="daily")
+ async def daily(self, ctx: commands.Context):
+ """Claim your daily Jenny with this command!"""
+ now = datetime.now()
+ user = User(ctx.author.id)
+
+ if str(user.daily_cooldown) > str(now): # When the cooldown is still active
+ return await ctx.send(f"You can claim your daily Jenny the next time in ")
+
+ min, max = 50, 100
+ if user.is_premium:
+ min, max = min*2, max*2 # Sadly `min, max *= 2` does not work, this is the only way to fit it in one line
+ if ctx.guild and Guild(ctx.guild.id).is_premium:
+ min, max = min*2, max*2
+ daily = randint(min, max)
+ if user.is_entitled_to_double_jenny:
+ daily *= 2
+
+ user.claim_daily()
+ user.add_jenny(daily)
+ await ctx.send(f"You claimed your {daily} daily Jenny and hold now on to {user.jenny}")
+
+ @check()
+ @economy.command(extras={"category": Category.ECONOMY}, usage="open")
+ async def open(self, ctx: commands.Context):
+ """Open a lootbox with an interactive UI"""
+ if len((user:=User(ctx.author.id)).lootboxes) == 0:
+ return await ctx.send("Sadly you don't have any lootboxes!")
+
+ lootboxes = self._fieldify_lootboxes(user.lootboxes)
+ embed = discord.Embed.from_dict({
+ "title": "Choose a lootbox to open!",
+ "fields": lootboxes,
+ "color": 0x1400ff
+ })
+ lbs = []
+ for l in user.lootboxes:
+ if l not in lbs:
+ lbs.append(l)
+
+ view = View(ctx.author.id)
+ select = Select(options=[discord.SelectOption(label=LOOTBOXES[lb]["name"], emoji=LOOTBOXES[lb]["emoji"], value=str(lb), description=d if len((d:=LOOTBOXES[lb]["description"])) < 47 else d[:47] + "...") for lb in lbs], placeholder="Select a box to open")
+ view.add_item(item=select)
+
+ msg = await ctx.send(embed=embed, view=view)
+ await view.wait()
+
+ await view.disable(msg)
+ if view.timed_out:
+ await ctx.send("Timed out!", ephemeral=True)
+
+ user.remove_lootbox(view.value)
+ values = LootBox.generate_rewards(view.value)
+ box = LootBox(ctx, values)
+ return await box.open()
+
+ @check()
+ @economy.command(aliases=["lootboxes", "inv"], extras={"category": Category.ECONOMY}, usage="inventory")
+ async def inventory(self, ctx: commands.Context):
+ """Displays the owned lootboxes"""
+ if len((user:=User(ctx.author.id)).lootboxes) == 0:
+ return await ctx.send("Sadly you don't have any lootboxes!")
+
+ lootboxes = self._fieldify_lootboxes(user.lootboxes)
+ embed = discord.Embed.from_dict({
+ "title": "Lootbox inventory",
+ "description": f"open a lootbox with `/economy open`",
+ "color": 0x1400ff,
+ "fields": lootboxes
+ })
+ embed.timestamp = datetime.now()
+ await ctx.send(embed=embed)
+
+ @check()
+ @economy.command(extras={"category": Category.ECONOMY}, usage="boxinfo ")
+ @discord.app_commands.autocomplete(box=lootbox_autocomplete)
+ @discord.app_commands.describe(box="The box to get infos about")
+ async def boxinfo(self, ctx: commands.Context, box: str):
+ """Get infos about any box you desire"""
+ if box.isdigit() and not int(box) in LOOTBOXES.keys():
+ box = self.client.get_lootbox_from_name(box)
+ if not box:
+ return await ctx.send("Invalid box name or id", ephemeral=True)
+
+ data = LOOTBOXES[int(box)]
+
+ c_min, c_max = data["cards_total"]
+ j_min, j_max = data["rewards"]["jenny"]
+ contains = f"{data['rewards_total']} total rewards\n{f'{c_min}-{c_max}' if c_max != c_min else c_min} cards\n{j_min}-{j_max} jenny per field\n" + ('' if c_max == 0 else f"card rarities: {' or '.join(data['rewards']['cards']['rarities'])}\ncard types: {' or '.join(data['rewards']['cards']['types'])}")
+ embed = discord.Embed.from_dict({
+ "title": f"Infos about lootbox {data['emoji']} {data['name']}",
+ "description": data["description"],
+ "fields": [
+ {"name": "Contains", "value": contains, "inline": False},
+ {"name": "Price", "value": data["price"], "inline": False},
+ {"name": "Buyable", "value": "Yes" if data["available"] else "No"},
+ ],
+ "color": 0x1400ff,
+ "image": {"url": data["image"]}
+ })
+ await ctx.send(embed=embed)
+
+
+Cog = Economy
+
diff --git a/tests/killua/cogs/events.py b/tests/killua/cogs/events.py
new file mode 100644
index 000000000..a7c4b8d2b
--- /dev/null
+++ b/tests/killua/cogs/events.py
@@ -0,0 +1,446 @@
+import io, re
+import sys
+import discord
+
+import logging
+import traceback
+from datetime import datetime
+from discord.ext import commands, tasks
+from PIL import Image
+from typing import Dict, List, Tuple
+from matplotlib import pyplot as plt
+
+from killua.bot import BaseBot
+from killua.utils.classes import Guild, Book
+from killua.static.enums import PrintColors
+from killua.static.constants import TOPGG_TOKEN, DBL_TOKEN, PatreonBanner, DB, GUILD, MAX_VOTES_DISPLAYED
+
+class Events(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+ self.skipped_first = False
+ self.status_started = False
+ self.log_channel_id = 718818548524384310
+ self.client.startup_datetime = datetime.now()
+
+ @property
+ def old_commands(self) -> List[str]:
+ return self._get_old_commands()
+
+ @property
+ def log_channel(self):
+ return self.client.get_guild(GUILD).get_channel(self.log_channel_id)
+
+ def _get_old_commands(self) -> List[str]:
+ """Gets a list of all commands names without and their aliases"""
+ cmds = []
+ for command in self.client.tree.walk_commands():
+ if not isinstance(command, discord.app_commands.Group) and not command.name == "help" and\
+ not command.qualified_name.startswith("jishaku") and \
+ not command.qualified_name.startswith("todo") and \
+ not command.qualified_name.startswith("tag"):
+ cmds.append(command.name)
+ return cmds
+
+ async def _post_guild_count(self) -> None:
+ """Posts relevant stats to the botlists Killua is on"""
+ data = { # The data for discordbotlist
+ "guilds": len(self.client.guilds),
+ "users": len(self.client.users)
+ }
+
+ await self.client.session.post(f"https://discordbotlist.com/api/v1/bots/756206646396452975/stats", headers={"Authorization": DBL_TOKEN}, data=data)
+ await self.client.session.post(f"https://top.gg/api/bots/756206646396452975/stats", headers={"Authorization": TOPGG_TOKEN}, data={"server_count": len(self.client.guilds)})
+
+ async def _load_cards_cache(self) -> None:
+ """Downloads all the card images so the image manipulation is fairly fast"""
+ cards = [x for x in DB.items.find()]
+
+ if len(cards) == 0:
+ return logging.error(f"{PrintColors.WARNING}No cards in the database, could not load cache{PrintColors.ENDC}")
+
+ logging.info(f"{PrintColors.WARNING}Loading cards cache....{PrintColors.ENDC}")
+ percentages = [25, 50, 75]
+ for p, item in enumerate(cards):
+ try:
+ if item["_id"] in Book.card_cache:
+ continue # in case the event fires multiple times this avoids using unnecessary cpu power
+
+ async with self.client.session.get(item["Image"]) as res:
+ image_bytes = await res.read()
+ image_card = Image.open(io.BytesIO(image_bytes)).convert("RGBA")
+ image_card = image_card.resize((84, 115), Image.ANTIALIAS)
+
+ Book.card_cache[str(item["_id"])] = image_card
+ if len(percentages) >= 1 and (p/len(cards))*100 > (percent:= percentages[0]):
+ logging.info(f"{PrintColors.WARNING}Cache loaded {percent}%...{PrintColors.ENDC}")
+ percentages.remove(percent)
+ except Exception as e:
+ logging.error(f"{PrintColors.FAIL}Failed to load card {item['_id']} with error: {e}{PrintColors.ENDC}")
+
+ logging.info(f"{PrintColors.OKGREEN}All cards successfully cached{PrintColors.ENDC}")
+
+ async def _set_patreon_banner(self) -> None:
+ """Loads the patron banner bytes so it can be quickly sent when needed"""
+ res = await self.client.session.get(PatreonBanner.URL)
+ image_bytes = await res.read()
+ PatreonBanner.VALUE = image_bytes
+ logging.info(f"{PrintColors.OKGREEN}Successfully loaded patreon banner{PrintColors.ENDC}")
+
+ def print_dev_text(self) -> None:
+ logging.info(f"{PrintColors.OKGREEN}Running bot in dev enviroment...{PrintColors.ENDC}")
+
+ async def cog_load(self):
+ #Changing Killua's status
+ await self._set_patreon_banner()
+ if self.client.is_dev:
+ self.print_dev_text()
+ else:
+ await self._post_guild_count()
+ await self._load_cards_cache()
+
+ @commands.Cog.listener()
+ async def on_message(self, message: discord.Message) -> None:
+ prefix = "kil!" if self.client.is_dev else (Guild(message.guild.id).prefix if message.guild else "k!")
+ if message.content.startswith(prefix):
+ if message.content[len(prefix):].split(" ")[0] in self.old_commands:
+ return await message.reply("This command has been moved over to a command group, check `/help` to find the new command and `/dev update` to see what's changing with Killua.", allowed_mentions=discord.AllowedMentions.none())
+
+ @commands.Cog.listener()
+ async def on_ready(self):
+ self.save_guilds.start()
+ if not self.status_started:
+ self.status.start()
+ self.status_started = True
+
+ logging.info(PrintColors.OKGREEN + "Logged in as: " + self.client.user.name + f" (ID: {self.client.user.id})" + PrintColors.ENDC)
+
+ @tasks.loop(hours=12)
+ async def status(self):
+ await self.client.update_presence() # For some reason this does not work in cog_load because it always fires before the bot is connected and
+ # thus throws an error so I have to do it a bit more hacky in here
+ if not self.client.is_dev:
+ await self._post_guild_count()
+
+ @status.before_loop
+ async def before_status(self):
+ await self.client.wait_until_ready()
+
+ @tasks.loop(hours=24)
+ async def save_guilds(self):
+ from killua.static.constants import daily_users
+
+ if not self.client.is_dev and self.skipped_first:
+ DB.const.update_one({"_id": "growth"}, {"$push": {"growth": {"date": datetime.now() ,"guilds": len(self.client.guilds), "users": len(self.client.users), "registered_users": DB.teams.count_documents({}), "daily_users": len(daily_users)}}})
+ daily_users = [] # Resetting the daily users list lgtm [py/unused-local-variable]
+ elif not self.skipped_first: # We want to avoid saving data each time the bot restarts, start 24h after one
+ self.skipped_first = True
+
+ @commands.Cog.listener()
+ async def on_guild_join(self, guild):
+ #Changing the status
+ await self.client.update_presence()
+ Guild.add_default(guild.id)
+
+ @commands.Cog.listener()
+ async def on_guild_remove(self, guild):
+ #Changing Killua's status
+ await self.client.update_presence()
+ Guild(guild.id).delete()
+ await self._post_guild_count()
+
+ @commands.Cog.listener()
+ async def on_member_join(self, member: discord.Member):
+ # Welcomes new member
+ if not self.client.is_dev and member.guild.id == GUILD: # In theory it would be cool if the dev bot welcomed you but it just isn't always online
+ embed = discord.Embed.from_dict({
+ "title": "Welcome to the Killua support server a.k.a. Kile's dev!",
+ "description": "You joined. What now?\n\n**Where to go**\n" + \
+ "â <#1019657047568035841> to recieve help or report bugs\n" + \
+ "â <#787819439596896288> To get some ping roles\n" +\
+ "â <#886546434663538728> Good place to check before asking questions\n" +\
+ "â <#754063177553150002> To see newest announcements\n" +\
+ "â <#757170264294424646> Read up on the newest Killua updates\n" +\
+ "â <#716357592493981707> Use bots in here\n" +\
+ "â <#811903366925516821> Check if there is any known outage/bug\n\n" +\
+ "Thanks for joining and don't forget to vote for Killua! :)",
+ "color": 0x1400ff,
+ })
+ embed.set_thumbnail(url=self.client.user.avatar.url if self.client.user else None)
+ embed.timestamp = datetime.now()
+
+ await self.log_channel.send(content=member.mention, embed=embed)
+ # try:
+ # await member.send(embed=embed)
+ # except discord.Forbidden:
+ # pass
+
+ def _create_piechart(self, data: List[list], title: str) -> discord.File:
+ """Creates a piechart with the given data"""
+ data = [l for l in data if l[1] > 0] # We want to avoid a 0% slice
+
+ labels = [x[0] for x in data]
+ values = [x[1] for x in data]
+ colours = [x[2] for x in data]
+ buffer = io.BytesIO()
+ plt.pie(values, labels=labels, autopct="%1.1f%%", shadow=True, textprops={'color':"w"}, colors=colours)
+ plt.title(title, fontdict={"color": "w"})
+ plt.axis("equal")
+ plt.tight_layout()
+ plt.savefig(buffer, format="png", transparent=True)
+ buffer.seek(0)
+ plt.close()
+ file = discord.File(buffer, filename="piechart.png")
+ return file
+
+ def find_counter_start(self, title: str) -> int:
+ """Finds where the counter in a poll title starts"""
+ revers = title[::-1]
+ for i, char in enumerate(revers):
+ if char == "`" and revers[i-1] == "[":
+ return i+1
+
+ @commands.Cog.listener()
+ async def on_interaction(self, interaction: discord.Interaction):
+ if interaction.type == discord.InteractionType.component:
+ if interaction.data["custom_id"] and (interaction.data["custom_id"].startswith("poll:") or interaction.data["custom_id"].startswith("wyr:")):
+ # for component in interaction.message.components[0].children:
+ # print("Before: ", component.custom_id)
+
+ if interaction.data["custom_id"].split(":")[2].isdigit(): # Backwards compatability
+ split = interaction.data["custom_id"].split(":")
+ _p = split[0]
+ action = split[1]
+ opt_votes = ""
+ else:
+ split = interaction.data["custom_id"].split(":")
+ _p = split[0]
+ action = split[1]
+ opt_votes = split[2]
+
+ poll = _p == "poll" # As the logic for polls and wyr overlaps we can use the same code for both, just need to differentiate for a few small things
+
+ guild = Guild(interaction.guild_id)
+ saved = guild.is_premium and poll
+
+ if saved:
+ author = guild.polls[str(interaction.message.id)]["author"]
+ else:
+ author = interaction.message.components[0].children[-1].custom_id.split(":")[2]
+
+ if action.startswith("opt"):
+
+ if self.client._encrypt(interaction.user.id, smallest=False) == author or str(author).isdigit() and interaction.user.id == int(author):
+ return await interaction.response.send_message("You cannot vote in your own poll!", ephemeral=True)
+
+ option = int(action.split("-")[1]) if poll else {"a": 1, "b": 2}[action.split("-")[1]]
+
+ if not saved: # Determines votes etc from custom ids
+ votes: Dict[int, Tuple[list, list]] = {}
+
+ old_close = interaction.message.components[0].children[-1].custom_id # as this value is modified in the loop the original value needs to be saved to check it
+ for pos, field in enumerate(interaction.message.embeds[0].fields):
+ child = interaction.message.components[0].children[pos]
+ votes[pos] = [int(v.replace("<@", "").replace(">", "")) for v in field.value.split("\n") if re.match(r"<@!?([0-9]+)>", v)], [v for v in child.custom_id.split(":")[2].split(",") if v != ""] if not child.custom_id.split(":")[2].isdigit() else []
+ encrypted = self.client._encrypt(interaction.user.id)
+
+ if (interaction.user.id in votes[pos][0] or encrypted in votes[pos][1] or re.findall(rf";{pos+1};[^;:]*{encrypted}(.*?)[;:]", old_close)) and pos == option-1:
+ return await interaction.response.send_message(f"You already {'voted for' if poll else 'chose'} this option!", ephemeral=True)
+
+ if interaction.user.id in votes[pos][0]:
+ votes[pos][0].remove(interaction.user.id)
+ elif encrypted in votes[pos][1] or encrypted in interaction.message.components[0].children[-1].custom_id:
+ # find component and remove the vote
+ for component in interaction.message.components[0].children:
+
+ if not (encrypted in component.custom_id):
+ continue
+
+ component.custom_id = re.sub(rf"{encrypted},?", "", component.custom_id)
+
+ if encrypted in votes[pos][1]: # Strange that I have to put this check in here again but it sometimes fails without it
+ votes[pos][1].remove(encrypted)
+
+ if len(votes[option-1][0]) < MAX_VOTES_DISPLAYED:
+ votes[option-1][0].append(interaction.user.id)
+ elif len(interaction.data["custom_id"] + encrypted) <= 100:
+ votes[option-1][1].append(encrypted)
+ interaction.message.components[0].children[option-1].custom_id = _p + ":" + action + ":" + opt_votes + ("," if opt_votes else "") + encrypted
+ elif len(interaction.message.components[0].children[-1].custom_id) + len(encrypted) + (0 if str(option) in interaction.message.components[0].children[-1].custom_id else 2) <= 100 and poll:
+ # using regex it will find a free space after ;{option}; to put it in
+ # first finding the current thing after ;{option};
+ found = re.findall(rf";{option};([^;:]*)", interaction.message.components[0].children[-1].custom_id)
+ if not found: # If the option has not been added yet
+ custom_id = interaction.message.components[0].children[-1].custom_id.split(":")
+ interaction.message.components[0].children[-1].custom_id = custom_id[0] + ":" + custom_id[1] + ":" + custom_id[2] + ":" + custom_id[3] + "" + f";{option};{encrypted}" + ":"
+ else:
+ if len(found[0]) > 0: # If other users have voted for this option
+ found_items = str(found[0]).split(",")
+ found_items.append(encrypted)
+ interaction.message.components[0].children[-1].custom_id = interaction.message.components[0].children[-1].custom_id.replace(str(found[0]), ",".join(found_items))
+ else: # If the number exists but with no votes
+ interaction.message.components[0].children[-1].custom_id = interaction.message.components[0].children[-1].custom_id.replace(f";{option};",f";{option};{encrypted}")
+ else:
+ view = discord.ui.View()
+ view.add_item(discord.ui.Button(style=discord.ButtonStyle.link, label="Get Premium", url="https://patreon.com/kilealkuri"))
+ if poll:
+ return await interaction.response.send_message(f"The maximum votes on this {'poll' if poll else 'wyr'} has been reached! Make this a premium server to allow more votes! Please that votes started before becomind a premium server will still not be able to recieve more votes.", ephemeral=True, view=view)
+ else:
+ return await interaction.response.send_message(f"The maximum votes on this {'poll' if poll else 'wyr'} has been reached!", ephemeral=True)
+ else:
+ votes: Dict[int, list] = guild.polls[str(interaction.message.id)]["votes"]
+
+ for pos, field in enumerate(interaction.message.embeds[0].fields):
+ if interaction.user.id in votes[str(pos)] and pos == option-1:
+ return await interaction.response.send_message(f"You already {'voted for' if poll else 'chose'} this option!", ephemeral=True)
+
+ if interaction.user.id in votes[str(pos)]:
+ votes[str(pos)].remove(interaction.user.id)
+
+ votes[str(option-1)].append(interaction.user.id)
+
+ guild.update_poll_votes(interaction.message.id, votes)
+
+ embed = interaction.message.embeds[0]
+
+ new_embed = discord.Embed(title=embed.title, description=embed.description, color=embed.color)
+ new_embed.set_footer(text=embed.footer.text, icon_url=embed.footer.icon_url)
+ if embed.thumbnail:
+ new_embed.set_thumbnail(url=embed.thumbnail.url)
+
+ for pos, field in enumerate(embed.fields):
+ if not saved: # Calculate poll votes if it is not saved
+ close_votes = re.findall(rf";{pos+1};(.*?)[;:]", interaction.message.components[0].children[-1].custom_id)
+ num_of_votes = len(votes[pos][0]) + len(votes[pos][1]) + (len([f for f in str(close_votes[0]).split(",") if f != ""]) if close_votes else 0)
+ new_name = field.name[:-self.find_counter_start(field.name)] + f"`[{num_of_votes} " + (f"vote{'s' if num_of_votes != 1 else ''}" if poll else f"{'people' if num_of_votes != 1 else 'person'}") + "]`"
+ if not votes[pos][1]:
+ value = "\n".join([f"<@{v}>" for v in votes[pos][0]]) if votes[pos][0] else ("No votes" if poll else "No takers")
+ else:
+ cancel_votes = re.findall(rf";{option};([^;:]*)", interaction.message.components[0].children[-1].custom_id)
+ additional_votes = len(votes[pos][1]) + (len(cancel_votes[0].split(",")) if cancel_votes else 0)
+ value = "\n".join([f"<@{v}>" for v in votes[pos][0]]) + f"\n*+ {additional_votes} more...*"
+ else:
+ num_of_votes = len(votes[str(pos)])
+ new_name = field.name[:-self.find_counter_start(field.name)] + f"`[{num_of_votes} " + (f"vote{'s' if num_of_votes != 1 else ''}" if poll else f"{'people' if num_of_votes != 1 else 'person'}") + "]`"
+ if len(votes[str(pos)]) > MAX_VOTES_DISPLAYED:
+ value = "\n".join([f"<@{v}>" for v in votes[str(pos)][:MAX_VOTES_DISPLAYED]]) + f"\n*+ {len(votes[str(pos)])-MAX_VOTES_DISPLAYED} more...*"
+ else:
+ value = "\n".join([f"<@{v}>" for v in votes[str(pos)]]) if votes[str(pos)] else ("No votes" if poll else "No takers")
+ new_embed.add_field(name=new_name, value=value, inline=False)
+
+ # for component in interaction.message.components[0].children:
+ # print("After: ", component.custom_id)
+
+ new_view = discord.ui.View()
+
+ for component in interaction.message.components[0].children:
+ d = component.to_dict()
+ del d["type"]
+ d["style"] = discord.ButtonStyle(d["style"])
+ new_view.add_item(discord.ui.Button(**d))
+ await interaction.response.edit_message(embed=new_embed, view=new_view)
+
+ elif action == "close":
+ # poll_creator = interaction.message.components[0].children[-1].custom_id.split(":")[2]
+ if not (self.client._encrypt(interaction.user.id, smallest=False) == author or str(author).isdigit() and interaction.user.id == int(author)):
+ return await interaction.response.send_message("Only the polll author can close this poll!", ephemeral=True)
+
+ # Create a piechart with the results
+ colours = ["#6aaae8", "#84ae62", "#a58fd0", "#e69639"]
+ if not saved:
+ data = [
+ [
+ f"Option {pos+1}", # Calculate the number of votes for each option
+ 0 if field.value == "No votes" else len(field.value.split("\n")) + \
+ len(interaction.message.components[0].children[pos].custom_id.split(":")[2].split(",")) - \
+ 1 if len(field.value.split("\n")) > MAX_VOTES_DISPLAYED else 0 + \
+ + (len(str(close_votes[0]).split(",")) if (close_votes := re.findall(rf";{pos};[^;:]*", interaction.message.components[0].children[-1].custom_id)) else 0),
+ colours[pos]
+ ]
+ for pos, field in enumerate(interaction.message.embeds[0].fields)
+ ]
+ else:
+ votes: Dict[int, list] = guild.polls[str(interaction.message.id)]["votes"]
+ data = [
+ [
+ f"Option {pos+1}",
+ len(votes[str(pos)]),
+ colours[pos]
+ ]
+ for pos, _ in enumerate(interaction.message.embeds[0].fields)
+ ]
+
+ if not data:
+ return await interaction.response.send_message("There are no votes for this poll!", ephemeral=True)
+
+ piechart = self._create_piechart(data, interaction.message.embeds[0].description)
+
+ new_embed = discord.Embed(title=interaction.message.embeds[0].title + " [closed]", description=interaction.message.embeds[0].description, color=interaction.message.embeds[0].color)
+ new_embed.set_image(url="attachment://piechart.png")
+
+ colour_emotes = ["\U0001f535", "\U0001f7e2", "\U0001f7e3", "\U0001f7e0"]
+ for pos, field in enumerate(interaction.message.embeds[0].fields):
+ new_embed.add_field(name=field.name + f" {colour_emotes[pos]}", value=field.value, inline=False)
+
+ new_view = discord.ui.View()
+ for button in interaction.message.components[0].children:
+ new_button = discord.ui.Button(label=button.label, style=button.style, disabled=True)
+ new_view.add_item(new_button)
+
+ if saved:
+ guild.close_poll(str(interaction.message.id))
+
+ await interaction.message.delete()
+ await interaction.response.send_message(embed=new_embed, file=piechart, view=new_view)
+
+ @commands.Cog.listener()
+ async def on_command_error(self, ctx: commands.Context, error):
+
+ if ctx.channel.permissions_for(ctx.me).send_messages is False and not self.client.is_dev: # we don't want to raise an error inside the error handler when Killua ' send the error because that does not trigger `on_command_error`
+ return
+
+ if ctx.command:
+ usage = f"`{self.client.command_prefix(self.client, ctx.message)[2]}{(ctx.command.parent.name + ' ') if ctx.command.parent else ''}{ctx.command.usage}`"
+
+ if isinstance(error, commands.BotMissingPermissions):
+ return await ctx.send(f"I don't have the required permissions to use this command! (`{', '.join(error.missing_permissions)}`)")
+
+ if isinstance(error, commands.MissingPermissions):
+ return await ctx.send(f"You don't have the required permissions to use this command! (`{', '.join(error.missing_permissions)}`)")
+
+ if isinstance(error, commands.MissingRequiredArgument):
+ return await ctx.send(f"Seems like you missed a required argument for this command: `{str(error.param).split(':')[0]}`")
+
+ if isinstance(error, commands.UserInputError):
+ return await ctx.send(f"Seems like you provided invalid arguments for this command. This is how you use it: {usage}", allowed_mentions=discord.AllowedMentions.none())
+
+ if isinstance(error, commands.NotOwner):
+ return await ctx.send("Sorry, but you need to be the bot owner to use this command")
+
+ if isinstance(error, commands.BadArgument):
+ return await ctx.send(f"Could not process arguments. Here is the command should be used: {usage}", allowed_mentions=discord.AllowedMentions.none())
+
+ if isinstance(error, commands.NoPrivateMessage):
+ return await ctx.send("This command can only be used inside of a guild")
+
+ if isinstance(error, commands.CommandNotFound) or isinstance(error, commands.CheckFailure): # I don't care if this happens
+ return
+
+ view = discord.ui.View()
+ view.add_item(discord.ui.Button(label="Report bug", url=self.client.support_server_invite))
+ await ctx.send(":x: an unexpected error occured. If this should keep happening, please report it by clicking on the button and using `/report` in the support server.", view=view)
+
+ if self.client.is_dev: # prints the full traceback in dev enviroment
+ logging.error(PrintColors.FAIL + "Ignoring exception in command {}:".format(ctx.command))
+ traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
+ return print(PrintColors.ENDC)
+
+ else:
+ guild = ctx.guild.id if ctx.guild else "dm channel with "+ str(ctx.author.id)
+ command = ctx.command.name if ctx.command else "Error didn't occur during a command"
+ logging.error(f"{PrintColors.FAIL}------------------------------------------")
+ logging.error(f"An error occurred\nGuild id: {guild}\nCommand name: {command}\nError: {error}")
+ logging.error(f"------------------------------------------{PrintColors.ENDC}")
+
+Cog = Events
\ No newline at end of file
diff --git a/tests/killua/cogs/games.py b/tests/killua/cogs/games.py
new file mode 100644
index 000000000..5410823cc
--- /dev/null
+++ b/tests/killua/cogs/games.py
@@ -0,0 +1,694 @@
+import discord
+from discord.ext import commands
+
+import re
+import random
+import asyncio
+import math
+from aiohttp import ClientSession
+from urllib.parse import unquote
+from typing import Union, List, Tuple, Literal
+
+from killua.bot import BaseBot
+from killua.utils.paginator import View
+from killua.utils.classes import CardLimitReached, User
+from killua.utils.interactions import ConfirmButton
+from killua.static.cards import Card
+from killua.static.enums import Category, TriviaDifficulties, CountDifficulties, GameOptions
+from killua.static.constants import ALLOWED_AMOUNT_MULTIPLE, DB
+from killua.utils.checks import blcheck, check
+from killua.utils.interactions import Select, Button
+
+leaderboard_options = [
+ discord.app_commands.Choice(name="global", value="global"),
+ discord.app_commands.Choice(name="server", value="server")
+]
+
+class PlayAgainButton(discord.ui.Button):
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.label = "Play Again"
+ self.__clicked = None
+ self.custom_id = "play_again"
+
+ async def callback(self, interaction: discord.Interaction):
+
+ if not self.__clicked:
+ self.label = "[1/2] Play Again"
+ self.__clicked = interaction.user
+ await interaction.response.edit_message(view=self.view)
+
+ else:
+ if self.__clicked == interaction.user:
+ self.label = "Play Again"
+ self.__clicked = None
+ await interaction.response.edit_message(view=self.view)
+ else:
+ self.label = "[2/2] Play Again"
+ self.view.value = True
+ await interaction.response.edit_message(view=self.view)
+ self.view.stop()
+
+
+class RpsSelect(discord.ui.Select):
+ """Creates a select menu to confirm an rps choice"""
+ def __init__(self, options, **kwargs):
+ super().__init__(
+ min_values=1,
+ max_values=1,
+ options=options,
+ **kwargs
+ )
+
+ async def callback(self, interaction: discord.Interaction):
+ self.view.value = int(interaction.data["values"][0])
+ for opt in self.options:
+ if opt.value == str(self.view.value):
+ opt.default = True
+ self.disabled = True
+ await interaction.response.edit_message(view=self.view)
+ self.view.stop()
+
+class Trivia:
+ """Handles a trivia game"""
+
+ def __init__(self, ctx: commands.Context, difficulty: str, session: ClientSession):
+ self.url = f"https://opentdb.com/api.php?amount=1&difficulty={difficulty}&type=multiple"
+ self.difficulty = difficulty.lower()
+ self.session = session
+ self.ctx = ctx
+ self.timed_out = False
+ self.result = None
+ self.rewards = {
+ "easy": (5, 10),
+ "medium": (10, 20),
+ "hard": (20, 30)
+ }
+
+ async def _get(self) -> dict:
+ """Requests the trivia url"""
+ res = await self.session.get(self.url)
+ self.res = await res.json()
+ self.failed = (self.res["response_code"] != 0)
+
+ def _create_embed(self) -> discord.Embed:
+ """Creates the trivia embed"""
+ question = unquote(self.data["question"])
+ question = re.sub("&.*?;", "", question) # Yes, apparently unqote is not enough to remove all html entities
+ self.embed = discord.Embed.from_dict({
+ "title": f"Trivia of category {self.data['category']}",
+ "description": f"**difficulty:** {self.data['difficulty']}\n\n**Question:**\n{question}",
+ "color": 0x1400ff
+ })
+
+ def _create_view(self) -> None:
+ """Creates a select with the options needed"""
+ self.view = View(self.ctx.author.id)
+ self.data["incorrect_answers"].append(self.data["correct_answer"])
+ self.options = random.sample(self.data["incorrect_answers"], k=4)
+ self.correct_index = self.options.index(self.data["correct_answer"])
+ self.view.add_item(Select(options=[discord.SelectOption(label=x if len(x) < 50 else x[:47] + "...", value=str(i)) for i, x in enumerate(self.options)]))
+
+ async def create(self) -> None:
+ """Creates all properties necessary"""
+ await self._get()
+ if not self.failed:
+ self.data = self.res["results"][0]
+ self._create_embed()
+ self._create_view()
+
+ async def send(self) -> Union[discord.Message, None]:
+ """Sends the embed and view and awaits a response"""
+ if self.failed:
+ return await self.ctx.send(":x: There was an issue with the API. Please try again. If this should happen frequently, please report it")
+ self.msg = await self.ctx.bot.send_message(self.ctx, embed=self.embed, view=self.view)
+ await self.view.wait()
+ await self.view.disable(self.msg)
+
+ if not hasattr(self.view, "value"):
+ self.timed_out = True
+ else:
+ self.result = self.view.value
+
+ async def send_result(self) -> None:
+ """Sends the result of the trivia and hands out jenny as rewards"""
+ user = User(self.ctx.author.id)
+
+ if self.failed:
+ return
+
+ elif self.timed_out:
+ await self.ctx.send("Timed out!", reference=self.msg)
+
+ elif self.result != self.correct_index:
+ user.add_trivia_stat("wrong", self.difficulty)
+ await self.ctx.send(f"Sadly not the right answer! The answer was {self.correct_index+1}) {self.options[self.correct_index]}")
+
+ else:
+ rew = random.randint(*self.rewards[self.difficulty])
+ if user.is_entitled_to_double_jenny:
+ rew *= 2
+ user.add_jenny(rew)
+ user.add_trivia_stat("right", self.difficulty)
+ await self.ctx.send(f"Correct! Here are {rew} Jenny as a reward!")
+
+
+class Rps:
+ """A class handling someone playing rps alone or with someone else"""
+ def __init__(self, ctx: commands.Context, points: int = None, other: discord.Member = None):
+ self.ctx = ctx
+ self.points = points
+ self.other = other
+ self.emotes = {
+ 0: ":page_facing_up:",
+ -1: ":moyai:",
+ 1: ":scissors:"
+ }
+
+ async def _dmcheck(self, user: discord.User) -> bool:
+ """Checks if a users dms are open by sending them an empty message and either recieving an error for can't send an empty message or not allowed"""
+ try:
+ await user.send("")
+ except Exception as e:
+ if isinstance(e, discord.Forbidden):
+ return False
+ if isinstance(e, discord.HTTPException):
+ return True
+ return True
+
+ def _get_options(self) -> List[discord.SelectOption]:
+ """Returns a new instance of the option list so itdoesn't get mixed up when editing"""
+ return [discord.SelectOption(label="rock", value="-1", emoji="\U0001f5ff"), discord.SelectOption(label="paper", value="0", emoji="\U0001f4c4"), discord.SelectOption(label="scissors", value="1", emoji="\U00002702")]
+
+ def _result(self, p: int, q: int) -> int:
+ """Evaluates who won, by doing very smart math. -1 means player p won, 0 means it was a tie, 1 means player q won"""
+ return int(math.sin(math.pi/12*(q-p)*((q-p)**2+5)))
+
+ async def _send_rps_embed(self) -> discord.Message:
+ """Sends a confirming embed"""
+ embed = discord.Embed.from_dict({
+ "title": f"{self.ctx.author.display_name} against {self.other.display_name or self.ctx.me.display_name}: **Rock... Paper... Scissors!**",
+ "image": {"url": "https://media1.tenor.com/images/dc503adb8a708854089051c02112c465/tenor.gif?itemid=5264587"},
+ "color": 0x1400ff
+ })
+
+ await self.ctx.bot.send_message(self.ctx, embed=embed)
+
+ async def _timeout(self, players: list, data: List[Tuple[discord.Message, View]]) -> None:
+ """A way to handle a timeout of not responding to Killua in dms"""
+ for x in players:
+ if x.id in [v.user.id for _, v in data if v.value is not None]:
+ await x.send("Sadly the other player has not responded in time")
+ else:
+ await x.send("Too late, time to respond is up!")
+
+ async def _wait_for_response(self, users: List[discord.Member]) -> Union[None, List[View]]:
+ data = []
+ for u in users:
+ view = View(user_id=u.id, timeout=None)
+ select = RpsSelect(options=self._get_options())
+ view.add_item(select)
+ view.user = u
+ msg = await u.send("You chose to play Rock Paper Scissors, what's your choice Hunter?", view=view)
+ data.append((msg, view))
+
+ done, pending = await asyncio.wait([v.wait() for _, v in data], return_when=asyncio.ALL_COMPLETED, timeout=100)
+
+ for m, v in data:
+ await v.disable(m)
+
+ if False in [x.done() == True for x in [*done, *pending]]:
+ # Handles the case that one or both players don't respond to the dm in time
+ return await self._timeout(users, data)
+
+ return [v for _, v in data]
+
+ async def check_for_achivement(self, player: discord.User) -> None:
+ """Checks wether someone has earend the "rps master" achivement"""
+ user = User(player.id)
+ if not "rps_master" in user.achievements and user.rps_stats["pve"]["won"] >= 25:
+ user.add_achievement(["rps_master"])
+ card = Card(83)
+ try:
+ if len(card.owners) >= (card.limit * ALLOWED_AMOUNT_MULTIPLE):
+ user.add_jenny(1000)
+ await player.send(f"By defeating me 25 times you have earned the **RPS Master** achievemt! Sadly the normal reward, the card \"{card.name}\" {card.emoji}, is currently owned by too many people, so insead you get **1000 Jenny** as a reward!")
+ else:
+ user.add_card(83)
+ await player.send(f"By defeating me 25 times you have earned the **RPS Master** achievemt! As a reward you recieve the card \"{card.name}\" {card.emoji}")
+ except CardLimitReached:
+ user.add_jenny(1000)
+ await player.send(f"By defeating me 25 times you have earned the **RPS Master** achievemt! Sadly you have no space in your book for the normal reward, the card \"{card.name}\" {card.emoji}, so insead you get **1000 Jenny** as a reward!")
+
+ async def _eval_outcome(self, winlose: int, choice1: int, choice2: int, player1:discord.Member, player2: discord.Member, view: View) -> discord.Message:
+ """Evaluates the outcome, informs the players and handles the points """
+ p1 = User(player1.id)
+ p2 = User(player2.id)
+ if winlose == -1:
+ p1.add_rps_stat("won", player2 == self.ctx.me)
+ p2.add_rps_stat("lost", player1 == self.ctx.me)
+ await self.check_for_achivement(player1)
+
+ if self.points:
+ p1.add_jenny(self.points)
+ if player2 != self.ctx.me:
+ p2.remove_jenny(self.points)
+ return await self.ctx.send(f"{self.emotes[choice1]} > {self.emotes[choice2]}: {player1.mention} won against {player2.mention} winning {self.points} Jenny which adds to a total of {p1.jenny}", view=view)
+ else:
+ return await self.ctx.send(f"{self.emotes[choice1]} > {self.emotes[choice2]}: {player1.mention} won against {player2.mention}", view=view)
+
+ elif winlose == 0:
+ p1.add_rps_stat("tied", player2 == self.ctx.me)
+ if player2 != self.ctx.me:
+ p2.add_rps_stat("tied", player1 == self.ctx.me)
+ return await self.ctx.send(f"{self.emotes[choice1]} = {self.emotes[choice2]}: {player1.mention} tied against {player2.mention}", view=view)
+
+ elif winlose == 1:
+ p1.add_rps_stat("lost", player2 == self.ctx.me)
+ p2.add_rps_stat("won", player1 == self.ctx.me)
+ await self.check_for_achivement(player2)
+
+ if self.points:
+ p1.remove_jenny(self.points, player2 == self.ctx.me)
+ if player2 != self.ctx.me:
+ p2.add_jenny(self.points)
+ return await self.ctx.send(f"{self.emotes[choice1]} < {self.emotes[choice2]}: {player1.mention} lost against {player2.mention} losing {self.points} Jenny which leaves them a total of {p1.jenny}", view=view)
+ else:
+ return await self.ctx.send(f"{self.emotes[choice1]} < {self.emotes[choice2]}: {player1.mention} lost against {player2.mention}", view=view)
+
+ def _play_again_view(self, players: List[discord.Member]) -> View:
+ """Creates a button that, if clicked by both players, automatically launches another game"""
+ view = View(user_id=[x.id for x in players])
+ button = PlayAgainButton()
+ view.add_item(button)
+ return view
+
+ async def singleplayer(self) -> Union[None, discord.Message]:
+ """Handles the case of the user playing against the bot"""
+ await self._send_rps_embed()
+
+ resp = await self._wait_for_response([self.ctx.author])
+ if not resp:
+ return
+
+ c2 = random.randint(-1, 1)
+ winlose = self._result(resp[0].value, c2)
+
+ view = View(user_id=self.ctx.author.id)
+ button = Button(label="Play again", style=discord.ButtonStyle.grey)
+ view.add_item(button)
+
+ msg =await self._eval_outcome(winlose, resp[0].value, c2, self.ctx.author, self.ctx.me, view)
+
+ await view.wait()
+ await view.disable(msg)
+ if not view.value or view.timed_out:
+ pass
+ else:
+ await self.singleplayer()
+
+ async def multiplayer(self, replay: bool = False) -> Union[None, discord.Message]:
+ """Handles the case of the user playing against self.other user"""
+ if not replay:
+ if await self._dmcheck(self.ctx.author) is False:
+ return await self.ctx.send(f"You need to open your dm to Killua to play {self.ctx.author.mention}")
+ if await self._dmcheck(self.other) is False:
+ return await self.ctx.send(f"{self.other.name} needs to open their dms to Killua to play")
+
+ if blcheck(self.other.id) is True:
+ return await self.ctx.send("You can't play against someone blacklisted")
+
+ view = ConfirmButton(self.other.id, timeout=80)
+ msg = await self.ctx.send(f"{self.ctx.author.mention} challenged {self.other.mention} to a game of Rock Paper Scissors! Will **{self.other}** accept the challange?", view=view)
+ await view.wait()
+ await view.disable(msg)
+
+ if not view.value:
+ if view.timed_out:
+ return await self.ctx.send(f"Sadly no response...")
+ else:
+ return await self.ctx.send(f"{self.other.display_name} doesn't want to play... maybe they do after a hug?")
+
+ await self._send_rps_embed()
+ res = await self._wait_for_response([self.ctx.author, self.other])
+ if not res:
+ return
+ winlose = self._result(res[0].value, res[1].value)
+
+ view = self._play_again_view([self.ctx.author, self.other])
+ msg = await self._eval_outcome(winlose, res[0].value, res[1].value, res[0].user, res[1].user, view)
+ await view.wait()
+ await view.disable(msg)
+ if not view.value or view.timed_out:
+ pass
+ else:
+ await self.multiplayer(replay=True)
+
+
+ async def start(self) -> None:
+ """The function starting the game"""
+ if self.other == self.ctx.me:
+ await self.singleplayer()
+ else:
+ await self.multiplayer()
+
+class CountButtons(discord.ui.Button):
+ """The code for every button used in the game"""
+ def __init__(self, solutions: dict, index: int, correct: bool = None, **kwargs):
+ self.index = index # the position the button is on. Starts with 1
+ self.solutions = solutions # The solutions in the format {number: correct_button_index}
+ self.correct = correct # If the button is correct
+ super().__init__(style=discord.ButtonStyle.grey if correct is None else (discord.ButtonStyle.green if correct else discord.ButtonStyle.red), **kwargs)
+
+ def _create_view(self, correct: bool) -> View:
+ """Creates a new view after the callback depending on if the result was correct or not"""
+ for c in self.view.children:
+ if correct:
+ c.correct=True if c.index == self.index else c.correct
+ c.disabled=True if c.index == self.index or self.view.stage-1 == len(self.solutions) else c.disabled
+ c.label=str(self.view.stage-1) if c.index == self.index else c.label
+ c.style=discord.ButtonStyle.success if c.index == self.index else c.style
+ else:
+ c.correct=False if c.index == self.index else c.correct
+ c.disabled=True
+ c.label=str(self.view.stage) if c.index == self.solutions[self.view.stage] else c.label
+ c.style=discord.ButtonStyle.red if c.index == self.index else c.style
+
+ return self.view
+
+ async def _respond(self, correct: bool, last: bool, view: View, interaction: discord.Interaction) -> discord.Message:
+ """Responds with the new view"""
+ if correct and last:
+ return await interaction.response.edit_message(content="Congrats, you move on to the next level!", view=view)
+ if not correct:
+ return await interaction.response.edit_message(content="Oh no! This was not the right order! Better luck next time", view=view)
+ if not last:
+ return await interaction.response.edit_message(content="Can you remember?", view=view)
+
+ async def callback(self, interaction: discord.Interaction):
+ """Is called when a button is clicked and determines wether it was correct or not, then passes that on to other functions"""
+ self.view.correct = self.solutions[self.view.stage] == self.index # if the button was correct
+ last: bool = self.view.stage == len(self.solutions) # if this is the last stage
+
+ if self.view.correct:
+ self.view.stage += 1
+
+ view = self._create_view(self.view.correct)
+ await self._respond(self.view.correct, last, view, interaction)
+
+ if not self.view.correct or last:
+ self.view.stop()
+
+class CountGame:
+ """A game where you have to remember numbers and type them in the right order"""
+ def __init__(self, ctx: commands.Context, difficulty: str):
+ self.ctx = ctx
+ self.user = User(ctx.author.id)
+ self.difficulty = difficulty
+ self.level = 1
+
+ def _handle_reward(self) -> int:
+ """Creates a jenny reward based on the level and difficulty"""
+ return ((2 if self.user.is_entitled_to_double_jenny else 1) * int(random.randint(20, 30) * self.level * (0.5 if self.difficulty == "easy" else 1))) if self.level > 1 else 0
+
+ def _assign_until_unique(self, already_assigned: List[int]) -> int:
+ """Picks one random free spot to put the next number in"""
+ r = random.randint(1, 25)
+ if r in already_assigned:
+ return self._assign_until_unique(already_assigned)
+ else:
+ return r
+
+ def _create_solutions(self, keep_used: bool) -> None:
+ """Creates the solution dictionary"""
+ res: dict = (self.solutions if hasattr(self, "solutions") else {}) if keep_used else {}
+ for i in range(1 if keep_used else self.level):
+ res[len(res)+1 if keep_used else i+1] = self._assign_until_unique(list(res.values()))
+ self.solutions = res
+
+ async def _send_solutions(self, msg: discord.Message = None) -> discord.Message:
+ """Sends the solutions before hiding them"""
+ view = View(self.ctx.author.id)
+ view.stage = 1
+ for i in range(25):
+ view.add_item(discord.ui.Button(label=str([k for k, v in self.solutions.items() if v-1 == i][0]) if i+1 in list(self.solutions.values()) else " ", disabled=True, style=discord.ButtonStyle.grey))
+ if not msg:
+ msg = await self.ctx.bot.send_message(self.ctx, content="Press the buttons in the order displayed as soon as the time starts. Good luck!", view=view)
+ else:
+ await msg.edit(content="One more button to remember. Get ready!", view=view)
+
+ await asyncio.sleep(3 if self.level == 1 else (self.level*2*(0.5 if self.difficulty == "easy" else 1)))
+ return msg
+
+ async def _handle_game(self, msg: discord.Message) -> discord.Message:
+ """The core of the game, creates the buttons and waits until the buttons return a result and handles it"""
+ view = View(self.ctx.author.id, timeout=self.level*10*(0.5 if self.difficulty == "easy" else 1))
+ view.stage = 1
+ for i in range(25):
+ view.add_item(CountButtons(self.solutions, i+1, label=" ", custom_id=str(i+1)))
+ await msg.edit(content="Can you remember?", view=view)
+ await view.wait()
+
+ if not hasattr(view, "correct") or not view.correct: # This happens when the user has lost the game or it timed out
+ reward = self._handle_reward()
+ resp = "Too slow!" if not hasattr(view, "correct") else "Wrong choice!"
+ for child in view.children:
+ child.disabled = True
+ await msg.edit(view=view)
+ self.user.add_jenny(reward)
+
+ if self.level-1 > self.user.counting_highscore[self.difficulty]:
+ self.user.set_counting_highscore(self.difficulty, self.level-1)
+ return await self.ctx.send(resp + " But well done, you made it to level " + str(self.level) + ", your new **personal best**, which brings you a reward of " + str(reward) + " Jenny!")
+ else:
+ return await self.ctx.send(resp + " But well done, you made it to level " + str(self.level) + ", which brings you a reward of " + str(reward) + " Jenny!")
+
+
+ self.level += 1
+
+ if self.level == 26:
+ reward = self._handle_reward()
+ return await self.ctx.send("Well done, you completed the game! Your reward is " + str(reward) + " Jenny. Keep up the great work!")
+
+ await asyncio.sleep(5)
+ self._create_solutions(self.difficulty == "easy")
+ new_msg = await self._send_solutions(msg)
+ await self._handle_game(new_msg)
+
+ async def start(self):
+ """The function to call to start the game"""
+ self._create_solutions(self.difficulty == "easy")
+ msg = await self._send_solutions()
+ await self._handle_game(msg)
+
+class Games(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+
+ @commands.hybrid_group()
+ async def games(self, _: commands.Context):
+ """A collection of games for Killua"""
+ ...
+
+ @check(500)
+ @games.command(extras={"category": Category.GAMES}, usage="count ")
+ @discord.app_commands.describe(difficulty="The difficulty to play in")
+ async def count(self, ctx: commands.Context, difficulty: CountDifficulties = CountDifficulties.easy):
+ """See how many numbers you can remember with this count game!"""
+ game = CountGame(ctx, difficulty.name)
+ await game.start()
+
+ @check(30)
+ @games.command(extras={"category":Category.GAMES}, usage="rps ")
+ @discord.app_commands.describe(
+ member="The person to challenge",
+ points="The points to play for"
+ )
+ async def rps(self, ctx: commands.Context, member: discord.Member, points: int = None):
+ """Play Rock Paper Scissors with your friends! You can play investing Jenny or just for fun."""
+
+ if member.id == ctx.author.id:
+ return await ctx.send("Baka! You can't play against yourself")
+
+ if not member.bot:
+ opponent = User(member.id)
+ elif member.bot and member != ctx.me:
+ return await ctx.send("Beep-boop, if you wanna play against a bot, play against me!")
+
+ p2 = opponent.jenny if member != ctx.me else False
+
+ user = User(ctx.author.id)
+
+ p1 = user.jenny
+
+ if points:
+ if points <= 0 or points > 100:
+ return await ctx.send(f"You can only play using 1-100 Jenny")
+
+ if p1 < points:
+ return await ctx.send(f"You do not have enough Jenny for that. Your current balance is `{p1}`")
+ if not p2 is False and p2 < points:
+ return await ctx.send(f"Your opponent does not have enough Jenny for that. Their current balance is `{p2}`")
+
+ game = Rps(ctx, points, member)
+ await game.start()
+
+ @check(20)
+ @games.command(extras={"category": Category.GAMES}, usage="trivia ")
+ @discord.app_commands.describe(difficulty="The difficulty of the question")
+ async def trivia(self, ctx: commands.Context, difficulty: TriviaDifficulties = TriviaDifficulties.easy):
+ """Play trivia and earn some jenny if you get the answer right!"""
+ await ctx.defer()
+ game = Trivia(ctx, difficulty.name, self.client.session)
+ await game.create()
+ await game.send()
+ await game.send_result()
+
+ @check()
+ @games.command(extras={"category": Category.GAMES}, usage="stats ")
+ @discord.app_commands.describe(member="The person to check the stats of")
+ async def stats(self, ctx: commands.Context, game_type: GameOptions, member: discord.Member = None):
+ """Check the game stats of yourself or another user"""
+ if not member:
+ member = ctx.author
+
+ user = User(member.id)
+
+ if game_type == GameOptions.rps:
+ pve_played = (user.rps_stats["pve"]["tied"] + user.rps_stats["pve"]["lost"] + user.rps_stats["pve"]["won"])
+ pve_win_rate = int(100*(user.rps_stats["pve"]["won"]/pve_played)) if pve_played != 0 else 0
+
+ pvp_played = (user.rps_stats["pvp"]["tied"] + user.rps_stats["pvp"]["lost"] + user.rps_stats["pvp"]["won"])
+ pvp_win_rate = int(100*(user.rps_stats["pvp"]["won"]/pvp_played)) if pvp_played != 0 else 0
+
+ await ctx.send(embed=discord.Embed(
+ title=f"{member.name}'s RPS stats",
+ description=f"**__PVE__**:\n:crown: Win rate: {pve_win_rate}%\n\n Wins: {user.rps_stats['pve']['won']}\nDraws: {user.rps_stats['pve']['tied']}\nLosses: {user.rps_stats['pve']['lost']}" + \
+ f"\n\n**__PVP__**:\n:crown: Win rate: {pvp_win_rate}%\n\n Wins: {user.rps_stats['pvp']['won']}\nDraws: {user.rps_stats['pvp']['tied']}\nLosses: {user.rps_stats['pvp']['lost']}",
+ color=0x1400ff
+ ))
+
+ elif game_type == GameOptions.trivia:
+ overall_right = user.trivia_stats["easy"]["right"] + user.trivia_stats["medium"]["right"] + user.trivia_stats["hard"]["right"]
+ overall_wrong = user.trivia_stats["easy"]["wrong"] + user.trivia_stats["medium"]["wrong"] + user.trivia_stats["hard"]["wrong"]
+
+ win_rate_overall = int(100*(overall_right/(overall_right + user.trivia_stats["easy"]["wrong"] + user.trivia_stats["medium"]["wrong"] + user.trivia_stats["hard"]["wrong"]))) if overall_wrong != 0 else 0
+
+ easy_played = user.trivia_stats["easy"]["wrong"] + user.trivia_stats["easy"]["right"]
+ win_rate_easy = int(100*(user.trivia_stats["easy"]["right"]/easy_played)) if easy_played != 0 else 0
+
+ medium_played = user.trivia_stats["medium"]["wrong"] + user.trivia_stats["medium"]["right"]
+ win_rate_medium = int(100*(user.trivia_stats["medium"]["right"]/medium_played)) if medium_played != 0 else 0
+
+ hard_played = user.trivia_stats["hard"]["wrong"] + user.trivia_stats["hard"]["right"]
+ win_rate_hard = int(100*(user.trivia_stats["hard"]["right"]/hard_played)) if hard_played != 0 else 0
+
+ await ctx.send(embed=discord.Embed(
+ title=f"{member.name}'s Trivia stats",
+ description=f"__Overall correctness__: {win_rate_overall}%\n\n__Hard__:\nRight answers: {user.trivia_stats['hard']['right']}\nWrong answers: {user.trivia_stats['hard']['wrong']}\n{win_rate_hard}% correct\n\n__Medium__:\nRight answers: {user.trivia_stats['medium']['right']}\nWrong answers: {user.trivia_stats['medium']['wrong']}\n{win_rate_medium}% correct\n\n__Easy__:\nRight answers: {user.trivia_stats['easy']['right']}\nWrong answers: {user.trivia_stats['easy']['wrong']}\n{win_rate_easy}% correct",
+ color=0x1400ff
+ ))
+
+ elif game_type == GameOptions.counting:
+ await ctx.send(embed=discord.Embed(
+ title=f"{member.name}'s Counting stats",
+ description=f"High score easy mode: {user.counting_highscore['easy']}\n\nHigh score hard mode: {user.counting_highscore['hard']}",
+ color=0x1400ff
+ ))
+
+ @check()
+ @games.command(extras={"category": Category.GAMES}, usage="leaderboard ")
+ @discord.app_commands.describe(game="The game to check the leaderboard of", where="Whether to show the global or server leaderboard")
+ async def leaderboard(self, ctx: commands.Context, game: GameOptions, where: Literal["global", "server"] = "global"):
+ """Checks the top 10 players of a game, globally or on the server."""
+ all: List[dict] = list(DB.teams.find({} if where == "global" else {"id": {"$in": [m.id for m in ctx.guild.members]}}))
+
+ if game == GameOptions.rps:
+ top_5_pve: List[dict] = all
+ top_5_pve.sort(key=lambda x: dict(x).get("stats", {}).get("rps", {}).get("pve", {}).get("won", 0), reverse=True)
+
+ top_5_pvp: List[dict] = all
+ top_5_pvp.sort(key=lambda x: dict(x).get("stats", {}).get("rps", {}).get("pvp", {}).get("won", 0), reverse=True)
+
+ embed = discord.Embed(title="Global RPS leaderboard", description="**PVE**", color=0x1400ff)
+ for pos, player in enumerate(top_5_pve[:5]):
+ # user = self.client.get_user(player["_id"])
+ # if user:
+ wins = player.get("stats", {}).get("rps", {}).get("pve", {}).get("won", 0)
+ embed.description += f"\n**{pos+1}.** <@{player['id']}> - {wins} win{'s' if wins != 1 else ''}"
+
+ embed.description += "\n\n**PVP**"
+
+ for pos, player in enumerate(top_5_pvp[:5]):
+ # user = self.client.get_user(player["_id"])
+ # if user:
+ wins = player.get("stats", {}).get("rps", {}).get("pvp", {}).get("won", 0)
+ embed.description += f"\n**{pos+1}.** <@{player['id']}> - {wins} win{'s' if wins != 1 else ''}"
+
+ await ctx.send(embed=embed)
+
+ elif game == GameOptions.trivia:
+ top_5_hard = all
+ top_5_hard.sort(key=lambda x: dict(x).get("stats", {}).get("trivia", {}).get("hard", {}).get("right", 0), reverse=True)
+
+ top_5_medium = all
+ top_5_medium.sort(key=lambda x: dict(x).get("stats", {}).get("trivia", {}).get("medium", {}).get("right", 0), reverse=True)
+
+ top_5_easy = all
+ top_5_easy.sort(key=lambda x: dict(x).get("stats", {}).get("trivia", {}).get("easy", {}).get("right", 0), reverse=True)
+
+ embed = discord.Embed(title="Global Trivia leaderboard", description="**Hard**", color=0x1400ff)
+ for pos, player in enumerate(top_5_hard[:5]):
+ # user = self.client.get_user(player["_id"])
+ # if user:
+ right_answers = player.get("stats", {}).get("trivia", {}).get("hard", {}).get("right", 0)
+ embed.description += f"\n**{pos+1}.** <@{player['id']}> - {right_answers} right answer{'s' if right_answers != 1 else ''}"
+
+ embed.description += "\n\n**Medium**"
+
+ for pos, player in enumerate(top_5_medium[:5]):
+ # user = self.client.get_user(player["_id"])
+ # if user:
+ right_answers = player.get("stats", {}).get("trivia", {}).get("medium", {}).get("right", 0)
+ embed.description += f"\n**{pos+1}.** <@{player['id']}> - {right_answers} right answer{'s' if right_answers != 1 else ''}"
+
+ embed.description += "\n\n**Easy**"
+
+ for pos, player in enumerate(top_5_easy[:5]):
+ # user = self.client.get_user(player["_id"])
+ # if user:
+ right_answers = player.get("stats", {}).get("trivia", {}).get("easy", {}).get("right", 0)
+ embed.description += f"\n**{pos+1}.** <@{player['id']}> - {right_answers} right answer{'s' if right_answers != 1 else ''}"
+
+ await ctx.send(embed=embed)
+
+ elif game == GameOptions.counting:
+ top_5_hard = all
+ top_5_hard.sort(key=lambda x: dict(x).get("stats", {}).get("counting_highscore", {}).get("hard", 0), reverse=True)
+
+ top_5_easy = all
+ top_5_easy.sort(key=lambda x: dict(x).get("stats", {}).get("counting_highscore", {}).get("easy", 0), reverse=True)
+
+ embed = discord.Embed(title="Global Counting leaderboard", description="**Hard**", color=0x1400ff)
+ for pos, player in enumerate(top_5_hard[:5]):
+ # user = self.client.get_user(player["_id"])
+ # if user:
+ embed.description += f"\n**{pos+1}.** <@{player['id']}> - {player.get('stats', {}).get('counting_highscore', {}).get('hard', 0)} high score"
+
+ embed.description += "\n\n**Easy**"
+
+ for pos, player in enumerate(top_5_easy[:5]):
+ # user = self.client.get_user(player["_id"])
+ # if user:
+ embed.description += f"\n**{pos+1}.** <@{player['id']}> - {player.get('stats', {}).get('counting_highscore', {}).get('easy', 0)} high score"
+
+ await ctx.send(embed=embed)
+
+
+d = [{"a": 1}, {"a": 2}, {"a": 3}, {"b": 1}]
+# sort dictionary d by the value of the key "a", then only use the first 2
+
+d.sort(key=lambda x: x.get("a", 0), reverse=True)
+
+Cog = Games
\ No newline at end of file
diff --git a/tests/killua/cogs/help.py b/tests/killua/cogs/help.py
new file mode 100644
index 000000000..0fb28ce0f
--- /dev/null
+++ b/tests/killua/cogs/help.py
@@ -0,0 +1,195 @@
+import discord, os
+from typing import List
+from discord.ext import commands
+from datetime import datetime
+from inspect import getsourcelines
+
+from killua.bot import BaseBot
+from killua.utils.classes import Guild
+from killua.static.enums import Category
+from killua.utils.paginator import Paginator
+from killua.utils.interactions import Select, View, Button
+
+class HelpPaginator(Paginator):
+ """A normal paginator with a button that returns to the original help command"""
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.view.add_item(Button(label="Menu", style=discord.ButtonStyle.blurple, custom_id="1"))
+
+ async def start(self):
+ view = await self._start()
+
+ if view.ignore or view.timed_out:
+ return
+
+ await self.view.message.delete()
+ await self.ctx.command.__call__(self.ctx)
+
+
+class HelpEmbed(discord.Embed):
+ def __init__(self, av: str, **kwargs):
+ super().__init__(**kwargs)
+ self.title = "Help menu"
+ self.color = 0x1400ff
+ self.set_thumbnail(url=av)
+ self.timestamp = datetime.now()
+
+class HelpCommand(commands.Cog):
+
+ def __init__(self, client: BaseBot) -> None:
+ self.client = client
+ self.client.remove_command("help")
+ self.cache = {}
+
+ def find_source(self, command: commands.HybridCommand) -> str:
+ """Finds the source of a command and links the GitHub link to it"""
+ base_url = "https://github.com/kile/killua"
+ branch = "master" if not self.client.is_dev else "v1.0"
+
+ source = command.callback.__code__
+ filename = source.co_filename
+
+ lines, firstlineno = getsourcelines(source)
+ location = os.path.relpath(filename).replace("\\", "/")
+
+ return f"{base_url}/blob/{branch}/{location}#L{firstlineno}-L{firstlineno + len(lines) - 1}"
+
+ def get_command_help(self, command: commands.HybridCommand, prefix: str) -> discord.Embed:
+ """Gets the help embed for a command"""
+
+ embed = discord.Embed(title="Infos about command `" + command.qualified_name + "`", description=command.help or "No help found...")
+ embed.color = 0x1400ff
+
+ embed.add_field(name="Category", value=command.extras["category"].value["name"])
+
+ checks = command.checks
+
+ premium_guild, premium_user, cooldown = False, False, False
+
+ if [c for c in checks if hasattr(c, "premium_guild_only")]:
+ premium_guild = True
+
+ if [c for c in checks if hasattr(c, "premium_user_only")]:
+ premium_user = True
+
+ if (res := [c for c in checks if hasattr(c, "cooldown")]):
+ check = res[0]
+ cooldown = getattr(check, "cooldown", False)
+
+ if premium_guild or premium_user:
+ embed.description += f"\n{'<:premium_guild_badge:883473807292121149>' if premium_guild else '<:tier_one_badge:879390548857880597>'} `[Premium {'servers' if premium_guild else 'users'} only]`"
+
+ if cooldown:
+ embed.add_field(name="Cooldown", value=f"{cooldown} seconds")
+
+ usage = "```css\n/" + command.qualified_name.replace(command.name, "") + command.usage + "\n```"
+ embed.add_field(name="Usage", value=usage, inline=False)
+
+ if len(prefix) < 100: # We don't want large prefixes to break the embed and make the help command unusable
+ embed.set_footer(text=f"Message prefix: {prefix}")
+
+ return embed
+
+ def get_group_help(self, ctx: commands.Context, group: Category, prefix: str) -> HelpPaginator:
+ """Gets the help embed for a group"""
+
+ c = self.cache[group]["commands"]
+
+ def make_embed(page, embed, pages):
+ embed = self.get_command_help(c[page-1], prefix)
+ source = self.find_source(c[page-1])
+ embed.description += f"\n[Source code]({source})"
+ if len(prefix) < 100: # We don't want large prefixes to break the embed and make the help command unusable
+ embed.set_footer(text=f"Page {page}/{len(pages)} | Message prefix: {prefix}")
+ else:
+ embed.set_footer(text=f"Page {page}/{len(pages)}")
+ return embed
+
+ return HelpPaginator(ctx, c, timeout=100, func=make_embed)
+
+ async def help_autocomplete(
+ self,
+ _: discord.Interaction,
+ current: str,
+ ) -> List[discord.app_commands.Choice[str]]:
+ """Autocomplete for all cards"""
+ if not self.cache:
+ self.cache = self.client.get_formatted_commands()
+
+ all_commands = [v["commands"] for v in self.cache.values()]
+ # combine all individual lists in all_commands into one in one line
+ all_commands: List[commands.Command] = [item for sublist in all_commands for item in sublist]
+
+ return [command.qualified_name for command in all_commands if current.lower() in command.qualified_name]
+
+ @commands.hybrid_command()
+ @discord.app_commands.describe(group="The group to get help for", command="The command to get help for")
+ async def help(self, ctx: commands.Context, group: Category = None, command: str = None) -> None:
+ """Displays helfpul information about a command, group, or the bot itself."""
+ message_prefix = Guild(ctx.guild.id).prefix if ctx.guild else "k!"
+
+ if not self.cache:
+ self.cache = self.client.get_formatted_commands()
+
+ if not (group or command):
+ embed = HelpEmbed(str(ctx.me.avatar.url))
+
+ for k, v in self.cache.items():
+ embed.add_field(name=f"{v['emoji']['normal']} `{k}` ({len(v['commands'])} commands)", value=v["description"], inline=False)
+
+ embed.add_field(name="** **", value="\nFor more info to a specific command, use ```css\nhelp ```", inline=False)
+ view = View(user_id=ctx.author.id, timeout=None)
+ view.add_item(Select([discord.SelectOption(label=k, value=str(i), emoji=v["emoji"]["unicode"]) for i, (k, v) in enumerate(self.cache.items())], placeholder="Select a command group"))
+
+ view.add_item(discord.ui.Button(url=self.client.support_server_invite, label="Support server"))
+ view.add_item(discord.ui.Button(url="https://github.com/kile/killua", label="Source code"))
+ view.add_item(discord.ui.Button(url="https://killua.dev", label="Website"))
+ view.add_item(discord.ui.Button(url="https://patreon.com/kilealkuri", label="Premium"))
+
+ msg = await ctx.send(embed=embed, view=view)
+
+
+ await view.wait()
+ if view.timed_out:
+ view.children[0].disabled = True # Instead of looping through all the children, we just disable the select menu since we want the links to remain clickable
+ return await msg.edit(view=view)
+ else:
+ #await msg.edit(embed=msg.embeds[0], view=discord.ui.View())
+ await msg.delete()
+ paginator = self.get_group_help(ctx, list(self.cache.keys())[view.value], message_prefix)
+ return await paginator.start()
+
+ elif command: # if both command and group are specified, command takes priority
+ all_commands = [v["commands"] for v in self.cache.values()]
+ # combine all individual lists in all_commands into one in one line
+ all_commands: List[commands.Command] = [item for sublist in all_commands for item in sublist]
+
+ # if command not in [c.qualified_name for c in self.client.commands]:
+ # return await ctx.send(f"No command called \"{command}\" found.", ephemeral=True)
+ if not command.lower() in [c.qualified_name for c in all_commands]:
+ return await ctx.send(f"No command called \"{command}\" found.", ephemeral=True)
+
+ cmd = [c for c in all_commands if c.qualified_name == command.lower()][0]
+
+ if isinstance(cmd, commands.HybridGroup) or isinstance(cmd, discord.app_commands.ContextMenu) or cmd.hidden or cmd.qualified_name.startswith("jishaku") or cmd.name == "help": # not showing what it's not supposed to. Hacky I know
+ return await ctx.send(f"No command called \"{command}\" found.", ephemeral=True)
+
+ source_link = self.find_source(cmd)
+
+ embed = self.get_command_help(cmd, message_prefix)
+
+ source_view = View(user_id=ctx.author.id, timeout=None)
+ source_view.add_item(discord.ui.Button(url=source_link, label="Source code", style=discord.ButtonStyle.link))
+
+ return await ctx.send(embed=embed, view=source_view)
+
+ elif group:
+ if group.name not in self.cache:
+ return await ctx.send(f"No group called \"{group.name}\" found.", ephemeral=True)
+
+ paginator = self.get_group_help(ctx, group.name, message_prefix)
+ return await paginator.start()
+
+Cog = HelpCommand
\ No newline at end of file
diff --git a/tests/killua/cogs/image_manipulation.py b/tests/killua/cogs/image_manipulation.py
new file mode 100644
index 000000000..271a5e38f
--- /dev/null
+++ b/tests/killua/cogs/image_manipulation.py
@@ -0,0 +1,328 @@
+import discord
+from discord.ext import commands
+from typing import Union, Any, List, Coroutine, Optional
+import re
+import io
+from PIL import Image, ImageDraw, ImageChops
+
+from pypxl import PxlClient # My own library â¨
+
+from killua.bot import BaseBot
+from killua.utils.gif import save_transparent_gif
+from killua.utils.checks import check
+from killua.static.enums import Category, SnapOptions, EyesOptions #, FlagOptions
+from killua.static.constants import NOKIA_CODE, PXLAPI, URL_REGEX
+
+class ImageManipulation(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+ self.wtf_meme = None
+ self.wtf_meme_url = "https://i.redd.it/pvdxasy5z7k41.jpg"
+ self.pxl = PxlClient(token=PXLAPI, stop_on_error=False, session=self.client.session)
+
+ async def _get_image_bytes(self, url: str) -> io.BytesIO:
+ """Gets the bytes from the image behind the url"""
+ res = await self.client.session.get(url)
+ _bytes = await res.read()
+ return io.BytesIO(_bytes)
+
+ def _crop_to_circle(self, im):
+ """Crops the given image to a circle"""
+ bigsize = (im.size[0] * 3, im.size[1] * 3)
+ mask = Image.new("L", bigsize, 0)
+ ImageDraw.Draw(mask).ellipse((0, 0) + bigsize, fill=255)
+ mask = mask.resize(im.size, Image.ANTIALIAS)
+ mask = ImageChops.darker(mask, im.split()[-1])
+ im.putalpha(mask)
+
+ return im.copy()
+
+ def _create_frames(self, image: Image.Image) -> List[Image.Image]:
+ """Creates the frames for the spin, sligtly rotating each frame"""
+ res = []
+ for i in range(17):
+ res.append(image.rotate(i*20-1))
+ return res
+
+ async def _create_spin_gif(self, url:str) -> io.BytesIO:
+ """Takes in a url and returns io bytes of a spinning GIF"""
+ image = Image.open(await self._get_image_bytes(url)).convert("RGB")
+ # Crops the image to a square in the middle with the smallest side being the size of the largest side
+ image = image.crop((image.width/2 - min(image.width, image.height)/2, image.height/2 - min(image.width, image.height)/2, image.width/2 + min(image.width, image.height)/2, image.height/2 + min(image.width, image.height)/2))
+ new_image = self._crop_to_circle(image)
+ image.close()
+ frames = self._create_frames(new_image)
+ new_image.close()
+ buffer = io.BytesIO()
+ save_transparent_gif(frames, durations=1, save_file=buffer) # making sure the gif is transparent. This is necessarry because of a pillow bug and slows this down quite significantly
+ buffer.seek(0)
+ return buffer
+
+ def _put_horizontally(self, im1: Image.Image, im2: Image.Image, reduce_by: int = 5) -> Image.Image:
+ """Puts im2 below im2 with regards to each others sizes"""
+ heigth_avatar = int(im2.width * (im1.height/im1.width))
+ height_meme = int((heigth_avatar + im2.height)/reduce_by)
+
+ dst = Image.new("RGBA", (im2.width, heigth_avatar + height_meme))
+
+ im1 = im1.resize((im2.width, heigth_avatar))
+ dst.paste(im1, (0, 0))
+ im2 = im2.resize((im2.width, height_meme))
+ dst.paste(im2, (0, heigth_avatar))
+ return dst
+
+ async def create_wtf_meme(self, url: str) -> io.BytesIO:
+ """Puts a "excuse me what the frick" below the image provided"""
+ if not self.wtf_meme:
+ self.wtf_meme = await self._get_image_bytes(self.wtf_meme_url)
+
+ image = Image.open(self.wtf_meme).copy().convert("RGBA")
+ url_image = Image.open(await self._get_image_bytes(url)).convert("RGBA")
+
+ buffer = io.BytesIO()
+ self._put_horizontally(url_image, image).save(buffer, "PNG")
+ buffer.seek(0)
+ return buffer
+
+ async def _validate_input(self, ctx: commands.Context, target: Optional[str]) -> str: # a useful check that looks for what url to pass pxlapi
+ """Finds an image url to use from a command"""
+ if target:
+ try:
+ m = await commands.MemberConverter().convert(ctx, target)
+ return str(m.avatar.url)
+ except commands.MemberNotFound:
+ pass
+
+ try:
+ e = await commands.EmojiConverter().convert(ctx, target)
+ return str(e.url)
+ except commands.EmojiNotFound:
+ pass
+
+ if target.isdigit():
+ try:
+ user = await self.client.fetch_user(int(target))
+ return str(user.avatar.url)
+ except discord.NotFound:
+ pass
+ else:
+ url = re.search(URL_REGEX, target)
+ # Makes sure the url is valid.
+ # This check is not perfect but it works for most cases and if it's a false positive itdoesn't matter too much
+ if not url:
+ pass
+ else:
+ return url.group(0)
+
+ if len(ctx.message.attachments) > 0:
+ return ctx.message.attachments[0].url
+
+ async for message in ctx.channel.history(limit=5):
+ if len(message.attachments) > 0:
+ return message.attachments[0].url
+ elif len(message.embeds) > 0:
+ embed = message.embeds[0]
+ if embed.image:
+ return embed.image.url
+ if embed.thumbnail:
+ return embed.thumbnail.url
+
+ return str(ctx.author.avatar.url) # if all else fails, return the author"s avatar
+
+ async def handle_command(
+ self,
+ ctx: commands.Context,
+ target: Union[discord.Member, discord.Emoji, str],
+ function: Coroutine,
+ t: Any = None,
+ censor: bool = False,
+ validate: bool = True
+ ) -> discord.Message:
+ """Handles the command and returns the message"""
+ if validate:
+ data = await self._validate_input(ctx, target)
+ if not data:
+ return await ctx.send(f"Invalid arguments passed. For help with the command, use `{self.client.command_prefix(self.client, ctx.message)[2]}help {ctx.command.name}`", allowed_mentions=discord.AllowedMentions.none(), ephemeral=True)
+ else:
+ data = target
+
+ await ctx.channel.typing()
+ await ctx.send(f"Processing...", ephemeral=True)
+ r = await function(data, t)
+ if r.success:
+ f = discord.File(r.convert_to_ioBytes(), filename=f"{ctx.command.name}.{r.file_type}", spoiler=censor)
+ return await self.client.send_message(ctx, file=f, reference=ctx.message, allowed_mentions=discord.AllowedMentions.none())
+ return await ctx.send(f":x: "+r.error, allowed_mentions=discord.AllowedMentions.none())
+
+ async def flag_autocomplete(
+ self,
+ _: commands.Context,
+ current: str
+ ) -> List[discord.app_commands.Choice[str]]:
+ """Returns a list of flags that match the current string since there are too many flags for it to use the options feature"""
+ return [discord.app_commands.Choice(name=i, value=i) for i in self.pxl.flags if i.startswith(current)][:25]
+
+ @commands.hybrid_group()
+ async def image(self, _: commands.Context):
+ """
+ Image related commands
+ """
+ ...
+
+ @check(120) # Big cooldown >_<
+ @image.command(aliases=["ej", "emojimosaic"], extras={"category":Category.FUN}, usage="emojaic ")
+ @discord.app_commands.describe(target="A user, url or emoji to take the image from")
+ async def emojaic(self, ctx: commands.Context, target: str = None):
+ """Emoji mosaic an image; let emojis recreate an image you gave Killua!"""
+ async def func(data, *_):
+ return await self.pxl.emojaic([data], groupSize=6)
+ await self.handle_command(ctx, target, func)
+
+ @check(5)
+ @image.command(extras={"category":Category.FUN}, usage="flag ")
+ @discord.app_commands.describe(
+ flag="The flag to overlay the image with",
+ target="A user, url or emoji to take the image from"
+ )
+ @discord.app_commands.autocomplete(flag=flag_autocomplete) #has to be done as autocomplete and not options because there are more than 25 flags
+ async def flag(self, ctx: commands.Context, flag: str, target: str = None):
+ """Overlay an image with a flag"""
+ async def func(data, flag):
+ return await self.pxl.flag(flag=flag, images=[data])
+ await self.handle_command(ctx, target, func, flag)
+
+ @check(5)
+ @image.command(extras={"category":Category.FUN}, usage="glitch ")
+ @discord.app_commands.describe(target="A user, url or emoji to take the image from")
+ async def glitch(self, ctx: commands.Context, target: str = None):
+ """Tranform a users pfp into a glitchy GIF!"""
+ async def func(data, *_):
+ return await self.pxl.glitch(images=[data], gif=True)
+ await self.handle_command(ctx, target, func)
+
+ @check(10)
+ @image.command(extras={"category":Category.FUN}, usage="lego ")
+ @discord.app_commands.describe(target="A user, url or emoji to take the image from")
+ async def lego(self, ctx: commands.Context, target: str = None):
+ """Legofies an image"""
+ async def func(data, *_):
+ return await self.pxl.lego(images=[data], scale=True, groupSize=10)
+ await self.handle_command(ctx, target, func)
+
+ @check(3)
+ @image.command(aliases=["snap"], extras={"category":Category.FUN}, usage="snapchat ")
+ @discord.app_commands.describe(
+ filter="The snap filter to apply to the image",
+ target="A user, url or emoji to take the image from"
+ )
+ async def snapchat(self, ctx: commands.Context, filter: SnapOptions, target: str = None):
+ """Put a snapchat filter on an image with a face"""
+ async def func(data, filter):
+ return await self.pxl.snapchat(filter=filter, images=[data])
+ await self.handle_command(ctx, target, func, filter.name)
+
+ @check(3)
+ @image.command(aliases=["eye"], extras={"category":Category.FUN}, usage="eyes ")
+ @discord.app_commands.describe(
+ type="The type of eyes to put on the image",
+ target="A user, url or emoji to take the image from"
+ )
+ async def eyes(self, ctx: commands.Context, type: EyesOptions, target: str = None):
+ """Put some crazy eyes on a person"""
+ async def func(data, type):
+ return await self.pxl.eyes(eyes=type, images=[data])
+ await self.handle_command(ctx, target, func, type.name)
+
+ @check(4)
+ @image.command(aliases=["8bit", "blurr"], extras={"category":Category.FUN}, usage="jpeg ")
+ @discord.app_commands.describe(target="A user, url or emoji to take the image from")
+ async def jpeg(self, ctx: commands.Context, target: str = None):
+ """Did you ever want to decrease image quality? Then this is the command for you!"""
+ async def func(data, *_):
+ return await self.pxl.jpeg(images=[data])
+ await self.handle_command(ctx, target, func)
+
+ @check(4)
+ @image.command(extras={"category":Category.FUN}, usage="ajit ")
+ @discord.app_commands.describe(target="A user, url or emoji to take the image from")
+ async def ajit(self, ctx: commands.Context, target: str = None):
+ """ Overlays an image of Ajit Pai snacking on some popcorn!"""
+ async def func(data, *_):
+ return await self.pxl.ajit(images=[data])
+ await self.handle_command(ctx, target, func)
+
+ @check()
+ @image.command(extras={"category":Category.FUN}, usage="nokia ")
+ @discord.app_commands.describe(target="A user, url or emoji to take the image from")
+ async def nokia(self, ctx: commands.Context, target: str = None):
+ """Add the image onto a nokia display"""
+ async def func(data, *_):
+ d = "const url = "" + data + ";"" + NOKIA_CODE
+ return await self.pxl.imagescript(version="1.2.0", code=d)
+ await self.handle_command(ctx, target, func)
+
+ @check(4)
+ @image.command(extras={"category":Category.FUN}, usage="flash ")
+ @discord.app_commands.describe(target="A user, url or emoji to take the image from")
+ async def flash(self, ctx: commands.Context, target: str = None):
+ """Greates a flashing GIF. WARNING FOR PEOPLE WITH EPILEPSY!"""
+ async def func(data, *_):
+ return await self.pxl.flash(images=[data])
+ await self.handle_command(ctx, target, func, censor=True)
+
+ @check(3)
+ @image.command(extras={"category":Category.FUN}, usage="thonkify ")
+ @discord.app_commands.describe(text="The text to thonkify")
+ async def thonkify(self, ctx: commands.Context, *, text: str):
+ """Turn text into thonks!"""
+ async def func(data, *_):
+ return await self.pxl.thonkify(text=data)
+ await self.handle_command(ctx, text, func, validate=False)
+
+ @check(5)
+ @image.command(aliases=["screen"], extras={"category":Category.FUN}, usage="screenshot ")
+ @discord.app_commands.describe(website="The url of the website to screenshot")
+ async def screenshot(self, ctx: commands.Context, website:str):
+ """Screenshot the specified webste!"""
+ async def func(data, *_):
+ return await self.pxl.screenshot(url=data)
+ await self.handle_command(ctx, website, func, validate=False)
+
+ @check(2)
+ @image.command(extras={"category":Category.FUN}, usage="sonic ")
+ @discord.app_commands.describe(text="The text to let sonic say")
+ async def sonic(self, ctx: commands.Context, *, text: str):
+ """Let sonic say anything you want"""
+ async def func(data, *_):
+ return await self.pxl.sonic(text=data)
+ await self.handle_command(ctx, text, func, validate=False)
+
+ @check(30) # long check because this is exhausting for the poor computer
+ @image.command(alises=["s"], extras={"category": Category.FUN}, usage="spin ")
+ @discord.app_commands.describe(target="A user, url or emoji to take the image from")
+ async def spin(self, ctx: commands.Context, target: str = None):
+ """Spins an image 'round and 'round and 'round and 'round..."""
+ data = await self._validate_input(ctx, target)
+ if not data:
+ return await ctx.send(f"Invalid arguments passed. For help with the command, use `{self.client.command_prefix(self.client, ctx.message)[2]}help {ctx.command.name}`", allowed_mentions=discord.AllowedMentions.none())
+
+ await ctx.channel.typing()
+ await ctx.send("Processing...", ephemeral=True)
+ buffer = await self._create_spin_gif(data)
+ await self.client.send_message(ctx, file=discord.File(fp=buffer, filename="spin.gif"), reference=ctx.message, allowed_mentions=discord.AllowedMentions.none())
+
+ @check(10)
+ @image.command(extras= {"category": Category.FUN}, usage= "wtf ")
+ @discord.app_commands.describe(target="A user, url or emoji to take the image from")
+ async def wtf(self, ctx: commands.Context, target: str = None):
+ """Puts the wtf meme below the image provided"""
+ data = await self._validate_input(ctx, target)
+ if not data:
+ return await ctx.send(f"Invalid arguments passed. For help with the command, use `{self.client.command_prefix(self.client, ctx.message)[2]}help {ctx.command.name}`", allowed_mentions=discord.AllowedMentions.none())
+ await ctx.channel.typing()
+ await ctx.send("Processing...", ephemeral=True)
+ buffer = await self.create_wtf_meme(data)
+ await self.client.send_message(ctx, file=discord.File(fp=buffer, filename="wtf.png"), reference=ctx.message, allowed_mentions=discord.AllowedMentions.none())
+
+Cog = ImageManipulation
\ No newline at end of file
diff --git a/tests/killua/cogs/moderation.py b/tests/killua/cogs/moderation.py
new file mode 100644
index 000000000..4b280c0a3
--- /dev/null
+++ b/tests/killua/cogs/moderation.py
@@ -0,0 +1,232 @@
+import discord
+from discord.ext import commands
+from typing import List, Union
+from datetime import datetime
+
+from killua.bot import BaseBot
+from killua.utils.converters import TimeConverter
+from killua.utils.checks import check
+from killua.utils.classes import Guild
+from killua.static.enums import Category
+
+Choice = discord.app_commands.Choice
+
+class Moderation(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+
+ async def check_perms(self, ctx, member) -> Union[None, discord.Message]:
+ if member == ctx.me:
+ return await ctx.send("Hey!", ephemeral=True)
+
+ if member == ctx.author:
+ return await ctx.send(f"You can't {ctx.command.name} yourself!", ephemeral=True)
+
+ if ctx.author.top_role < member.top_role:
+ return await ctx.send(f"You can't {ctx.command.name} someone with a higher role than you", ephemeral=True)
+
+ if ctx.me.top_role < member.top_role:
+ return await ctx.send(f"My role needs to be moved higher up to grant me permission to {ctx.command.name} this person", ephemeral=True)
+ return None
+
+ @commands.hybrid_group()
+ async def moderation(self, _: commands.Context):
+ """
+ Moderation commands
+ """
+ ...
+
+ @check()
+ @commands.has_permissions(ban_members=True)
+ @commands.bot_has_permissions(ban_members=True)
+ @moderation.command(extras={"category":Category.MODERATION}, usage="ban ")
+ @discord.app_commands.describe(
+ member= "The member to ban",
+ delete_days="The number of days worth of messages to delete",
+ config="The options on notifying the user",
+ reason="The reason for the ban"
+ )
+ @discord.app_commands.choices(config=[
+ Choice(name="Send no dm", value=0),
+ Choice(name="Send dm on ban", value=1),
+ Choice(name="Send dm on ban with acting moderator", value=2)
+ ])
+ async def ban(
+ self,
+ ctx: commands.Context,
+ member: str,
+ delete_days: int = 1,
+ config: Choice[int] = 1,
+ *, reason: str = None
+ ):
+ """Bans a user from the server."""
+ try:
+ member = await commands.MemberConverter().convert(ctx, member)
+ except commands.MemberNotFound:
+ if member.isdigit():
+ try:
+ await ctx.guild.ban(discord.Object(id=member))
+ user = self.client.get_user(member) or await self.client.fetch_user(member)
+ return await ctx.send(f":hammer: Banned **{user}** because of: ```\n{reason or 'No reason provided'}```Operating moderator: **{ctx.author}**")
+ except discord.HTTPException:
+ return await ctx.send("Something went wrong! Did you specify a valid user id?", ephemeral=True)
+ else:
+ return await ctx.send("Invalid user!", ephemeral=True)
+
+ r = await self.check_perms(ctx, member)
+ if r: return
+
+ if config in [1, 2]:
+ try:
+ await member.send(f"You have been banned from {ctx.guild.name} because of: ```\n{reason or 'No reason provided'}```" + f" by `{ctx.author}`" if config == 2 else "")
+ except discord.HTTPException:
+ pass
+
+ await member.ban(reason=reason, delete_message_days=delete_days)
+ await ctx.send(f":hammer: Banned **{member}** because of: ```\n{reason or 'No reason provided'}```Operating moderator: **{ctx.author}**")
+
+
+ @check()
+ @commands.has_permissions(ban_members=True)
+ @commands.bot_has_permissions(ban_members=True, view_audit_log=True)
+ @moderation.command(extras={"category":Category.MODERATION}, usage="unban ")
+ @discord.app_commands.describe(member="The member to be unbanned")
+ async def unban(self, ctx: commands.Context, *, member: str):
+ """Unbans a user by ID or by tag, meaning `unban Kile#0606` will also work"""
+ banned_users = []
+ async for ban in ctx.guild.bans(limit=100): # The last 100 band should be enough
+ banned_users.append(ban.user)
+
+ if member.isdigit():
+ try:
+ user = discord.Object(id=int(member))
+ await ctx.guild.unban(user)
+ await ctx.send(f":ok_hand: Unbanned user with id **{member}**\nOperating moderator: **{ctx.author}**")
+ except discord.HTTPException as e:
+ if e.code == 10013:
+ return await ctx.send(f"No user with the user ID {member} found")
+ if e.code == 10026:
+ return await ctx.send("The user is not currently banned")
+
+ else:
+ data = member.split("#")
+ if len(data) != 2:
+ return await ctx.send("Invalid user specified! (Did you not use the User#0000 format or does the user have a # in their name?)")
+ member_name, member_discriminator = data
+
+ for ban_entry in banned_users:
+
+ if (ban_entry.name, ban_entry.discriminator) == (member_name, member_discriminator):
+ await ctx.guild.unban(ban_entry)
+ return await ctx.send(f":ok_hand: Unbanned {ban_entry.mention}\nOperating moderator: **{ctx.author}**")
+
+ return await ctx.send("User is not currently banned")
+
+ @check()
+ @commands.has_permissions(kick_members=True)
+ @commands.bot_has_permissions(kick_members=True)
+ @moderation.command(extras={"category":Category.MODERATION}, usage="kick ")
+ @discord.app_commands.describe(
+ member="The member to be kicked",
+ reason="The reason for the kick"
+ )
+ @discord.app_commands.choices(config=[
+ Choice(name="Send no dm", value=0),
+ Choice(name="Send dm on kick", value=1),
+ Choice(name="Send dm on kick with acting moderator", value=2)
+ ])
+ async def kick(
+ self, ctx: commands.Context,
+ member: discord.Member,
+ config: Choice[int] = 1,
+ *, reason: str = None
+ ):
+ """Kicks a user from the server."""
+
+ r = await self.check_perms(ctx, member)
+ if r:
+ return
+
+ if config in [1, 2]:
+ try:
+ await member.send(f"You have been kicked from {ctx.guild.name} because of: ```\n{reason or 'No reason provided'}```"+ f" by `{ctx.author}`" if config == 2 else "")
+ except discord.HTTPException:
+ pass
+
+ await member.kick(reason=reason or "No reason provided")
+ await ctx.send(f":hammer: Kicked **{member}** because of: ```\n{reason or 'No reason provided'}```Operating moderator: **{ctx.author}**")
+
+ async def shush_autocomplete(
+ self,
+ _: discord.Interaction,
+ current: str
+ ) -> List[Choice[TimeConverter]]:
+ """
+ Autocomplete for shush command
+ """
+ times = ["1m", "5m", "10m", "30m", "1h", "12h", "1d", "7d"]
+ return list([
+ Choice(name=opt, value=opt)
+ for opt in times if opt.lower().startswith(current.lower())
+ ])
+
+ @check()
+ @commands.has_permissions(moderate_members=True)
+ @commands.bot_has_permissions(moderate_members=True)
+ @moderation.command(extras={"category":Category.MODERATION}, usage="shush ")
+ @discord.app_commands.describe(
+ member="The member to be shushed",
+ time="The time until the shush expires",
+ reason="Reason for the shush"
+ )
+ @discord.app_commands.autocomplete(time=shush_autocomplete)
+ async def shush(self, ctx: commands.Context, member: discord.Member, time: TimeConverter, *, reason: str = None):
+ """\U0001f90f Timeout a user for a specified time"""
+
+ r = await self.check_perms(ctx, member)
+ if r:
+ return
+
+ await member.timeout(time, reason=reason or "No reason provided")
+ await ctx.send(f":pinching_hand: Timeouted {member} until for: ```\n{reason or 'No reason provided'}```Operating moderator: **{ctx.author}**")
+
+ @check()
+ @moderation.command(extras={"category":Category.MODERATION}, usage="unshush ")
+ @discord.app_commands.describe(
+ member="The member to be unshushed",
+ reason="The reason for the unshush"
+ )
+ async def unshush(self, ctx: commands.Context, member: discord.Member, *, reason: str = None):
+ """\U0001f444 Removes a timeout from a user"""
+
+ r = await self.check_perms(ctx, member)
+ if r:
+ return
+
+ if not member.is_timed_out():
+ return await ctx.send("This user is not timed out", ephemeral=True)
+
+ await member.timeout(None, reason=reason)
+
+ await ctx.send(f":lips: Removed the timeout from {member}")
+
+ @check()
+ @moderation.command(extras={"category":Category.MODERATION}, usage="prefix ")
+ @discord.app_commands.describe(prefix="The new message command prefix")
+ async def prefix(self, ctx: commands.Context, prefix: str = None):
+ """Change Killua's prefix with this command."""
+
+ guild = Guild(ctx.guild.id)
+
+ if ctx.author.guild_permissions.administrator and prefix:
+ guild.change_prefix(prefix)
+ return await ctx.send(f"Successfully changed server prefix to `{prefix}`!", allowed_mentions=discord.AllowedMentions.none())
+
+ elif ctx.author.guild_permissions.administrator is False and prefix:
+ return await ctx.send("You need `administrator` permissions to change the server prefix!")
+
+ await ctx.send(f"The current server prefix is `{guild.prefix}`", allowed_mentions=discord.AllowedMentions.none())
+
+
+Cog = Moderation
diff --git a/tests/killua/cogs/premium.py b/tests/killua/cogs/premium.py
new file mode 100644
index 000000000..733078b28
--- /dev/null
+++ b/tests/killua/cogs/premium.py
@@ -0,0 +1,222 @@
+import discord
+from discord.ext import commands, tasks
+
+from typing import List, Union
+from aiohttp import ClientSession
+from datetime import datetime
+
+from killua.bot import BaseBot
+from killua.utils.checks import check, premium_member_only
+from killua.utils.classes import User, Guild, LootBox
+from killua.static.enums import Category, PremiumGuildOptions
+from killua.static.constants import PATREON_TIERS, GUILD, BOOSTER_ROLE, PATREON, LOOTBOXES, PREMIUM_BENEFITS, DB
+
+class Patrons:
+
+ def __init__(self, patrons: List[dict]):
+ self.patrons = patrons
+ self.invalid = [x for x in self.patrons if x["discord"] is None]
+
+ def __iter__(self):
+ self.pos = 0
+ return self
+
+ def __next__(self): # This is to check `if id in Patrons`
+ self.pos += 1
+
+ if self.pos > len(self.patrons):
+ raise StopIteration
+
+ return self.patrons[self.pos-1]["discord"]
+
+
+class Patreon:
+ """A class which returns all current patreons with the campain specified and their discord id or None"""
+ def __init__(self, session: ClientSession, token: str, campain_id: Union[str, int]):
+ self.session = session
+ self.token = token
+ self.campain_id = campain_id
+ self.url = f"https://www.patreon.com/api/oauth2/v2/campaigns/{self.campain_id}/members?page%5B100%5D&include=currently_entitled_tiers%2Cuser&fields%5Bmember%5D=full_name%2Cis_follower%2Clast_charge_date%2Clast_charge_status%2Clifetime_support_cents%2Ccurrently_entitled_amount_cents%2Cpatron_status%2Cpledge_relationship_start&fields%5Buser%5D=social_connections&page%5Bcount%5D=100"
+
+ def _int_else(self, i: Union[str, None]) -> Union[int, None]:
+ """Turns a string into an integer if it exists, else returns None"""
+ return int(i) if i else None
+
+ def _catch(self, d:dict) -> Union[str, None]:
+ """Tries to get the discord id from the response, if any step on the way fails it returns None"""
+ try:
+ return d["attributes"]["social_connections"]["discord"]["user_id"]
+ except KeyError: # In case this happens I still want to have a value, just `None`
+ return None
+
+ async def _make_request(self, url: str) -> dict:
+ """Makes a request to the Patreon API"""
+ res = await self.session.get(url, headers={"Authorization": f"Bearer {self.token}"})
+ return await res.json()
+
+ async def _paginate(self, data: dict, prev: List[dict]) -> List[dict]:
+ """Paginates through all patreons and returns a list of all patreons"""
+ if "links" in data.keys():
+ res = await self._make_request(data["links"]["next"])
+ patrons = [*prev, *self._format_patrons(res)]
+ return await self._paginate(res, patrons)
+ else:
+ return prev
+
+ async def _get(self, data: dict) -> List[dict]:
+ """Gets a list of all discord ids of the patrons"""
+ prev: List[dict] = self._format_patrons(data)
+ if "links" in data.keys():
+ return await self._paginate(data, prev)
+ else:
+ return prev
+
+ def _get_user_info(self, data: list, user: str) -> dict:
+ """Finds the relevant info by comparing user ids"""
+ return [x for x in data if "user" in x["relationships"].keys() and x["relationships"]["user"]["data"]["id"] == user][0] # Think this is stupid? Thank Python and Patreon
+
+ def _format_patrons(self, data: dict) -> List[dict]:
+ res:List[dict] = []
+ for i in data["included"]:
+ if i["type"] == "user":
+ user = self._get_user_info(data["data"], i["id"])
+ try:
+ res.append({"discord": self._int_else(self._catch(i)), "tier": sorted(user["relationships"]["currently_entitled_tiers"]["data"], key=lambda x: int(x["id"]))[0]["id"]})
+ except Exception: # If this happens something with the tier went wrong. This means they are no longer subscribed and I want to ignore that case
+ pass
+
+ return res
+
+ async def get_patrons(self) -> List[dict]:
+ res = await self._make_request(self.url)
+ valid = await self._get(res)
+ # return valid
+ return Patrons(valid)
+
+class Premium(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+ self.invalid = True # this is only `True` the first time the bot starts because the boosters of the support server are not cached at that point, so it avoids removing their badge
+
+ async def cog_load(self):
+ self.get_patrons.start()
+
+ def _get_boosters(self) -> list:
+ """Gets a list of all the boosters of the support server"""
+ guild = self.client.get_guild(GUILD)
+ if guild is None:
+ self.invalid = True
+ return []
+ return [x.id for x in guild.members if BOOSTER_ROLE in [r.id for r in x.roles]]
+
+ def _get_differences(self, current: Patrons, saved: List[dict]) -> List[dict]:
+ """Returns a list of dictionaries containing a user id and the badge to assign. If the badge is None, they will loose their premium badges"""
+ boosters = self._get_boosters()
+ new_patrons = [*[x for x in current.patrons if x["discord"] not in [x["id"] for x in saved]], *[{"discord": b, "tier": list(PATREON_TIERS.keys())[0]} for b in boosters if b not in [s["id"] for s in saved]]]
+ # Kinda hacky ways to do it but saves lines
+ removed_patrons = [{"discord": x["id"], "tier": None} for x in saved if x["id"] not in current and (x["id"] not in boosters and not self.invalid)]
+ different_badges = [x for x in current.patrons if x["tier"] not in [y["id"] for y in saved if y["id"] == x["discord"]]]
+ return [*new_patrons, *removed_patrons, *different_badges]
+
+ def _assign_badges(self, diff: List[dict]) -> None:
+ """Assigns the changed badges to the users"""
+ for d in diff:
+ user = User(d["discord"])
+ premium_guilds = user.premium_guilds
+ badges = user.badges
+
+ for k in PATREON_TIERS.keys():
+ if k in badges:
+ badges.remove(k)
+
+ if d["tier"] is None:
+ Guild.bullk_remove_premium([int(x) for x in premium_guilds.keys()])
+ user.clear_premium_guilds()
+ else:
+ badges.append(d["tier"])
+
+ user.set_badges(badges)
+
+ @tasks.loop(minutes=2)
+ async def get_patrons(self):
+ current_patrons = await Patreon(self.client.session, PATREON, "5394117").get_patrons()
+ saved_patrons = [x for x in DB.teams.find({"badges": {"$in": list(PATREON_TIERS.keys())}})]
+
+ diff = self._get_differences(current_patrons, saved_patrons)
+ self._assign_badges(diff)
+ self.invalid = False
+
+ @commands.hybrid_group()
+ async def premium(self, _: commands.Context):
+ """Premium commands"""
+ ...
+
+ @commands.guild_only()
+ @premium_member_only()
+ @premium.command(extras={"category": Category.OTHER}, usage="premium ")
+ @discord.app_commands.describe(action="Wether to add or remove the premium status of the current server")
+ async def guild(self, ctx: commands.Context, action: PremiumGuildOptions):
+ """Add or remove the premium status of a guild with this command"""
+ if action.name == "add":
+
+ if not (user:= User(ctx.author.id)).is_premium:
+ return await ctx.send("Sadly you aren't a premium subscriber so you don't have premium guilds! Become a premium subscriber here: https://www.patreon.com/KileAlkuri")
+
+ if len(user.premium_guilds.keys()) > PATREON_TIERS[user.premium_tier]["premium_guilds"]:
+ return await ctx.send("You first need to remove premium perks from one of your other servers to give this server premium status")
+
+ if (guild:= Guild(ctx.guild.id)).is_premium:
+ return await ctx.send("This guild already has the premium status!")
+
+ guild.add_premium()
+ user.add_premium_guild(ctx.guild.id)
+ await ctx.send("Success! This guild is now a premium guild")
+
+ else:
+
+ if not (guild:= Guild(ctx.guild.id)).is_premium:
+ return await ctx.send("This guild is not a premium guild, so you don't remove it's premium status! Looking for premium? Visit https://www.patreon.com/KileAlkuri")
+
+ if not str(guild.id) in ((user:= User(ctx.author.id)).premium_guilds.keys()):
+ return await ctx.send("You are not the one who added the premium status to this server, so you can't remove it")
+
+ if not (diff:= (datetime.now()-user.premium_guilds[str(ctx.guild.id)]).days) > 7:
+ return await ctx.send(f"You need to wait {7-int(diff)} more days before you can remove this servers premium status!")
+
+ guild.remove_premium()
+ user.remove_premium_guild(ctx.guild.id)
+ await ctx.send("Successfully removed this servers premium status!")
+
+ @check()
+ @premium_member_only()
+ @premium.command(extras={"category": Category.ECONOMY}, usage="weekly")
+ async def weekly(self, ctx: commands.Context):
+ """Claim a weekly lootbox with this command"""
+ user = User(ctx.author.id)
+
+ if user.weekly_cooldown and user.weekly_cooldown > datetime.now():
+ cooldown = f""
+ return await ctx.send(f"You can claim your weekly lootbox the next time {cooldown}")
+
+ lootbox = LootBox.get_random_lootbox()
+ user.claim_weekly()
+ user.add_lootbox(lootbox)
+
+ await ctx.send(f"Successfully claimed lootbox: {LOOTBOXES[lootbox]['name']}")
+
+ @check()
+ @premium.command(aliases=["support"], extras={"category":Category.FUN}, usage="info")
+ async def info(self, ctx: commands.Context):
+ """List of all the premium perks that come along with being a patron!"""
+ view = discord.ui.View()
+ view.add_item(discord.ui.Button(label="Get premium", url="https://patreon.com/kilealkuri"))
+ embed = discord.Embed.from_dict({
+ "title": "**Support Killua**",
+ "thumbnail":{"url": "https://cdn.discordapp.com/avatars/758031913788375090/e44c0de4678c544e051be22e74bc502d.png?size=1024"},
+ "description": PREMIUM_BENEFITS,
+ "color": 0x1400ff
+ })
+ await self.client.send_message(ctx, embed=embed, view=view)
+
+Cog = Premium
\ No newline at end of file
diff --git a/tests/killua/cogs/shop.py b/tests/killua/cogs/shop.py
new file mode 100644
index 000000000..c52bd2a89
--- /dev/null
+++ b/tests/killua/cogs/shop.py
@@ -0,0 +1,491 @@
+import discord
+import logging
+from random import randint, choice
+from discord.ext import commands, tasks
+from datetime import datetime
+from typing import Union, Tuple, List
+
+from killua.bot import BaseBot
+from killua.static.cards import Card
+from killua.static.constants import FREE_SLOTS, ALLOWED_AMOUNT_MULTIPLE, PRICES, LOOTBOXES, DB, editing
+from killua.utils.classes import User, TodoList, CardNotFound, CardLimitReached
+from killua.static.enums import Category, PrintColors, TodoAddons
+from killua.utils.interactions import Button, ConfirmButton
+from killua.utils.checks import check
+from killua.utils.paginator import DefaultEmbed, Paginator
+from killua.utils.interactions import Select, View
+
+class ShopPaginator(Paginator):
+ """A normal paginator with a button that returns to the original shop select menu"""
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.view.add_item(Button(label="Menu", style=discord.ButtonStyle.blurple, custom_id="menu"))
+
+ async def start(self):
+ view = await self._start()
+
+ if view.ignore:
+ return
+
+ await self.view.message.delete()
+ if self.ctx.command.parent:
+ await self.ctx.invoke(self.ctx.command.parent)
+ else:
+ await self.ctx.invoke(self.ctx.command)
+
+class Shop(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+
+ def _format_offers(self, offers: list, reduced_item: int = None, reduced_by: int = None) -> list:
+ """Formats the offers for the shop"""
+ formatted: list = []
+ if reduced_item and reduced_by:
+ x: int = 0
+ for offer in offers:
+ formatted.append(self._format_item(offer, reduced_item, reduced_by, x))
+ x += 1
+ else:
+ for offer in offers:
+ formatted.append(self._format_item(offer))
+
+ return formatted
+
+ def _format_item(self, offer: int, reduced_item: int = None, reduced_by: int = None, number: int = None) -> dict:
+ """Formats a single item for the shop"""
+ item = DB.items.find_one({"_id": int(offer)})
+ if reduced_item:
+ if number == reduced_item:
+ return {"name":f"**Number {item['_id']}: {item['name']}** |{item['emoji']}|", 'value': f"**Description:** {item['description']}\n**Price:** {PRICES[item['rank']]-int(PRICES[item['rank']]*(reduced_by/100))} (Reduced by **{reduced_by}%**) Jenny\n**Type:** {item['type'].replace('normal', 'item')}\n**Rarity:** {item['rank']}"}
+
+ return {"name":f"**Number {item['_id']}: {item['name']}** |{item['emoji']}|", "value": f"**Description:** {item['description']}\n**Price:** {PRICES[item['rank']]} Jenny\n**Type:** {item['type'].replace('normal', 'item')}\n**Rarity:** {item['rank']}"}
+
+
+ async def cog_load(self):
+ self.cards_shop_update.start()
+
+ @tasks.loop(hours=6)
+ async def cards_shop_update(self):
+ # There have to be 4-5 shop items, inserted into the db as a list with the card numbers
+ # the challenge is to create a balanced system with good items rare enough but not too rare
+ try:
+ shop_items:list = []
+ number_of_items = randint(3,5) # How many items the shop has
+ if randint(1,100) > 95:
+ # Add a S/A card to the shop
+ thing = [i["_id"] for i in DB.items.find({"type": "normal", "rank": {"$in": ["A", "S"], "available": True}})]
+ shop_items.append(choice(thing))
+ if randint(1,100) > 20: # 80% chance for spell
+ if randint(1, 100) > 95: # 5% chance for a good spell (they are rare)
+ spells = [s["_id"] for s in DB.items.find({"type": "spell", "rank": "A", "available": True})]
+ shop_items.append(choice(spells))
+ elif randint(1,10) > 5: # 50% chance of getting a medium good card
+ spells = [s["_id"] for s in DB.items.find({"type": "spell", "rank": {"$in": ["B", "C"]}, "available": True})]
+ shop_items.append(choice(spells))
+ else: # otherwise getting a fairly normal card
+ spells = [s["_id"] for s in DB.items.find({"type": "spell", "rank": {"$in": ["D", "E", "F", "G"]}, "available": True})]
+ shop_items.append(choice(spells))
+
+ while len(shop_items) != number_of_items: # Filling remaining spots
+ thing = [t["_id"] for t in DB.items.find({"type": "normal", "rank": {"$in": ["D", "B"]}, "available": True})]
+ # There is just one D item so there is a really high probability of it being in the shop EVERY TIME
+ t = choice(thing)
+ if not t in shop_items:
+ shop_items.append(t)
+
+ log = DB.const.find_one({"_id": "shop"})["log"]
+ if randint(1, 10) > 6: # 40% to have an item in the shop reduced
+ reduced_item = randint(0, len(shop_items)-1)
+ reduced_by = randint(15, 40)
+ logging.info(f"{PrintColors.OKBLUE}Updated shop with following cards: " + ", ".join([str(x) for x in shop_items])+f", reduced item number {shop_items[reduced_item]} by {reduced_by}%{PrintColors.ENDC}")
+ log.append({"time": datetime.now(), "items": shop_items, "reduced": {"reduced_item": reduced_item, "reduced_by": reduced_by}})
+ DB.const.update_many({"_id": "shop"}, {"$set": {"offers": shop_items, "log": log, "reduced": {"reduced_item": reduced_item, "reduced_by": reduced_by}}})
+ else:
+ logging.info(f"{PrintColors.OKBLUE}Updated shop with following cards: {', '.join([str(x) for x in shop_items])}{PrintColors.ENDC}")
+ log.append({"time": datetime.now(), "items": shop_items, "redued": None})
+ DB.const.update_many({"_id": "daily_offers"}, {"$set": {"offers": shop_items, "log": log, "reduced": None}})
+ except (IndexError, TypeError):
+ logging.error(f"{PrintColors.WARNING}Shop could not be loaded, card data is missing{PrintColors.ENDC}")
+
+ def _get_view(self, ctx) -> View:
+ """Creates a view for the shop"""
+ view = View(ctx.author.id)
+ view.add_item(Button(label="Menu", style=discord.ButtonStyle.blurple, custom_id="menu"))
+ return view
+
+ async def _shop_menu(self, ctx, msg, view) -> None:
+ """Handles the shop menu"""
+ await view.wait()
+ await view.disable(msg)
+ if view.value:
+ await msg.delete()
+ if ctx.command.parent:
+ await ctx.invoke(ctx.command.parent) #in case the menu was invoked by a subcommand
+ else:
+ await ctx.invoke(ctx.command) # in case the menu was invoked by the parent
+
+ @commands.hybrid_group(aliases=["store"])
+ async def shop(self, ctx: commands.Context):
+ if not ctx.invoked_subcommand:
+ if ctx.command.parent:
+ subcommands = [c for c in ctx.command.parent.commands]
+ else:
+ subcommands = [c for c in ctx.command.commands]
+
+ view = View(ctx.author.id)
+ view.add_item(Select(options=[discord.SelectOption(label=f"{c.name} shop", value=str(i)) for i, c in enumerate(subcommands)]))
+ embed = discord.Embed.from_dict({
+ "title": "Shop menu",
+ "description": "Select the shop you want to visit",
+ "image": {"url": "https://cdn.discordapp.com/attachments/795448739258040341/885927080410361876/image0.png"},
+ "color": 0x1400ff
+ })
+ msg = await ctx.send(embed=embed, view=view)
+ await view.wait()
+
+ await view.disable(msg)
+ if view.value is None:
+ return
+
+ await msg.delete()
+ await ctx.invoke(subcommands[int(view.value)]) # calls a shop subcommand if a shop was specified
+
+ @check()
+ @shop.command(name="cards", extras={"category":Category.CARDS}, usage="cards")
+ async def cards_shop(self, ctx: commands.Context):
+ """Shows the current cards for sale"""
+
+ sh = DB.const.find_one({"_id": "shop"})
+ shop_items:list = sh["offers"]
+
+ if not sh["reduced"] is None:
+ reduced_item = sh["reduced"]["reduced_item"]
+ reduced_by = sh["reduced"]["reduced_by"]
+ formatted = self._format_offers(shop_items, reduced_item, reduced_by)
+ embed = discord.Embed(title="Current Card shop", description=f"**{Card(shop_items[reduced_item]).name} is reduced by {reduced_by}%**")
+ else:
+ formatted:list = self._format_offers(shop_items)
+ embed = discord.Embed(title="Current Card shop")
+
+ embed.color = 0x1400ff
+ embed.set_thumbnail(url="https://static.wikia.nocookie.net/hunterxhunter/images/0/08/Spell_Card_Store.png/revision/latest?cb=20130328063032")
+ for item in formatted:
+ embed.add_field(name=item["name"], value=item["value"], inline=True)
+ view = self._get_view(ctx)
+ msg = await self.client.send_message(ctx, embed=embed, view=view)
+ await self._shop_menu(ctx, msg, view)
+
+ @check()
+ @shop.command(name="todo", extras={"category": Category.TODO}, usage="todo")
+ async def todo_shop(self, ctx: commands.Context):
+ """Get some info about what cool stuff you can buy for your todo list with this command"""
+ prefix = self.client.command_prefix(self.client, ctx.message)[2]
+ embed = discord.Embed.from_dict({
+ "title": "**The todo shop**",
+ "description": f"""You can buy the following items with `{prefix}buy todo - ` while you are in the edit menu for the todo list you want to buy the item for
+
+**Cost**: 1000 Jenny
+`color` change the color of the embed which displays your todo list!
+
+**Cost**: 1000 Jenny
+`thumbnail` add a neat thumbnail to your todo list (small image on the top right)
+
+**Cost**: 1000 Jenny
+`description` add a description to your todo list (recommended for public lists with custom id)
+
+**Timed todos**: 2000 Jenny
+`timed` add todos with deadline to your list and get notified when the deadline is reached
+
+**Cost**: number of current spots * 50
+`space` buy 10 more spots for todo"s for your list""",
+ "color": 0x1400ff
+ })
+ view = self._get_view(ctx)
+ msg = await self.client.send_message(ctx, embed=embed, view=view)
+ await self._shop_menu(ctx, msg, view)
+
+ @check()
+ @shop.command(name="lootboxes", aliases=["boxes"], extras={"category": Category.ECONOMY}, usage="lootboxes")
+ async def lootboxes_shop(self, ctx: commands.Context):
+ """Get the current lootbox shop with this command"""
+ prefix = self.client.command_prefix(self.client, ctx.message)[2]
+ fields = [{"name": data["emoji"] + " " + data["name"] + " (id: " + str(id) + ")", "value": f"{data['description']}\nPrice: {data['price']}"} for id, data in LOOTBOXES.items() if data["available"]]
+
+ def make_embed(page, embed, pages):
+ embed.title = "Current lootbox shop"
+ embed.description = f"To get infos about what a lootbox contains, use `{prefix}boxinfo
`\nTo buy a box, use `{prefix}buy lootbox `"
+ embed.clear_fields()
+ if len(pages)-page*10+10 > 10:
+ for x in pages[page*10-10:-(len(pages)-page*10)]:
+ embed.add_field(name=x["name"], value=x["value"], inline=True)
+ elif len(pages)-page*10+10 <= 10:
+ for x in pages[-(len(pages)-page*10+10):]:
+ embed.add_field(name=x["name"], value=x["value"], inline=True)
+
+ return embed
+
+ if len(fields) <= 10:
+ embed = make_embed(1, DefaultEmbed(), fields)
+ view = self._get_view(ctx)
+ msg = await self.client.send_message(ctx, embed=embed, view=view)
+ return await self._shop_menu(ctx, msg, view)
+
+ await ShopPaginator(ctx, fields, func=make_embed).start() # currently only 10 boxes exist so this is not necessary, but supports more than 10 if ever necessary
+
+################################################ Buy commands ################################################
+
+ @commands.hybrid_group()
+ async def buy(self, ctx):
+ # have a shop for everything, you also need a buy for everything
+ if not ctx.invoked_subcommand:
+ return await ctx.send("You need to provide a valid subcommand! Subcommands are: `card`, `lootbox` and `todo`")
+
+ @check(2)
+ @buy.command(extras={"category": Category.CARDS}, usage="card ")
+ @discord.app_commands.describe(item="The card to buy")
+ async def card(self, ctx: commands.Context, item: str):
+ """Buy a card from the shop with this command"""
+
+ shop_data = DB.const.find_one({"_id": "shop"})
+ shop_items: list = shop_data["offers"]
+ user = User(ctx.author.id)
+
+ try:
+ card = Card(item)
+ except CardNotFound:
+ return await ctx.send(f"This card is not for sale at the moment! Find what cards are in the shop with `{self.client.command_prefix(self.client, ctx.message)[2]}shop`", allowed_mentions=discord.AllowedMentions.none())
+
+ if not item in shop_items:
+ return await ctx.send(f"This card is not for sale at the moment! Find what cards are in the shop with `{self.client.command_prefix(self.client, ctx.message)[2]}shop`", allowed_mentions=discord.AllowedMentions.none())
+
+ if not shop_data["reduced"] is None:
+ if shop_items.index(card.id) == shop_data["reduced"]["reduced_item"]:
+ price = int(PRICES[card.rank] - int(PRICES[card.rank] * (shop_data["reduced"]["reduced_by"]/100)))
+ else:
+ price = PRICES[card.rank]
+ else:
+ price = PRICES[card.rank]
+
+ if len(card.owners) >= (card.limit * ALLOWED_AMOUNT_MULTIPLE):
+ return await ctx.send("Unfortunately the global maximal limit of this card is reached! Someone needs to sell their card for you to buy one or trade/give it to you")
+
+ if len(user.fs_cards) >= FREE_SLOTS:
+ return await ctx.send(f"Looks like your free slots are filled! Get rid of some with `{self.client.command_prefix(self.client, ctx.message)[2]}sell`", allowed_mentions=discord.AllowedMentions.none())
+
+ if user.jenny < price:
+ return await ctx.send(f"I'm afraid you don't have enough Jenny to buy this card. Your balance is {user.jenny} while the card costs {price} Jenny")
+ try:
+ user.add_card(item)
+ except Exception as e:
+ if isinstance(e, CardLimitReached):
+ return await ctx.send(f"Free slots card limit reached (`{FREE_SLOTS}`)! Get rid of one card in your free slots to add more cards with `{self.client.command_prefix(self.client, ctx.message)[2]}sell `", allowed_mentions=discord.AllowedMentions.none())
+ else:
+ raise
+
+ user.remove_jenny(price) #Always putting substracting points before giving the item so if the payment errors no item is given
+ return await ctx.send(f"Successfully bought card number `{card.id}` {card.emoji} for {price} Jenny. Check it out in your inventory with `{self.client.command_prefix(self.client, ctx.message)[2]}book`!", allowed_mentions=discord.AllowedMentions.none())
+
+ async def lootbox_autocomplete(
+ self,
+ _: discord.Interaction,
+ current:str
+ ) -> List[discord.app_commands.Choice[str]]:
+ """A function to autocomplete the lootbox name"""
+ options = []
+ for lb in LOOTBOXES.values():
+ if not lb["available"]: continue
+ if current in lb["name"]:
+ options.append(discord.app_commands.Choice(name=lb["name"], value=lb["name"]))
+ return options
+
+ @check(2)
+ @buy.command(aliases=["box"], extras={"category": Category.ECONOMY}, usage="lootbox - ")
+ @discord.app_commands.describe(box="The lootbox to buy")
+ @discord.app_commands.autocomplete(box=lootbox_autocomplete)
+ async def lootbox(self, ctx: commands.Context, box: str):
+ """Buy a lootbox with this command"""
+ if not box.isdigit():
+ box = self.client.get_lootbox_from_name(box)
+ if not box:
+ return await ctx.send("This lootbox is not for sale!")
+
+ if not int(box) in LOOTBOXES or not LOOTBOXES[int(box)]["available"]:
+ return await ctx.send("This lootbox is not for sale!")
+
+ user = User(ctx.author.id)
+
+ if user.jenny < (price:=LOOTBOXES[int(box)]["price"]):
+ return await ctx.send(f"You don't have enough jenny to buy this box (You have: {user.jenny}, cost: {price})")
+
+ user.remove_jenny(price)
+ user.add_lootbox(int(box))
+ return await ctx.send(f"Successfully bought lootbox {LOOTBOXES[int(box)]['emoji']} {LOOTBOXES[box]['name']}!")
+
+
+ @check(2)
+ @buy.command(name="todo",extras={"category": Category.TODO}, usage="todo
- ")
+ @discord.app_commands.describe(what="The todo addon to buy")
+ async def _todo(self, ctx: commands.Context, what: TodoAddons):
+ """Buy cool stuff for your todo list with this command! (Only in editor mode)"""
+ try:
+ todo_list = TodoList(editing[ctx.author.id])
+ except KeyError:
+ return await ctx.send(f"You have to be in the editor mode to use this command! Use `{self.client.command_prefix(self.client, ctx.message)[2]}todo edit
`", allowed_mentions=discord.AllowedMentions.none())
+
+ user = User(ctx.author.id)
+
+ if what.name == "space":
+ if user.jenny < (todo_list.spots * 100 * 0.5):
+ return await ctx.send(f"You don't have enough Jenny to buy more space for your todo list. You need {todo_list['spots']*100} Jenny")
+
+ if todo_list.spots >= 100:
+ return await ctx.send("You can't buy more than 100 spots")
+
+ view = ConfirmButton(ctx.author.id, timeout=10)
+ msg = await ctx.send(f"Do you want to buy 10 more to-do spots for this list? \nCurrent spots: {todo_list.spots} \nCost: {int(todo_list.spots*100*0.5)} points", view=view)
+ await view.wait()
+ await view.disable(msg)
+
+ if not view.value:
+ if view.timed_out:
+ return await ctx.send(f"Timed out")
+ else:
+ return await ctx.send(f"Alright, see you later then :3")
+
+ user.remove_jenny(int(100*todo_list.spots*0.5))
+ todo_list.add_spots(10)
+ return await ctx.send("Congrats! You just bought 10 more todo spots for the current todo list!")
+ elif what.name == "timing":
+ if todo_list.has_addon("due_in"):
+ return await ctx.send("You already have this addon!")
+ if user.jenny < 2000:
+ return await ctx.send(f"You don't have enough Jenny to buy this item. You need 2000 Jenny while you currently have {user.jenny}")
+ user.remove_jenny(2000)
+ todo_list.enable_addon("due_in")
+ return await ctx.send("Congrats! You just bought the timing addon for the current todo list! You can now specifiy the `due_in` parameter when adding a todo.")
+ else:
+ if todo_list.has_addon(what.name):
+ return await ctx.send("You already have this addon!")
+ if user.jenny < 1000:
+ return await ctx.send(f"You don't have enough Jenny to buy this item. You need 1000 Jenny while you currently have {user.jenny}")
+ user.remove_jenny(1000)
+ todo_list.enable_addon(what.name)
+ return await ctx.send(f"Successfully bought {what.name} for 1000 Jenny! Customize it with `{self.client.command_prefix(self.client, ctx.message)[2]}todo update {what.name}`")
+
+
+################################################ Give commands ################################################
+
+ @commands.hybrid_group()
+ async def give(self, ctx: commands.Context):
+ if not ctx.invoked_subcommand:
+ return await ctx.send("You need to provide a valid subcommand! Subcommands are: `card`, `lootbox` and `jenny`")
+
+ async def _validate(self, ctx: commands.Context, other: discord.Member) -> Union[discord.Message, Tuple[User, User]]:
+ """Validates if someone is a bot or the author and returns a tuple of users if correct, else a message"""
+ if other == ctx.author:
+ return await ctx.send("You can't give yourself anything!")
+ if other.bot:
+ return await ctx.send("đ¤")
+
+ return User(ctx.author.id), User(other.id)
+
+ @check()
+ @give.command(extras={"category":Category.ECONOMY}, usage="jenny ")
+ @discord.app_commands.describe(
+ other="The user to give jenny to",
+ amount="The amount of jenny to give"
+ )
+ async def jenny(self, ctx: commands.Context, other: discord.Member, amount: int):
+ """If you're feeling generous give another user jenny"""
+
+ if isinstance((val:=await self._validate(ctx, other)), discord.Message):
+ return
+ else:
+ user, o = val
+
+ if amount < 1:
+ return await ctx.send(f"You can't transfer less than 1 Jenny!")
+ if user.jenny < amount:
+ return await ctx.send("You can't transfer more Jenny than you have")
+ o.add_jenny(amount)
+ user.remove_jenny(amount)
+ return await ctx.send(f"âī¸ transferred {amount} Jenny to `{other}`!", allowed_mentions=discord.AllowedMentions.none())
+
+ async def all_cards_autocomplete(
+ self,
+ interaction: discord.Interaction,
+ current: str,
+ ) -> List[discord.app_commands.Choice[str]]:
+ """Autocomplete for all cards"""
+ if not self.cardname_cache:
+ for card in DB.items.find({}):
+ self.cardname_cache[card["_id"]] = card["name"], card["type"]
+
+ name_cards = [(x[0], self.cardname_cache[x[0]][0]) for x in User(interaction.user.id).all_cards if self.cardname_cache[x[0]][0].lower().startswith(current.lower())]
+ id_cards = [(x[0], self.cardname_cache[x[0]][0]) for x in User(interaction.user.id).all_cards if str(x[0]).startswith(current)]
+ name_cards = list(dict.fromkeys(name_cards))
+ id_cards = list(dict.fromkeys(id_cards)) # removing all duplicates from the list
+
+ if current == "": # No ids AND names if the user hasn"t typed anything yet
+ return [discord.app_commands.Choice(name=x[1], value=str(x[0])) for x in name_cards]
+ return [*[discord.app_commands.Choice(name=n, value=str(i)) for i, n in name_cards], *[discord.app_commands.Choice(name=str(i), value=str(i)) for i, _ in id_cards]]
+
+ @check()
+ @give.command(name="card", extras={"category":Category.CARDS}, usage="card ")
+ @discord.app_commands.describe(
+ other="The user to give the card to",
+ card="What card to give"
+ )
+ @discord.app_commands.autocomplete(card=all_cards_autocomplete)
+ async def _card(self, ctx: commands.Context, other: discord.Member, card: str):
+ """If you're feeling generous give another user a card"""
+
+ if isinstance((val:=await self._validate(ctx, other)), discord.Message):
+ return
+ else:
+ user, o = val
+
+ try:
+ item = Card(card).id
+ except CardNotFound:
+ return await ctx.send("Invalid card number")
+ if user.has_any_card(item, False) is False:
+ return await ctx.send("You don't have any not fake copies of this card!")
+ if (len(o.fs_cards) >= 40 and item < 100 and o.has_rs_card(item)) or (len(o.fs_cards) >= 40 and item > 99):
+ return await ctx.send("The user you are trying to give the cards's free slots are full!")
+
+ removed_card = user.remove_card(item)
+ o.add_card(item, clone=removed_card[1]["clone"])
+ return await ctx.send(f"âī¸ gave `{other}` card No. {item}!", allowed_mentions=discord.AllowedMentions.none())
+
+ @check()
+ @give.command(name="lootbox", aliases=["box"], extras={"category":Category.ECONOMY}, usage="lootbox ")
+ @discord.app_commands.describe(
+ other="The user to give the lootbox to",
+ box="What lootbox to give"
+ )
+ async def _lootbox(self, ctx: commands.Context, other: discord.Member, box: str):
+ """If you're feeling generous give another user a lootbox, maybe they'll get lucky'"""
+
+ if isinstance((val:=await self._validate(ctx, other)), discord.Message):
+ return
+ else:
+ user, o = val
+
+ if box.isdigit() and int(box) not in LOOTBOXES:
+ box = self.client.get_lootbox_from_name(box)
+ if not box:
+ return await ctx.send("Invalid lootbox. ")
+
+ if int(box) not in user.lootboxes:
+ return await ctx.send("You don't own this lootbox!")
+ user.remove_lootbox(int(box))
+ o.add_lootbox(int(box))
+ await ctx.send(f"âī¸ gave {other.display_name} the box '{LOOTBOXES[int(box)]['name']}'", allowed_mentions=discord.AllowedMentions.none())
+
+
+
+Cog = Shop
\ No newline at end of file
diff --git a/tests/killua/cogs/small_commands.py b/tests/killua/cogs/small_commands.py
new file mode 100644
index 000000000..7c48e9802
--- /dev/null
+++ b/tests/killua/cogs/small_commands.py
@@ -0,0 +1,351 @@
+import discord
+from discord.ext import commands
+
+import json
+import time
+from random import randint, choice
+import math
+from typing import List
+from urllib.parse import quote
+
+
+from killua.bot import BaseBot
+from killua.static.constants import TOPICS, ANSWERS, ALIASES, UWUS, LANGS, WYR
+from killua.utils.interactions import View, Button
+from killua.utils.checks import check
+from killua.static.enums import Category
+from killua.utils.classes import Guild
+
+class PollSetup(discord.ui.Modal): #lgtm [py/missing-call-to-init]
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(title="Poll setup", *args, **kwargs)
+ self.add_item(discord.ui.TextInput(label="Question", custom_id="question", max_length=256, style=discord.TextStyle.long, placeholder="Are there more doors or wheels in the world?"))
+ self.add_item(discord.ui.TextInput(label="Option 1", custom_id="option:1", max_length=246, placeholder="Doors"))
+ self.add_item(discord.ui.TextInput(label="Option 2", custom_id="option:2", max_length=246, placeholder="Wheels"))
+ self.add_item(discord.ui.TextInput(label="Option 3", custom_id="option:3", max_length=246, placeholder="Both", required=False))
+ self.add_item(discord.ui.TextInput(label="Option 4", custom_id="option:4", max_length=246, placeholder="Neither", required=False))
+
+ async def on_submit(self, interaction: discord.Interaction) -> None:
+ """Called when the modal is submitted"""
+ await interaction.response.defer()
+
+class SmallCommands(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+ self._init_menus()
+
+ def _init_menus(self) -> None:
+ menus = []
+ menus.append(discord.app_commands.ContextMenu(
+ name='uwufy',
+ callback=self.client.callback_from_command(self.uwufy, message=True),
+ ))
+ menus.append(discord.app_commands.ContextMenu(
+ name='translate',
+ callback=self.client.callback_from_command(self.translate, message=True, source="auto"),
+ ))
+
+ for menu in menus:
+ self.client.tree.add_command(menu)
+
+ def hardcoded_aliases(self, text:str) -> str:
+ l = []
+ for w in text.split(' '):
+ if w.lower() in ALIASES:
+ l.append(choice(ALIASES[w.lower()]))
+ continue
+ l.append(w)
+ return ' '.join(l)
+
+ def initial_uwuing(self, text:str) -> str:
+ t = []
+ for w in text.split(' '):
+ chars = [c for c in w]
+ if 'r' in chars:
+ w = w.replace('r', 'w')
+ if 'ng' in chars and randint(1,2) == 1:
+ w = w.replace('ng', 'n')
+ if 'l' in chars and randint(1,2) == 1:
+ w = w.replace('l', 'w')
+ t.append(w)
+ return ' '.join(t)
+
+ def stuttify(self, text:str, stuttering:int):
+ nt = []
+ for p, w in enumerate(text.split(' ')):
+ if p % 2 == 0:
+ if int(len(text.split(' '))*(randint(1, 5)/10))*stuttering*2 < len(text.split(' ')) and len(w) > 2 and w[0] != "\n":
+ nt.append(w[:1]+'-'+w)
+ continue
+ nt.append(w)
+ return ' '.join(nt)
+
+ def cuteify(self, text:str, cuteness:int) -> str:
+ s = text.split(' ')
+ emotes = math.ceil((len([x for x in s if x[-1:] in [',' , '.'] and x[-2:] != '..'])+1)*(cuteness/10))
+ t = []
+ for p, w in enumerate(s):
+ if emotes > 0:
+ if (w[-1:] in [',', '.'] and w[-2:] != '..' and randint(1,10) > 5) or p+1 == len(s):
+ t.append(w[:len(w)-(1 if w[-1:] in [',', '.'] else 0)]+' '+choice(UWUS)+(w[-1:] if p != len(s)-1 else ''))
+ emotes = emotes-1
+ continue
+ t.append(w)
+ return ' '.join(t)
+
+ def build_uwufy(self, text:str, cuteness:int=5, stuttering:int=3) -> str:
+ text = self.hardcoded_aliases(text)
+ stuttered_text = self.stuttify(self.initial_uwuing(text), stuttering)
+ cuteified_text= self.cuteify(stuttered_text, cuteness)
+ return cuteified_text
+
+ @commands.hybrid_group()
+ async def misc(self, _: commands.Context):
+ """A collection of miscellaneous commands."""
+ ...
+
+ @check()
+ @misc.command(aliases=["uwu", "owo", "owofy"], extras={"category":Category.FUN}, usage="uwufy ")
+ @discord.app_commands.describe(text="The text to uwufy")
+ async def uwufy(self, ctx: commands.Context, *, text: str):
+ """Uwufy any sentence you want with dis command, have fun >_<"""
+ has_send_messages_perms = ctx.channel.permissions_for(ctx.author).send_messages
+ # Only do a non epehemeral response with a context menu if the user has send messages perms
+ return await self.client.send_message(ctx, self.build_uwufy(text, stuttering=3, cuteness=3), ephemeral=has_send_messages_perms if hasattr(ctx, "invoked_by_context_menu") else False)
+
+ @check()
+ @misc.command(extras={"category":Category.FUN}, usage="ping")
+ async def ping(self, ctx: commands.Context):
+ """Standard of seeing if the bot is working"""
+ start = time.time()
+ msg = await ctx.send("Pong!")
+ end = time.time()
+ await msg.edit(content = str("Pong in `" + str(1000 * (end - start))) + "` ms")
+
+ @check()
+ @misc.command(extras={"category":Category.FUN}, usage="topic")
+ async def topic(self, ctx: commands.Context):
+ """Sends a conversation starter"""
+ await ctx.send(choice(TOPICS))
+
+ @check()
+ @misc.command(extras={"category":Category.FUN}, usage="hi")
+ async def hi(self, ctx: commands.Context):
+ """This is just here because it was Killua's first command and I can't take that from him"""
+ await ctx.send("Hello " + str(ctx.author))
+
+ @check()
+ @misc.command(name="8ball", extras={"category":Category.FUN}, usage="8ball ")
+ @discord.app_commands.describe(question="The question to ask the magic 8 ball")
+ async def _ball(self, ctx: commands.Context, *, question: str):
+ """Ask Killua anything and he will answer"""
+ embed = discord.Embed.from_dict({
+ "title": f"8ball has spoken đą",
+ "description": f"You asked:\n```\n{question}\n```\nMy answer is:\n```\n{choice(ANSWERS)}```",
+ "footer": {"icon_url": str(ctx.author.avatar.url), "text": f"Asked by {ctx.author}"},
+ "color": 0x1400ff
+ })
+ await self.client.send_message(ctx, embed=embed)
+
+ @check()
+ @misc.command(aliases=["av", "a"], extras={"category":Category.FUN}, usage="avatar ")
+ @discord.app_commands.describe(user="The user to show the avatar of")
+ async def avatar(self, ctx: commands.Context, user: str = None):
+ """Shows the avatar of a user"""
+ if user:
+ user = await self.client.find_user(ctx, user)
+ if not user:
+ return await ctx.send("User not found")
+ else:
+ user = ctx.author
+
+ if not user.avatar:
+ return await ctx.send("User has no avatar")
+
+ embed = discord.Embed.from_dict({
+ "title": f"Avatar of {user}",
+ "image": {"url": str(user.avatar.url)},
+ "color": 0x1400ff
+ })
+ await self.client.send_message(ctx, embed=embed)
+
+ @check()
+ @misc.command(extras={"category":Category.FUN}, usage="invite")
+ async def invite(self, ctx: commands.Context):
+ """Allows you to invite Killua to any guild you have at least `manage server` permissions."""
+ view = discord.ui.View()
+ view.add_item(discord.ui.Button(label="Invite", url=self.client.invite))
+ embed = discord.Embed(
+ title = "Invite",
+ description = f"Invite the bot to your server by clicking on the button. Thank you a lot for supporting me!",
+ color = 0x1400ff
+ )
+ await ctx.send(embed=embed, view=view)
+
+ @check()
+ @misc.command(aliases=["perms"], extras={"category":Category.FUN}, usage="permissions")
+ async def permissions(self, ctx: commands.Context):
+ """Displays the permissions Killua has and has not in the current channel"""
+ permissions = "\n".join([f"{v} {n}" for n, v in ctx.me.guild_permissions])
+ prettier = permissions.replace("_", " ").replace("True", "<:CheckMark:771754620673982484>").replace("False", "<:x_:771754157623214080>")
+ embed = discord.Embed.from_dict({
+ "title": "Bot permissions",
+ "description": prettier,
+ "color": 0x1400ff,
+ "thumbnail": {"url": str(ctx.me.avatar.url)}
+ })
+ try:
+ await ctx.send(embed=embed)
+ except discord.Forbidden: # If embed permission is denied
+ await ctx.send("__Bot permissions__\n\n"+prettier)
+
+ @check()
+ @misc.command(extras={"category":Category.FUN}, usage="vote")
+ async def vote(self, ctx: commands.Context):
+ """Gives you the links you need if you want to vote for Killua, you will get sone Jenny as a reward"""
+ view = discord.ui.View()
+ view.add_item(discord.ui.Button(style=discord.ButtonStyle.grey, url="https://top.gg/bot/756206646396452975/vote", label="top.gg"))
+ view.add_item(discord.ui.Button(style=discord.ButtonStyle.grey, url="https://discordbotlist.com/bots/killua/upvote", label="dbl"))
+ await ctx.send("Thanks for supporting Killua! Vote for him by clicking on the buttons!", view=view)
+
+ async def lang_autocomplete(
+ self,
+ _: commands.Context,
+ current: str
+ ) -> List[discord.app_commands.Choice[str]]:
+ """Returns a list of flags that match the current string since there are too many flags for it to use the options feature"""
+ return [
+ discord.app_commands.Choice(name=i.title(), value=i) for i in LANGS.keys()
+ if i.startswith(current.lower()) or current.lower() in i
+ ][:25]
+
+ @check()
+ @misc.command(extras={"category":Category.FUN}, usage="translate ")
+ @discord.app_commands.describe(
+ source="The language you want to translate from",
+ target="The language you want to translate to",
+ text="The text you want to translate"
+ )
+ @discord.app_commands.autocomplete(source=lang_autocomplete, target=lang_autocomplete)
+ async def translate(self, ctx: commands.Context, source: str, target: str = None, *, text: str):
+ """Translate anything to 20+ languages with this command!"""
+ if source.lower() in LANGS: source = LANGS[source.lower()]
+ if hasattr(ctx, "invoked_by_context_menu") or not target: target = (str(ctx.interaction.locale) if str(ctx.interaction.locale).startswith("zh") else str(ctx.interaction.locale).split("-")[0]) if ctx.interaction else target
+ elif target.lower() in LANGS: target = LANGS[target.lower()]
+
+ if (not target in LANGS.values() and not hasattr(ctx, "invoked_by_context_menu")) or not (source in LANGS.values()):
+ return await ctx.send("Invalid language! This is how to use the command: `" + ctx.command.usage + "`", ephemeral=True)
+
+ if len(source) > 1800:
+ return await ctx.send("Too many characters to translate!", ephemeral=True)
+
+ coded_text = quote(text, safe="")
+ res = await self.client.session.get("http://api.mymemory.translated.net/get?q=" + coded_text + "&langpair=" + source.lower() + "|" + target.lower())
+
+ if not (res.status == 200):
+ return await ctx.send(":x: " + await res.text(), ephemeral=True)
+
+ translation = await res.json()
+ if not "matches" in translation or len(translation["matches"]) < 1:
+ if source == "autodetect":
+ return await ctx.send("Unfortunately the translators language detection is currently malfunctioning, please try again later!", ephemeral=True)
+ return await ctx.send("Translation failed!", ephemeral=hasattr(ctx, "invoked_by_context_menu"))
+
+ embed = discord.Embed.from_dict({
+ "title": f"Translation Successfull",
+ "description": f"```\n{text}```\n`{source}` -> `{target}`\n\n```\n{translation['responseData']['translatedText']}```",
+ "color": 0x1400ff,
+ "footer": {"text": "Confidence: " + str(translation["matches"][0]["quality"]) + "%"}
+ })
+
+ await self.client.send_message(ctx, embed=embed, ephemeral=hasattr(ctx, "invoked_by_context_menu"))
+
+ @check()
+ @misc.command(extras={"category":Category.FUN}, usage="calc ")
+ @discord.app_commands.describe(expression="The expression to calculate")
+ async def calc(self, ctx: commands.Context, *, expression: str = None):
+ """Calculates any equation you give it. Syntax: https://mathjs.org/docs/reference/functions.html"""
+ if not expression:
+ return await ctx.send("Please give me something to evaluate.\n")
+ exprs = str(expression).split("\n")
+ request = {"expr": exprs, "precision": 14}
+
+ r = await self.client.session.post("http://api.mathjs.org/v4/", data=json.dumps(request))
+ answer = await r.json()
+
+ if "error" not in answer or "result" not in answer:
+ return await ctx.send("An unknown error occurred during calculation!")
+ if answer["error"]:
+ return await ctx.send("The following error occured while calculating:\n`{}`".format(answer["error"]))
+ await self.client.send_message(ctx, "Result{}:\n```\n{}\n```".format("s" if len(exprs) > 1 else "", "\n".join(answer["result"])))
+
+ @check()
+ @misc.command(extras={"category":Category.FUN}, usage="poll")
+ async def poll(self, ctx: commands.Context):
+ """Creates a poll"""
+ if not ctx.interaction:
+ view = View(ctx.author.id)
+ view.add_item(Button(style=discord.ButtonStyle.green, label="Setup"))
+ msg = await ctx.send("Please press the button to setup the poll", view=view)
+ await view.wait()
+
+ if view.timed_out:
+ return await msg.delete()
+ else:
+ await msg.delete()
+ ctx.interaction = view.interaction
+
+ modal = PollSetup()
+ await ctx.interaction.response.send_modal(modal)
+
+ timed_out = await modal.wait()
+
+ if timed_out:
+ return
+
+ view = discord.ui.View(timeout=None)
+
+ embed = discord.Embed(title="Poll", description=modal.children[0].value, color=0x1400ff)
+ embed.set_footer(text=f"Poll by {ctx.author}", icon_url=ctx.author.avatar.url if ctx.author.avatar else ctx.author.default_avatar.url)
+
+ for pos, child in enumerate(modal.children):
+ if child.value and child.label.startswith("Option"):
+ embed.add_field(name=f"{pos}) " + child.value + " `[0 votes]`", value="No votes", inline=False)
+ item = discord.ui.Button(style=discord.ButtonStyle.blurple, label=f"Option {pos}", custom_id=f"poll:opt-{pos}:")
+ view.add_item(item)
+
+ close_item = discord.ui.Button(style=discord.ButtonStyle.red, label="Close Poll", custom_id=f"poll:close:{self.client._encrypt(ctx.author.id, smallest=False)}:")
+ view.add_item(close_item)
+
+ poll = await ctx.send(embed=embed, view=view)
+
+ if (guild := Guild(ctx.guild.id)).is_premium:
+ option_count = len([i for i in modal.children if i.value and i.label.startswith("Option")])
+ guild.add_poll(str(poll.id), {"author": ctx.author.id, "votes": {str(i): [] for i in range(option_count)}})
+
+ @check()
+ @misc.command(extras={"category":Category.FUN}, usage="wyr")
+ async def wyr(self, ctx: commands.Context):
+ """Asks a random would you rather question and allows you to vote."""
+
+ view = discord.ui.View(timeout=None)
+
+ embed = discord.Embed(title="Would you rather...", color=0x1400ff)
+ embed.set_footer(text=f"Command ran by {ctx.author}", icon_url=ctx.author.avatar.url if ctx.author.avatar else ctx.author.default_avatar.url)
+ embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/761621578458202122/1035249833335861308/unknown.png")
+
+ A, B = choice(WYR)
+
+ embed.add_field(name="A) " + A + " `[0 people]`", value="No takers", inline=False)
+ embed.add_field(name="B) " + B + " `[0 people]`", value="No takers", inline=False)
+
+ itemA = discord.ui.Button(style=discord.ButtonStyle.blurple, label="Option A", custom_id=f"wyr:opt-a:")
+ itemB = discord.ui.Button(style=discord.ButtonStyle.blurple, label="Option B", custom_id=f"wyr:opt-b:")
+
+ view.add_item(itemA).add_item(itemB)
+
+ await ctx.send(embed=embed, view=view)
+
+Cog = SmallCommands
\ No newline at end of file
diff --git a/tests/killua/cogs/tags.py b/tests/killua/cogs/tags.py
new file mode 100644
index 000000000..10649d0e4
--- /dev/null
+++ b/tests/killua/cogs/tags.py
@@ -0,0 +1,322 @@
+import discord
+from discord.ext import commands
+from datetime import datetime
+from typing import List
+import math
+
+from killua.bot import BaseBot
+from killua.static.constants import DB
+from killua.static.enums import Category
+from killua.utils.classes import Guild
+from killua.utils.checks import check
+from killua.utils.paginator import Paginator
+
+class Tag():
+ def __init__(self, guild_id: int, tag_name: str):
+ guild = DB.guilds.find_one({"id": guild_id})
+ if guild is None:
+ self.found = False
+ return
+ if not "tags" in guild:
+ self.found = False
+ return
+
+ self.tags: list = guild["tags"]
+
+ if not tag_name.lower() in [r[0] for r in self.tags]:
+ self.found = False
+ return
+
+ self.indx: int = [r[0] for r in self.tags].index(tag_name.lower())
+ tag = self.tags[self.indx]
+
+ self.guild_id = guild_id
+ self.found = True
+ self.name = tag[1]["name"] # By saving it that way it is non case sensitive when searching but keeps case sensitivity when displayed
+ self.created_at = tag[1]["created_at"]
+ self.owner = tag[1]["owner"]
+ self.content = tag[1]["content"]
+ self.uses = tag[1]["uses"]
+
+ def update(self, new_content) -> None:
+ self.tags[self.indx][1]["content"] = new_content
+ DB.guilds.update_one({"id": self.guild_id}, {"$set": {"tags": self.tags}})
+
+ def delete(self) -> None:
+ self.tags.remove(self.tags[self.indx])
+ DB.guilds.update_one({"id": self.guild_id}, {"$set": {"tags": self.tags}})
+
+ def add_use(self) -> None:
+ self.tags[self.indx][1]["uses"] = self.tags[self.indx][1]["uses"]+1
+ DB.guilds.update_one({"id": self.guild_id}, {"$set": {"tags": self.tags}})
+
+ def transfer(self, to: int) -> None:
+ """Transfers the ownership of a tag to the new id"""
+ self.tags[self.indx][1]["owner"] = to
+ DB.guilds.update_one({"id": self.guild_id}, {"$set": {"tags": self.tags}})
+
+class Member():
+
+ def __init__(self, user_id: int, guild_id: int):
+ guild = DB.guilds.find_one({"id": guild_id})
+
+ if guild is None:
+ self.has_tags = False
+ return
+
+ if not "tags" in guild:
+ self.has_tags = False
+ return
+
+ tags:list = guild["tags"]
+ if not user_id in [r[1]["owner"] for r in tags]:
+ self.has_tags = False
+ return
+
+ owned_tags:list = []
+ for x in tags:
+ owned_tags.append([x[1]["name"], [x[1]["uses"]]])
+
+ self.tags = owned_tags
+ self.has_tags = True
+
+class Tags(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+ self._init_menus()
+
+ def _init_menus(self) -> None:
+ menus = []
+ menus.append(discord.app_commands.ContextMenu(
+ name='tags',
+ callback=self.client.callback_from_command(self.user, message=False)
+ ))
+
+ for menu in menus:
+ self.client.tree.add_command(menu)
+
+ def _build_embed(self, ctx: commands.Context, content: list, page: int, user: discord.User=None) -> discord.Embed:
+
+ if len(content)-page*10+10 > 10:
+ final_tags = content[page*10-10:-(len(content)-page*10)]
+ elif len(content)-page*10+10 <= 10:
+ final_tags = content[-(len(content)-page*10+10):]
+
+ embed = discord.Embed.from_dict({
+ "title": f"Top tags owned by {user.name}" if user else f"Top tags of guild {ctx.guild.name}",
+ "description": "\n".join(final_tags),
+ "color": 0x1400ff,
+ "thumbnail": {"url": str(user.avatar.url) if user else str(ctx.guild.icon.url)}
+ })
+ return embed
+
+ async def tag_autocomplete(
+ self,
+ interaction: discord.Interaction,
+ current: str,
+ ) -> List[discord.app_commands.Choice[str]]:
+ """Returns a list of tags that match the message. """
+ guild = Guild(interaction.guild.id)
+ tags: list = guild.tags
+
+ return [
+ discord.app_commands.Choice(name=t[1]["name"], value=t[1]["name"]) for t in tags
+ if current.lower() in t[0] or current in t[0]
+ ][:25]
+
+ @commands.hybrid_group(hidden=True, extras={"category":Category.TAGS})
+ async def tag(self, _: commands.Context):
+ """Tag commands. Only usable in premium guilds."""
+ ...
+
+ @check()
+ @commands.guild_only()
+ @tag.command(extras={"category":Category.TAGS}, usage="create ")
+ @discord.app_commands.describe(name="The name of the tag you want to create")
+ async def create(self, ctx: commands.Context, *, name: str):
+ """Create a tag with this command"""
+ guild = DB.guilds.find_one({"id": ctx.guild.id})
+ member = Member(ctx.author.id, ctx.guild.id)
+
+ if not Tag(ctx.guild.id, name).found is False:
+ tag = Tag(ctx.guild.id, name)
+ user = ctx.guild.get_member(tag.owner)
+ return await ctx.send(f"This tag already exists and is owned by {user or '`user left`'}")
+
+ if "tags" in guild:
+ tags = guild["tags"]
+ else:
+ tags = []
+
+ if len(tags) >= 10 and not Guild(ctx.guild.id).is_premium:
+ return await ctx.send("Your server has reached the limit of tags! Buy premium to up to 250 tags!")
+
+ if member.has_tags:
+ if len(member.tags) > 50:
+ return await ctx.send("You can't own more than 15 tags on a guild, consider deleting one")
+
+ if len(name) > 30:
+ return await ctx.send("The tag title has too many characters!")
+
+ content = await self.client.get_text_response(ctx, "What should the description of the tag be?", timeout=600, min_length=1, max_length=2000)
+ if not content: return
+
+ if len(content) > 2000:
+ return await ctx.send("Too many characters!")
+
+ tags.append([name.lower(), {"name": name, "created_at": datetime.now(), "owner": ctx.author.id, "content": content, "uses": 0}])
+ DB.guilds.update_one({"id": ctx.guild.id}, {"$set": {"tags": tags}})
+
+ return await ctx.send(f"Successfully created tag `{name}`")
+
+ @check()
+ @commands.guild_only()
+ @tag.command(extras={"category":Category.TAGS}, usage="delete ")
+ @discord.app_commands.describe(name="The name of the tag you want to delete")
+ @discord.app_commands.autocomplete(name=tag_autocomplete)
+ async def delete(self, ctx: commands.Context, *, name: str):
+ """Delete a tag you own with this command or any tag if you have manage guild permissions"""
+ tag = Tag(ctx.guild.id, name)
+
+ if tag is None:
+ return await ctx.send("A tag with that name does not exist!")
+
+ if ctx.channel.permissions_for(ctx.author).manage_guild is False and not ctx.author.id == tag.owner:
+ return await ctx.send("You need to be tag owner or have the `manage server` permission to delete tags!")
+
+ tag.delete()
+ await ctx.send(f"Successfully deleted tag `{tag.name}`")
+
+ @check()
+ @commands.guild_only()
+ @tag.command(extras={"category":Category.TAGS}, usage="edit ")
+ @discord.app_commands.describe(name="The name of the tag you want to edit")
+ @discord.app_commands.autocomplete(name=tag_autocomplete)
+ async def edit(self, ctx: commands.Context, *, name: str):
+ """Chose wrong tag description? Edit a tag's description with this command"""
+ tag = Tag(ctx.guild.id, name)
+
+ if tag.found is False:
+ return await ctx.send("A tag with that name does not exist!")
+
+ if not ctx.author.id == tag.owner:
+ return await ctx.send("You need to be tag owner to edit this tag!")
+
+ content = await self.client.get_text_response(ctx, "What should the new description to be?", timeout=600, min_length=1, max_length=2000)
+
+ if len(content) > 2000:
+ return await ctx.send("Too many characters!")
+
+ tag.update(content)
+ return await ctx.send(f"Successfully updated tag `{tag.name}`")
+
+ @check()
+ @commands.guild_only()
+ @tag.command(extras={"category":Category.TAGS}, usage="transfer ")
+ @discord.app_commands.describe(user="The user to tranfer the tag ownership to", name="The name of the tag you want to transfer")
+ @discord.app_commands.autocomplete(name=tag_autocomplete)
+ async def transfer(self, ctx: commands.Context, user: discord.Member, *, name: str):
+ """Transfer a tag you own to another user"""
+ tag = Tag(ctx.guild.id, name)
+
+ if tag.found is False:
+ return await ctx.send("A tag with that name does not exist!", ephemeral=True)
+
+ if not ctx.author.id == tag.owner:
+ return await ctx.send("You need to be tag owner to transfer this tag!", ephemeral=True)
+
+ tag.transfer(user.id)
+ return await ctx.send(f"Successfully transferred tag `{tag.name}` to {user}", allowed_mentions=discord.AllowedMentions.none())
+
+ @check()
+ @commands.guild_only()
+ @tag.command(extras={"category":Category.TAGS}, usage="get ")
+ @discord.app_commands.describe(name="The name of the tag you want look at")
+ @discord.app_commands.autocomplete(name=tag_autocomplete)
+ async def get(self, ctx: commands.Context, *, name: str):
+ """Get the content of any tag"""
+ tag = Tag(ctx.guild.id, name)
+ if tag.found is False:
+ return await ctx.send("This tag doesn't exist")
+ tag.add_use()
+ return await ctx.send(tag.content, allowed_mentions=discord.AllowedMentions.none(), reference=ctx.message.reference or ctx.message)
+
+ @check()
+ @commands.guild_only()
+ @tag.command(extras={"category":Category.TAGS}, usage="info ")
+ @discord.app_commands.describe(name="The name of the tag to get info about")
+ @discord.app_commands.autocomplete(name=tag_autocomplete)
+ async def info(self, ctx: commands.Context, *, name: str):
+ """Get information about any tag"""
+ tag = Tag(ctx.guild.id, name.lower())
+ if tag.found is False:
+ return await ctx.send("There is no tag with that name!")
+
+ guild = DB.guilds.find_one({"id": ctx.guild.id})
+ owner = self.client.get_user(tag.owner) or await self.client.fetch_user(tag.owner)
+
+ s = sorted(zip([x[0] for x in guild["tags"]], [x[1]["uses"] for x in guild["tags"]]))
+ rank = [x[0] for x in s].index(name.lower())+1
+ embed = discord.Embed.from_dict({
+ "title": f"Information about tag \"{tag.name}\"",
+ "description": f"**Tag owner:** `{str(owner)}`\n\n**Created on**: \n\n**Uses:**Â `{tag.uses}`\n\n**Tag rank:** `{rank}`",
+ "color": 0x1400ff,
+ "thumbnail": {"url": str(owner.avatar.url)}
+ })
+ await ctx.send(embed=embed)
+
+ @check()
+ @commands.guild_only()
+ @tag.command(aliases=["l"], extras={"category":Category.TAGS}, usage="list")
+ @discord.app_commands.describe(page="The page of the tag list you want to view")
+ async def list(self, ctx: commands.Context, page: int = 1):
+ """Get a list of tags on the current server sorted by uses"""
+ guild = DB.guilds.find_one({"id": ctx.guild.id})
+ if not "tags" in guild:
+ return await ctx.send("Seems like this server doesn't have any tags!")
+
+ s = sorted(zip([x[1]["name"] for x in guild["tags"]], [x[1]["uses"] for x in guild["tags"]]))
+
+ if len(guild["tags"]) == 0:
+ return await ctx.send("Seems like this server doesn't have any tags!")
+
+ if math.ceil(len(guild["tags"])/10) < page:
+ return await ctx.send("Invalid page")
+
+ tags = [f"Tag `{n}` with `{u}` uses" for n, u in s]
+
+ if len(guild["tags"]) <= 10:
+ return await ctx.send(embed=self._build_embed(ctx, tags, page))
+
+ def make_embed(page, *_):
+ return self._build_embed(ctx, tags, page)
+
+ await Paginator(ctx, tags, func=make_embed, max_pages=math.ceil(len(tags)/10)).start()
+
+ @check()
+ @commands.guild_only()
+ @tag.command(extras={"category":Category.TAGS}, usage="user ")
+ @discord.app_commands.describe(user="User you want to see tags of")
+ async def user(self, ctx: commands.Context, user: discord.Member):
+ """Get the tags a user own sorted by uses"""
+ if hasattr(ctx, "invoked_by_context_menu"): # user is a string if invoked by a context menu
+ user = await self.client.find_user(ctx, user)
+
+ member = Member(user.id, ctx.guild.id)
+ if member.has_tags is False:
+ return await ctx.send("This user currently does not have any tags!", ephemeral=True)
+ z = sorted(zip([x[1] for x in member.tags], [x[0] for x in member.tags]), reverse=True)
+ g:list = []
+ for i in z:
+ uses, name = i
+ g.append(f"`{name}` with `{uses}` uses")
+ if len(g) <= 10:
+ return await ctx.send(embed=self._build_embed(ctx, g, 1, user), ephemeral=hasattr(ctx, "invoked_by_context_menu"))
+
+ def make_embed(page, _, pages):
+ return self._build_embed(ctx, pages, page, user)
+
+ await Paginator(ctx, g, func=make_embed, max_pages=math.ceil(len(g)/10), ephemeral=hasattr(ctx, "invoked_by_context_menu")).start()
+
+Cog = Tags
diff --git a/tests/killua/cogs/todo.py b/tests/killua/cogs/todo.py
new file mode 100644
index 000000000..9f690ae2c
--- /dev/null
+++ b/tests/killua/cogs/todo.py
@@ -0,0 +1,769 @@
+import discord
+from discord.ext import commands, tasks
+from datetime import datetime
+import re
+import math
+from typing import Union, Optional, List
+
+from killua.bot import BaseBot
+from killua.static.enums import Category, TodoDeleteWhenDone, TodoStatus, TodoPermissions
+from killua.static.constants import DB, URL_REGEX, editing, REPORT_CHANNEL
+from killua.utils.checks import check, blcheck
+from killua.utils.classes import TodoList, Todo, User, TodoListNotFound
+from killua.utils.interactions import ConfirmButton, Button
+from killua.utils.paginator import Paginator
+from killua.utils.converters import TimeConverter
+
+class TodoSystem(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+ self._init_menus()
+
+ @commands.Cog.listener()
+ async def on_ready(self):
+ self.check_todo_dues.start()
+
+ def _init_menus(self) -> None:
+ menus = []
+ menus.append(discord.app_commands.ContextMenu(
+ name='Add as todo',
+ callback=self.client.callback_from_command(self.add, message=True)
+ ))
+
+ for menu in menus:
+ self.client.tree.add_command(menu)
+
+ @tasks.loop(seconds=60)
+ async def check_todo_dues(self):
+ """
+ Checks if any todo's are due and sends a message to the owner if so
+ """
+ for todo_list in [TodoList(r["_id"]) for r in DB.todo.find()]:
+ for todo in todo_list.todos:
+
+ if "due_at" in todo and todo["due_at"] and todo["due_at"] < datetime.now() and not todo["notified"]:
+ to_be_notifed = []
+ to_be_notifed.append(self.client.get_user(todo["added_by"]))
+ to_be_notifed.extend([self.client.get_user(u) for u in todo["assigned_to"]])
+
+ for user in to_be_notifed:
+ if user:
+ try:
+ embed = discord.Embed.from_dict({
+ "title": "Todo due",
+ "description": f"Your todo `{todo['todo']}` is due\nAdded ",
+ "color": todo_list.color or 0x1400ff,
+ "footer": {"text": f"From todo list: {todo_list.name} (ID: {todo_list.id})", "icon_url": todo_list.thumbnail}
+ })
+ await user.send(embed=embed)
+ except discord.HTTPException:
+ continue # If dms are closed we don't want to interrupt the loop
+
+ todo["notified"] = True
+ todo_list.set_property("todos", todo_list.todos)
+
+ @check_todo_dues.before_loop
+ async def before_check_todo_dues(self):
+ await self.client.wait_until_ready()
+
+ async def _get_user(self, u: int) -> discord.User:
+ """Gets a user from cache if possible, else makes an API request"""
+ r = self.client.get_user(u)
+ if not r:
+ r = await self.client.fetch_user(u)
+ return r
+
+ async def _build_embed(self, todo_list: TodoList, page: int = None) -> discord.Embed:
+ """Creates an embed for a todo list page"""
+ owner = await self._get_user(todo_list.owner)
+ l = todo_list.todos
+ desc = []
+
+ if len(todo_list) > 10 and page:
+ max_pages = math.ceil(len(l)/10)
+ final_todos = []
+
+ if len(l)-page*10+10 > 10:
+ final_todos = l[page*10-10:-(len(l)-page*10)]
+ elif len(l)-page*10+10 <= 10:
+ final_todos = l[-(len(l)-page*10+10):]
+
+ async def assigned_users(t: Todo) -> str:
+ at = []
+ for user in t.assigned_to:
+ person = await self._get_user(user)
+ at.append(person)
+ return f"\n`Assigned to: {', '.join([str(x) for x in at])}`"
+
+ for n, t in enumerate(final_todos if page else l, page*10-10 if page else 0):
+ t = Todo(n+1, todo_list.id)
+ ma = f"\n`Marked as {t.marked}`" if t.marked else ""
+ due = f"\nDue " if t.due_at else ""
+ desc.append(f"{n+1}) {t.todo}{ma}{due}{await assigned_users(t) if len(t.assigned_to) > 0 else ''}")
+ desc = "\n".join(desc) if len(desc) > 0 else "No todos"
+
+
+ embed = discord.Embed.from_dict({
+ "title": f"To-do list \"{todo_list.name}\" (ID: {todo_list.id})",
+ "description": f"{f'*Page {page}/{max_pages}*' if page else ''}\n{desc}",
+ "color": todo_list.color or 0x1400ff,
+ "footer": {"icon_url": str(owner.avatar.url), "text": f"Owned by {owner}"}
+ })
+
+ if todo_list.thumbnail:
+ embed.set_thumbnail(url=todo_list.thumbnail)
+
+ return embed
+
+ async def todo_info_embed_generator(self, ctx: commands.Context, list_id: Union[int, str]) -> discord.Message:
+ """outsourcing big embed production đ """
+ try:
+ todo_list = TodoList(list_id)
+ except TodoListNotFound:
+ return await ctx.send("No todo list with this id exists")
+ if not todo_list.has_view_permission(ctx.author.id):
+ return await ctx.send("You don't have permission to view infos about this list!")
+
+ todo_list.add_view(ctx.author.id)
+
+ owner = await self._get_user(todo_list.owner)
+ created_at = f"" if isinstance(todo_list.created_at, datetime) else todo_list.created_at
+
+ embed = discord.Embed.from_dict({
+ "title": f"Information for the todo list \"{todo_list.name}\" (ID: {todo_list.id})",
+ "description": f"{todo_list.description if todo_list.description else ''}" +\
+ f"**Owner**: `{owner}`\n\n" +\
+ f"**Created on:** {created_at}\n\n" +\
+ f"**Custom ID**: `{todo_list.custom_id or 'No custom id'}`\n\n" +\
+ f"**Status**: `{todo_list.status}`\n\n" +\
+ f"**Editors**: `{', '.join([str(await self._get_user(u)) for u in todo_list.editor]) if len(todo_list.editor) > 0 else 'Nobody has editor perissions'}`\n" +\
+ f"**Viewers**: `{', '.join([str(await self._get_user(u)) for u in todo_list.viewer]) if len(todo_list.viewer) > 0 else 'Nobody has viewer permissions'}`\n\n" +\
+ f"**Todos**: `{len(todo_list)}/{todo_list.spots}`",
+ "color": todo_list.color or 0x1400ff,
+ "footer": {"text": f"{todo_list.views} view{'s' if todo_list.views != 1 else ''}"}
+ })
+ if todo_list.thumbnail:
+ embed.set_thumbnail(url=todo_list.thumbnail)
+
+ return await self.client.send_message(ctx, embed=embed)
+
+ async def single_todo_info_embed_generator(self, ctx: commands.Context, list_id: Union[int, str], task_id: int) -> discord.Message:
+ """outsourcing big embed production đ """
+ try:
+ todo_list = TodoList(list_id)
+ except TodoListNotFound:
+ return await ctx.send("No todo list with this id exists")
+ try:
+ todo_task = Todo(task_id, list_id)
+ except Exception:
+ return await ctx.send("A todo task with that id is not on the list")
+
+ if not todo_list.has_view_permission(ctx.author.id):
+ return await ctx.send("You don't have permission to view infos about this list!")
+
+ todo_task.add_task_view(ctx.author.id, todo_task.position)
+
+ addist = await self._get_user(todo_task.added_by)
+ added_on = f"" if isinstance(todo_task.added_on, datetime) else todo_task.added_on
+
+ mark_log = "\n".join([f"""Changed to: `{x["change"]}`\nBy `{await self._get_user(x["author"])}`\nOn""" + (f""
+ if isinstance(x["date"], datetime) else f"`{x['date']}`") for x in todo_task.mark_log[3:]])
+
+ mark_log = mark_log if len(mark_log) > 0 else "No recent changes"
+
+ due = f"**Due** \n" if todo_task.due_at else ""
+ embed = discord.Embed.from_dict({
+ "title": f"Information for the todo task {task_id}",
+ "description": f"**Added by**: `{addist}`\n\n" +\
+ f"**Content**: {todo_task.todo}\n\n" +\
+ f"**Currently marked as**: `{todo_task.marked or 'Not currently marked'}`\n\n" +\
+ f"**Assigned to**: `{', '.join([str(await self._get_user(u)) for u in todo_task.assigned_to]) if len(todo_task.assigned_to) > 0 else 'unassigned'}`\n\n" +\
+ f"**Added on:** {added_on}\n{due}\n" +\
+ f"**Latest changes marks**:\n" +\
+ f"{mark_log}",
+ "color": todo_list.color or 0x1400ff,
+ "footer": {"text": f"{todo_task.views} view{'s' if todo_task.views != 1 else ''}"}
+ })
+ if todo_list.thumbnail:
+ embed.set_thumbnail(url=todo_list.thumbnail)
+ return await self.client.send_message(ctx, embed=embed)
+
+ async def _edit_check(self, ctx: commands.Context) -> Union[None, TodoList]:
+ """A generic check before every command that edits a todo list property"""
+ try:
+ list_id = editing[ctx.author.id]
+ except KeyError:
+ await ctx.send(f"You have to be in the editor mode to use this command! Use `/todo edit `", allowed_mentions=discord.AllowedMentions.none())
+ else:
+ todo_list = TodoList(list_id)
+ return todo_list
+
+ @commands.hybrid_group(hidden=True, extras={"category":Category.TODO})
+ async def todo(self, _: commands.Context):
+ """All commands relating to todo lists"""
+ ...
+
+ @check(10)
+ @todo.command(extras={"category":Category.TODO}, usage="create")
+ @discord.app_commands.describe(
+ name="The name of the todo list",
+ status="Wether a todo list is publicly viewable or not",
+ delete_when_done="Wether a todo should be deleted when marked done",
+ custom_id="A custom id for the todo list- Premium only",
+ )
+ async def create(self, ctx: commands.Context, name: str, status: TodoStatus, delete_when_done: TodoDeleteWhenDone, custom_id: Optional[str] = None):
+ """Lets you create your todo list in an interactive menu"""
+
+ user_todo_lists = [x for x in DB.todo.find({"owner": ctx.author.id})]
+
+ if len(user_todo_lists) == 5:
+ return await ctx.send("You can currently not own more than 5 todo lists", ephermeral=True)
+
+ user = User(ctx.author.id)
+ if len(name) > 30:
+ return await ctx.send("Name can't be longer than 20 characters", ephemeral=True)
+
+ if custom_id and not user.is_premium:
+ return await ctx.send("You need to be a premium user to use custom ids", ephemeral=True)
+
+ if len(custom_id) > 20:
+ return await ctx.send("Your custom id can have max 20 characters", ephemeral=True)
+
+ if custom_id.lower().isdigit():
+ return await ctx.send("Your custom id needs to contain at least one character that isn't an integer", ephemeral=True)
+
+ try:
+ TodoList(custom_id.lower())
+ except TodoListNotFound:
+ pass
+ else:
+ return await ctx.send("This custom id is already taken", ephemeral=True)
+
+ l = TodoList.create(owner=ctx.author.id, title=name, status=status.name, done_delete=delete_when_done.name == "yes", custom_id=custom_id)
+ await ctx.send(f"Created the todo list with the name {name}. You can look at it and edit it through the id `{l.id}`" + (f" or through your custom id {custom_id}" if custom_id else ""), allowed_mentions=discord.AllowedMentions.none())
+
+ @check()
+ @todo.command(extras={"category":Category.TODO}, usage="view ")
+ @discord.app_commands.describe(todo_id="The id of the todo list you want to view")
+ async def view(self, ctx: commands.Context, todo_id: str = None):
+ """Allows you to view what is on any todo list- provided you have the permissions"""
+ if todo_id is None:
+ todo_list = await self._edit_check(ctx)
+ if todo_list is None: return
+ else:
+ try:
+ todo_list = TodoList(todo_id)
+ except TodoListNotFound:
+ return await ctx.send("No todo list with specified ID found")
+
+ if not todo_list.has_view_permission(ctx.author.id):
+ return await ctx.send("This is a private list you don't have the permission to view")
+ todo_list.add_view(ctx.author.id)
+
+ if len(todo_list) <= 10:
+ return await ctx.send(embed=await self._build_embed(todo_list))
+
+ async def make_embed(page, _, pages):
+ return await self._build_embed(pages, page)
+ await Paginator(ctx, todo_list, max_pages=math.ceil(len(todo_list)/10),func=make_embed).start()
+
+ @check()
+ @todo.command(extras={"category":Category.TODO}, usage="clear")
+ async def clear(self, ctx: commands.Context):
+ """Clears all todos from a todo list"""
+ try:
+ list_id = editing[ctx.author.id]
+ except KeyError:
+ return await ctx.send("You have to be in the editor mode to use this command without providing an id! Use `/todo edit `")
+
+ todo_list = TodoList(list_id)
+ if not todo_list.has_edit_permission(ctx.author.id):
+ return await ctx.send("You have to be added as an editor to this list to use this command")
+ todo_list.clear()
+ await ctx.send("Done! Cleared all your todos")
+
+ @check(1)
+ @todo.command(extras={"category":Category.TODO}, usage="info ")
+ @discord.app_commands.describe(
+ todo_or_task_id="The task or todo list you want information about",
+ task_id="The id of the tasks you want information about",
+ )
+ async def info(self, ctx: commands.Context, todo_or_task_id: str = None, task_id: int = None):
+ """This gives you info about either a todo task or list"""
+ if task_id is None:
+ if todo_or_task_id is None:
+ todo_list = await self._edit_check(ctx)
+ if not todo_list: return
+ return await self.todo_info_embed_generator(ctx, todo_list.id)
+ try:
+ list_id = editing[ctx.author.id]
+ except KeyError:
+ return await self.todo_info_embed_generator(ctx, todo_or_task_id)
+ return await self.single_todo_info_embed_generator(ctx, list_id, int(todo_or_task_id))
+ elif task_id:
+ return await self.single_todo_info_embed_generator(ctx, todo_or_task_id, int(task_id))
+
+ @check()
+ @todo.command(extras={"category":Category.TODO}, usage="edit ")
+ @discord.app_commands.describe(list_id="The id of the todo list you want to edit")
+ async def edit(self, ctx: commands.Context, list_id: str):
+ """The command with which you can change stuff on your todo list"""
+ if ctx.author.id in editing and editing[ctx.author.id] == list_id:
+ return await ctx.send("You are already editing this list!")
+ try:
+ todo_list = TodoList(list_id)
+ except TodoListNotFound:
+ return await ctx.send("No todo list with this id exists")
+
+ if not todo_list.has_edit_permission(ctx.author.id):
+ return await ctx.send("You do not have the permission to edit this todo list")
+
+ editing[ctx.author.id] = todo_list.id
+ await ctx.send(f"You are now in editor mode for todo list '{todo_list.name}'", allowed_mentions=discord.AllowedMentions.none())
+
+ @check()
+ @todo.command(extras={"category":Category.TODO}, usage="update ")
+ @discord.app_commands.describe(
+ name="The name of the todo list you want to change",
+ status="The status of the todo list you want to change",
+ delete_when_done="Whether you want to delete a todo when it's done",
+ custom_id="The custom id of the todo list you want to change",
+ color="The color of the todo list you want to change",
+ thumbnail="The thumbnail of the todo list you want to change",
+ description="The description of the todo list you want to change"
+ )
+ async def update(
+ self,
+ ctx: commands.Context,
+ name: Optional[str] = None,
+ status: Optional[TodoStatus] = None,
+ delete_when_done: Optional[TodoDeleteWhenDone] = None,
+ custom_id: Optional[str] = None,
+ color: Optional[str] = None,
+ thumbnail: Optional[str] = None,
+ description: Optional[str] = None
+ ):
+ """Update your todo list with this command (Only in editor mode)"""
+
+ res = await self._edit_check(ctx)
+ if not res: return
+
+ updated = []
+
+ user = User(ctx.author.id)
+ if name:
+ if len(name) > 30:
+ return await ctx.send("Name can't be longer than 20 characters", ephemeral=True)#
+ else:
+ res.set_property("title", name)
+ updated.append("title")
+
+ if status:
+ res.set_property("status", status.name)
+ updated.append("status")
+
+ if delete_when_done:
+ res.set_property("delete_when_done", delete_when_done.name == "yes")
+ updated.append("delete_when_done")
+
+ if custom_id:
+
+ if not user.is_premium:
+ return await ctx.send("You need to be a premium user to use custom ids", ephemeral=True)
+
+ if len(custom_id) > 20:
+ return await ctx.send("Your custom id can have max 20 characters", ephemeral=True)
+
+ if custom_id.lower().isdigit():
+ return await ctx.send("Your custom id needs to contain at least one character that isn't an integer", ephemeral=True)
+
+ try:
+ TodoList(custom_id.lower())
+ except TodoListNotFound:
+ pass
+ else:
+ return await ctx.send("This custom id is already taken", ephemeral=True)
+
+ res.set_property("custom_id", custom_id.lower())
+ updated.append("custom_id")
+
+ if color:
+ if not res.has_addon("color"):
+ return await ctx.send("You can't customize this property, you need to buy it in the shop", ephemeral=True)
+ if color.lower() == "none":
+ res.set_property("color", None)
+ else:
+ try:
+ res.set_property("color", int(color, 16))
+ updated.append("color")
+ except ValueError:
+ return await ctx.send("Color needs to be a valid hexadecimal number", ephemeral=True)
+
+ if thumbnail:
+ if not res.has_addon("thumbnail"):
+ return await ctx.send("You can't customize this property, you need to buy it in the shop", ephemeral=True)
+ search_url = re.search(URL_REGEX, thumbnail)
+
+ if search_url:
+ image = re.search(r"png|jpg|gif|svg", thumbnail)
+ else:
+ await ctx.send("You didn't provide a valid url with an image! Please make sure your url is valid")
+
+ if image:
+ res.set_property("thumbnail", thumbnail)
+ updated.append("thumbnail")
+ else:
+ await ctx.send("You didn't provide a valid url with an image! Please make sure your url is valid")
+
+ if description:
+ if not res.has_addon("description"):
+ return await ctx.send("You can't customize this property, you need to buy it in the shop", ephemeral=True)
+ if len(description) > 200:
+ return await ctx.send("Description can't be longer than 200 characters", ephemeral=True)
+ else:
+ res.set_property("description", description)
+ updated.append("description")
+
+ await ctx.send(f"Successfully updated {updated.join(', ')} of your todo list!", allowed_mentions=discord.AllowedMentions.none())
+
+ @check()
+ @todo.command(extras={"category":Category.TODO}, usage="remove ")
+ @discord.app_commands.describe(todo_numbers="The todo tasks you want to delete")
+ async def remove(self, ctx: commands.Context, todo_numbers: commands.Greedy[int]):
+ """Remove a todo with this command. YAY, GETTING THINGS DONE!! (Only in editor mode)"""
+ todo_list = await self._edit_check(ctx)
+ if not todo_list: return
+
+ if len(todo_numbers) == 0:
+ return await ctx.send("No valid numbers provided")
+
+ todos = todo_list.todos
+
+ failed = []
+ for n in todo_numbers:
+ if not todo_list.has_todo(n):
+ failed.append(n)
+ continue
+ todos.pop(n-1)
+ if len(todo_numbers) == len(failed):
+ return await ctx.send("All inputs are invalid task ids. Please try again.")
+
+ todo_list.set_property("todos", todos)
+ return await ctx.send(f"You removed todo number{'s' if len(todo_numbers) > 1 else ''} {', '.join([str(x) for x in todo_numbers])} successfully" + (". Failed to remove the following numbers because they are invalid: " + ", ".join([str(x) for x in failed]) if len(failed) > 0 else ""), allowed_mentions=discord.AllowedMentions.none())
+
+ async def marked_as_autocomplete(
+ self,
+ _: discord.Interaction,
+ current: str
+ ) -> List[discord.app_commands.Choice[str]]:
+ return [
+ discord.app_commands.Choice(name=x, value=x)
+ for x in ["done", "in progress", "high priority", "low priority"]
+ if x.startswith(current) or current in x
+ ]
+
+ @check()
+ @todo.command(extras={"category":Category.TODO}, usage="mark ")
+ @discord.app_commands.describe(
+ todo_number="The todo task you want to mark",
+ marked_as="What you want to make the todo task as"
+ )
+ @discord.app_commands.autocomplete(marked_as=marked_as_autocomplete)
+ async def mark(self, ctx: commands.Context, todo_number: int, *, marked_as: str):
+ """Mark a todo with a comment like `done` or `too lazy` (Only in editor mode)"""
+ todo_list = await self._edit_check(ctx)
+ if not todo_list: return
+
+ todos = todo_list.todos
+
+ if not todo_list.has_todo(todo_number):
+ return await ctx.send(f"You don't have a number {todo_number} on your current todo list", allowed_mentions=discord.AllowedMentions.none())
+
+ if marked_as.lower() == "done" and todo_list.delete_done is True:
+ todos.pop(todo_number-1)
+ todo_list.set_property("todos", todos)
+ return await ctx.send(f"Marked to-do number {todo_number} as done and deleted it per default")
+ elif marked_as.lower() == "-r" or marked_as.lower() == "-rm":
+ todos[todo_number-1]["marked"] = None
+ mark_log = {
+ "author": ctx.author.id,
+ "change": "REMOVED MARK",
+ "date": datetime.now()
+ }
+ todos[todo_number-1]["mark_log"].append(mark_log)
+ todo_list.set_property("todos", todos)
+ return await ctx.send(f"Removed to-do number {todo_number} successfully!", allowed_mentions=discord.AllowedMentions.none())
+ else:
+ todos[todo_number-1]["marked"] = marked_as
+ mark_log = {
+ "author": ctx.author.id,
+ "change": marked_as,
+ "date": datetime.now()
+ }
+ todos[todo_number-1]["mark_log"].append(mark_log)
+ todo_list.set_property("todos", todos)
+ return await ctx.send(f"Marked to-do number {todo_number} as `{marked_as}`!", allowed_mentions=discord.AllowedMentions.none())
+
+ async def due_in_autocomplete(
+ self,
+ _: discord.Interaction,
+ current: str
+ ) -> List[discord.app_commands.Choice[TimeConverter]]:
+ """
+ Autocomplete for the due in parameter
+ """
+ times = ["1m", "5m", "10m", "30m", "1h", "12h", "1d", "7d"]
+ return list([
+ discord.app_commands.Choice(name=opt, value=opt)
+ for opt in times if opt.lower().startswith(current.lower())
+ ])
+
+ @check()
+ @todo.command(extras={"category":Category.TODO}, usage="add ")
+ @discord.app_commands.describe(text="What to add to the todo list")
+ @discord.app_commands.autocomplete(due_in=due_in_autocomplete)
+ async def add(self, ctx: commands.Context, *, text: str, due_in: Optional[TimeConverter] = None):
+ """Add a todo to your list, *yay, more work* (Only in editor mode)"""
+ todo_list = await self._edit_check(ctx)
+ if not todo_list: return
+
+ if len(text) > 100:
+ return await ctx.send("Your todo can't have more than 100 characters", ephemeral=True)
+
+ if len(todo_list.todos) >= todo_list.spots:
+ return await ctx.send(f"You don't have enough spots for that! Buy spots with `/todo buy space`. You can currently only have up to {todo_list.spots} spots in this list", allowed_mentions=discord.AllowedMentions.none(), ephemeral=True)
+
+ if due_in and not todo_list.has_addon("due_in"):
+ return await ctx.send("You cannot assign a time to a todo yet, you need to buy it in the shop", ephemeral=True)
+
+ todos = todo_list.todos
+ todos.append({"todo": text, "marked": None, "added_by": ctx.author.id, "added_on": datetime.now(),"views": 0, "assigned_to": [], "mark_log": [], "due_at": (datetime.now() + due_in) if due_in else None, "notified": False if due_in else None})
+
+ todo_list.set_property("todos", todos)
+ return await ctx.send(f"Great! Added \"{text}\" to your todo list!" + (f" I'll remind you and everyone assigned " if due_in else ""), allowed_mentions=discord.AllowedMentions.none(), ephemeral=hasattr(ctx, "invoked_by_context_menu"))
+
+ @check(20)
+ @todo.command(extras={"category":Category.TODO}, usage="kick ")
+ @discord.app_commands.describe(user="The user to kick from the todo list")
+ async def kick(self, ctx: commands.Context, user: discord.User):
+ """Take all permissions from someone from your todo list (Only in editor mode)"""
+ todo_list = await self._edit_check(ctx)
+ if not todo_list: return
+
+ if not ctx.author.id == todo_list.owner:
+ return await ctx.send("You have to own the todo list to remove permissions from users")
+
+ if not (user.id in todo_list.viewer or user.id in todo_list.editor):
+ return await ctx.send("The user you specified doesn't have permission to view or edit the todo list, you can't take permissions you never granted")
+
+ if user.id in todo_list.editor:
+ todo_list.kick_editor(user.id)
+ await ctx.send(f"You have successfully taken the editor permission from {user}", allowed_mentions=discord.AllowedMentions.none())
+
+ if user.id in todo_list.viewer:
+ todo_list.kick_viewer(user.id)
+ await ctx.send(f"You have successfully taken the viewer permission from {user}", allowed_mentions=discord.AllowedMentions.none())
+
+ @check()
+ @todo.command(extras={"category":Category.TODO}, usage="exit")
+ async def exit(self, ctx: commands.Context):
+ """Exit editing mode with this. (Only in editor mode)"""
+ # I"ve never used it because it is pointless because my code is so good you realistically never need to be out of editing mode but it is here so use it
+ todo_list = await self._edit_check(ctx)
+ if not todo_list: return
+
+ editing.pop(ctx.author.id, None)
+ return await ctx.send("Exiting editing mode!")
+
+ @check(20)
+ @todo.command(extras={"category":Category.TODO}, usage="invite ")
+ @discord.app_commands.describe(
+ user="The user to give permissions to",
+ role="The role to give the user"
+ )
+ async def invite(self, ctx: commands.Context, user: discord.User, role: TodoPermissions):
+ """Wanna let your friend add more todos for you? Invite them! (Only in editor mode)"""
+ todo_list = await self._edit_check(ctx)
+ if not todo_list: return
+
+ if user.id == ctx.author.id:
+ return await ctx.send("You are already owner, you don't need to invite yourself")
+
+ if blcheck(user.id):
+ return await ctx.send("You can't invite a blacklisted user")
+
+ if role.name == "viewer" and todo_list.status == "public":
+ return await ctx.send("You can't add viewers to a public todo list. Everyone has viewing permissions on this list", ephemeral=True)
+
+ if user.id in getattr(todo_list, role.name):
+ return await ctx.send("The specified user already has that role!")
+
+ if role.name == "viewer" and user.id in todo_list.editor:
+ return await ctx.send("User already has editor permissions, you can't also add viewer permission", ephemeral=True)
+
+ embed = discord.Embed.from_dict({
+ "title": f"You were invited to to-do list {todo_list.name} (ID: {todo_list.id})",
+ "description": f"{ctx.author} invited you to be {role.name} in their to-do list. To accept, click \"confirm\", to deny click \"cancel\". If this invitation was inappropriate, click \"report\"",
+ "color": todo_list.color or 0x1400ff,
+ "footer": {"icon_url": str(ctx.author.avatar.url), "text": f"Requested by {ctx.author}"}
+ })
+
+ try:
+ view = ConfirmButton(user.id, timeout=80)
+ view.add_item(Button(label="Report", custom_id="report", style=discord.ButtonStyle.red))
+ msg = await user.send(embed=embed, view=view)
+ await ctx.send("Successfully send the invitation to the specified user! They have 24 hours to accept or deny")
+ except discord.Forbidden:
+ return await ctx.send("Failed to send the user a dm. Make sure they are on a guild Killua is on and has their dms open")
+
+ await view.wait()
+ await view.disable(msg)
+
+ if not view.value:
+ if view.timed_out:
+ await user.send("Timed out!")
+ return await ctx.author.send(f"{user} has not responded to your invitation in 24 hours so the invitation went invalid")
+ else:
+ await user.send("Successfully denied invitation")
+ return await ctx.author.send(f"{user} has denied your invitation the todo list `{todo_list.name}`", allowed_mentions=discord.AllowedMentions.none())
+
+ elif view.value == "report":
+ channel = self.client.get_channel(REPORT_CHANNEL)
+ embed = discord.Embed.from_dict({
+ "title": f"Report from {user}",
+ "fields": [
+ {"name": "Guild", "value": f"ID: {ctx.guild.id}\nName: {ctx.guild.name}"},
+ {"name": "Reported user", "value": f"ID: {ctx.author.id}\nName: {ctx.author.name}"},
+ {"name": "Todo list", "value": f"ID: {todo_list.id}\nName: {todo_list.name}"}
+ ],
+ "color": 0xff0000,
+ "footer": {"text": user.id, "icon_url": str(user.avatar.url)},
+ "thumbnail": {"url": str(ctx.author.avatar.url)}
+ })
+ await channel.send(embed=embed)
+ await ctx.author.send(f"{user} reported your invite to your todo list")
+ return await user.send(f"Successfully reported {ctx.author.name}!")
+
+ if role.name == "viewer":
+ todo_list.add_viewer(user.id)
+
+ if role.name == "editor":
+ if user.id in todo_list.viewer:
+ todo_list.kick_viewer(user.id) # handled like a promotion and exchanges viewer perms for edit perms
+ todo_list.add_editor(user.id)
+
+ await user.send(f"Success! You have now {role.name} permissions in the todo list `{todo_list.name}`", allowed_mentions=discord.AllowedMentions.none())
+ return await ctx.author.send(f"{user} accepted your invitation to your todo list `{todo_list.name}`!", allowed_mentions=discord.AllowedMentions.none())
+
+
+ @check()
+ @todo.command(extras={"category":Category.TODO}, usage="assign ")
+ @discord.app_commands.describe(
+ todo_number="What todo to assign someone to",
+ user="Who to assign the todo to"
+ )
+ async def assign(self, ctx: commands.Context, todo_number: int, user: discord.User):
+ """Assign someone a todo task with this. If already asigned they are removed. (Only in editor mode)"""
+ todo_list = await self._edit_check(ctx)
+ if not todo_list: return
+
+ if not user.id == todo_list.owner and not user.id in todo_list.editor:
+ return await ctx.send("You can only assign people todos who have permission to edit this todo list")
+
+ todos = todo_list.todos
+
+ if not todo_list.has_todo(todo_number):
+ return await ctx.send(f"You don't have a number {todo_number} on your current todo list")
+
+ if user.id in todos[todo_number-1]["assigned_to"]:
+ if not ctx.author == user:
+ embed = discord.Embed.from_dict({
+ "title": f"Removed assignment to todo on list {todo_list.name} (ID: {todo_list.id})",
+ "description": f"{ctx.author} removed assignment you to the todo {todos[todo_number-1]['todo']}",
+ "color": todo_list.color or 0x1400ff,
+ "footer": {"icon_url": str(ctx.author.avatar.url), "text": f"Requested by {ctx.author}"}
+ })
+ try:
+ await user.send(embed=embed)
+ except discord.Forbidden:
+ pass
+ todos[todo_number-1]["assigned_to"].remove(user.id)
+ todo_list.set_property("todos", todos)
+ return await ctx.send(f"Successfully removed assignment of todo task {todo_number} of {user}")
+
+ todos[todo_number-1]["assigned_to"].append(user.id)
+ todo_list.set_property("todos", todos)
+
+ if not ctx.author == user:
+ embed = discord.Embed.from_dict({
+ "title": f"Assigned to todo on list {todo_list.name} (ID: {todo_list.id})",
+ "description": f"{ctx.author} assigned you to the todo {todos[todo_number-1]['todo']}",
+ "color": todo_list.color or 0x1400ff,
+ "footer": {"icon_url": str(ctx.author.avatar.url), "text": f"Requested by {ctx.author}"}
+ })
+ try:
+ await user.send(embed=embed)
+ except discord.Forbidden:
+ pass
+ return await ctx.send(f"Successfully assigned the task with number {todo_number} to `{user}`", allowed_mentions=discord.AllowedMentions.none())
+
+ @check()
+ @todo.command(extras={"category":Category.TODO}, usage="reorder ")
+ @discord.app_commands.describe(
+ position="The position the todo is currently at",
+ new_position="Where to put the todo"
+ )
+ async def reorder(self, ctx: commands.Context, position: int, new_position: int):
+ """Reorder a todo task with this. (Only in editor mode)"""
+ todo_list = await self._edit_check(ctx)
+ if not todo_list: return
+
+ if not ctx.author.id == todo_list.owner and not ctx.author.id in todo_list.editor:
+ return await ctx.send("You can only reorder tasks who have permission to edit this todo list")
+
+ if not todo_list.has_todo(position):
+ return await ctx.send(f"You don't have a number {position} on your current todo list")
+
+ if new_position > len(todo_list.todos) or new_position < 1:
+ return await ctx.send(f"You can't reorder todo task {position} to position {new_position} because it's out of range")
+
+ todo_list.todos.insert(new_position-1, todo_list.todos.pop(position-1))
+ todo_list.set_property("todos", todo_list.todos)
+ return await ctx.send(f"Successfully reordered todo task {position} to position {new_position}")
+
+ @check()
+ @todo.command(extras={"category":Category.TODO}, usage="delete ")
+ @discord.app_commands.describe(todo_id="The todo list to delete")
+ async def delete(self, ctx: commands.Context, todo_id: str):
+ """Use this command to delete your todo list. Make sure to say goodbye a last time"""
+ todo_list = await self._edit_check(ctx)
+ if not todo_list: return
+
+ if not ctx.author.id == todo_list.owner:
+ return await ctx.send("Only the owner of a todo list can delete it")
+
+ todo_list.delete()
+ return await ctx.send(f"Done! Deleted todo list {todo_list.name}", allowed_mentions=discord.AllowedMentions.none())
+
+ @check()
+ @todo.command(extras={"category":Category.TODO}, usage="lists")
+ async def lists(self, ctx: commands.Context):
+ """This shows a list of todo lists you own or have access to"""
+ lists_owning = DB.todo.find({"owner": ctx.author.id})
+ lists_viewing = DB.todo.find({"viewer": ctx.author.id})
+ lists_editing = DB.todo.find({"editor": ctx.author.id})
+
+ l_o = "\n".join([f"{l['name']} (id: {l['_id']}/{l['custom_id'] or 'No custom id'})" for l in lists_owning])
+ l_v = "\n".join([f"{l['name']} (id: {l['_id']}/{l['custom_id'] or 'No custom id'})" for l in lists_viewing])
+ l_e = "\n".join([f"{l['name']} (id: {l['_id']}/{l['custom_id'] or 'No custom id'})" for l in lists_editing])
+
+ embed = discord.Embed.from_dict({
+ "title": f"Your todo lists and permissions",
+ "description": f"**todo lists you own**\n\n{l_o or 'No todo lists'}\n\n**todo lists you have viewing permissions**\n\n{l_v or 'No todo lists'}\n\n**todo lists you have editing permissions**\n\n{l_e or 'No todo lists'}",
+ "color": 0x1400ff,
+ "footer": {"icon_url": str(ctx.author.avatar.url), "text": f"Requested by {ctx.author}"}
+ })
+ return await ctx.send(embed=embed)
+
+Cog = TodoSystem
\ No newline at end of file
diff --git a/tests/killua/cogs/web_scraping.py b/tests/killua/cogs/web_scraping.py
new file mode 100644
index 000000000..3e208eb5c
--- /dev/null
+++ b/tests/killua/cogs/web_scraping.py
@@ -0,0 +1,199 @@
+import re
+import discord
+from discord.ext import commands
+from bs4 import BeautifulSoup
+from html import escape
+from json import loads
+from typing import Union
+from pypxl import PxlClient
+from urllib.parse import unquote
+
+from killua.bot import BaseBot
+from killua.utils.checks import check
+from killua.utils.paginator import Paginator
+from killua.static.enums import Category
+from killua.static.constants import PXLAPI
+
+from typing import Any, Callable
+
+class WebScraping(commands.Cog):
+
+ def __init__(self, client: BaseBot):
+ self.client = client
+ self.pxl = PxlClient(token=PXLAPI, stop_on_error=False, session=self.client.session)
+ self.headers = {
+ "dnt": "1",
+ "accept-encoding": "gzip, deflate, sdch",
+ "x-requested-with": "XMLHttpRequest",
+ "accept-language": "en-GB,en-US;q=0.8,en;q=0.6,ms;q=0.4",
+ "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
+ "accept": "application/json, text/javascript, */*; q=0.01",
+ "referer": "https://duckduckgo.com/",
+ "authority": "duckduckgo.com",
+ }
+ self._init_menus()
+
+ def _init_menus(self) -> None:
+ menus = []
+ menus.append(discord.app_commands.ContextMenu(
+ name='google',
+ callback=self.client.callback_from_command(self.google, message=True)
+ ))
+
+ for menu in menus:
+ self.client.tree.add_command(menu)
+
+ def _try_else(self, x: Any, f: Callable[[Any], str], e: str = None) -> str:
+ """Returns a book info it it exists, else "-" or e if provided"""
+ try:
+ return " ".join(f(x).split())
+ except Exception:
+ return e or "-"
+
+ def _has_results(self, page: BeautifulSoup) -> bool:
+ """Checks if there are any results before activating the paginator"""
+ try:
+ page.find_all("div", class_="u-anchorTarget")[0].attrs["id"]
+ #If there are no results this will raise an error, in that case Killua will say so
+ except Exception:
+ return False
+ return True
+
+ def getBookCount(self, page) -> int:
+ """Gets the number of results for a book"""
+ #This function gets the number of total book results by taking in the books name
+ # get the web page (id only for this website)
+ return len(page.find_all("div", class_="u-anchorTarget"))
+
+
+ async def getBook(self, nr: int, name: str, pages: BeautifulSoup) -> discord.Embed:
+ """Get result x of a book with title y"""
+ #This is the essential function getting infos about a book by taking the name and the number of the result list
+ # get the id of the book (id only for this website)
+ bookNr = pages.find_all("div", class_="u-anchorTarget")[nr].attrs["id"]
+ # get the book
+ res = await self.client.session.get("https://www.goodreads.com/book/show/" + bookNr)
+ content = await res.text()
+ book = BeautifulSoup(content.encode(), "html.parser")
+ # get the book values
+
+ rating = self._try_else(book, lambda book: book.find("span", itemprop="ratingValue").text)
+ name = self._try_else(book, lambda book: book.find("div", class_="bookCoverPrimary").find("img").attrs["alt"])
+ language = self._try_else(book, lambda book: book.find("div", itemprop="inLanguage").text)
+ pages = self._try_else(book, lambda book: book.find("span", itemprop="numberOfPages").text)
+ author = self._try_else(book, lambda book: book.find("a", class_="authorName").find_all("span")[0].text)
+ img_url = self._try_else(book, lambda book: book.find("div", class_="bookCoverPrimary").find("img").attrs["src"], "https://upload.wikimedia.org/wikipedia/commons/f/fc/No_picture_available.png")
+ isbn = self._try_else(book, lambda book: book.find_all("div", class_="infoBoxRowItem")[1].text)
+ description = self._try_else(book, lambda book: book.find("div", id="description").find(style="display:none").text)
+
+ # Special cases
+ if not isbn.isdigit():
+ isbn = "-"
+
+ if description.startswith("Alternate cover for this ISBN can be found here"):
+ description = description.replace("Alternate cover for this ISBN can be found here", "")
+
+ if len(description) > 1000:
+ description = description[:1000]+ "..."
+ #Making sure embed limit isn"t exceeded
+
+ if len(name) > 256:
+ name = name[:253] + "..."
+ #Making sure title limit isn"t exceeded
+
+ return discord.Embed.from_dict({
+ "title": name,
+ "thumbnail":{
+ "url": img_url},
+ "description": f"\n**Rating:** {rating}/5\n**Author:** {author}\n**Language:** {language}\n**Number of pages:** {pages}\n**Book description:**\n{description}\n**ISBN:**{isbn}",
+ "color": 0x1400ff
+ }) #returning the fresh crafted embed with all the information
+
+ @commands.hybrid_group()
+ async def web(self, _: commands.Context):
+ """Web search commands"""
+ pass
+
+ @check(12)
+ @web.command(aliases=["n", "search-book", "sb"], extras={"category":Category.FUN}, usage="book ")
+ @discord.app_commands.describe(book="The name of the book to loock for")
+ async def book(self, ctx: commands.Context, *, book: str):
+ """With this command you can search for books! Just say the book title and look through the results"""
+ response = await self.client.session.get(f"https://www.goodreads.com/search?q={book}")
+ content: str = await response.text()
+ p = BeautifulSoup(content.encode(), "html.parser")
+ if not self._has_results(p):
+ return await ctx.send("No results found")
+ await ctx.channel.typing()
+ await ctx.send("Processing...", ephemeral=True)
+ async def make_embed(page, _, pages):
+ return await self.getBook(page-1, book, pages)
+
+ await Paginator(ctx, p, max_pages=self.getBookCount(p), func=make_embed, defer=True).start()
+
+ async def _get_token(self, query: str) -> Union[str, None]:
+ """Gets a new token to be used in the image search"""
+ try:
+ res = await self.client.session.get(f"https://duckduckgo.com/?q={escape(query)}")
+
+ if not res.status == 200:
+ return
+
+ token = re.search(r"vqd='(.*?)'", str(BeautifulSoup(await res.text(), "html.parser"))).group(1)
+ return token
+ except Exception:
+ return
+
+ @check(4)
+ @web.command(aliases=["image", "i"], extras={"category":Category.FUN}, usage="img ")
+ @discord.app_commands.describe(query="What image to look for")
+ async def img(self, ctx: commands.Context, *, query: str):
+ """Search for any image you want"""
+
+ token = await self._get_token(query)
+
+ if not token:
+ return await ctx.send("Something went wrong... If this keeps happening please contact the developer")
+
+ base = "https://duckduckgo.com/i.js?l=wt-wt&o=json&q={}&vqd={}&f=,,,&p=1"
+ url = base.format(escape(query), token)
+
+ response = await self.client.session.get(url, headers=self.headers)
+
+ results = loads(await response.text())["results"]
+
+ if not results:
+ return await ctx.send("There were no images found matching your query")
+
+ # A hacky way to get the list of results because the response is not in the correct format
+ # as duckduckgo is not returning a json decodable response but a string
+
+ links = [r["image"] for r in results if r["image"]]
+
+ def make_embed(page, embed, pages):
+ embed.title = "Results for query " + query
+ embed.set_image(url=pages[page-1])
+ return embed
+
+ return await Paginator(ctx, links, func=make_embed).start()
+
+ @check(2)
+ @web.command(aliases=["g","search"], extras={"category":Category.FUN}, usage="google ")
+ @discord.app_commands.describe(text="The query to search for")
+ async def google(self, ctx: commands.Context, *, text: str):
+ """Get the best results for a query the web has to offer"""
+
+ r = await self.pxl.web_search(query=text)
+ if r.success:
+ results = r.data["results"]
+ embed = discord.Embed.from_dict({
+ "title": f"Results for query {text}",
+ "color": 0x1400ff,
+ })
+ for i in range(4 if len(results) >= 4 else len(results)):
+ res = results[i-1]
+ embed.add_field(name="** **", value=f"**[__{res['title']}__]({res['url']})**\n{unquote(res['description'][:100])}..." if len(res["description"]) > 100 else unquote(res["description"]), inline=False)
+ return await self.client.send_message(ctx, embed=embed, ephemeral=hasattr(ctx, "invoked_by_context_menu"))
+ return await ctx.send(":x: "+r.error, epheremal=True)
+
+Cog = WebScraping
diff --git a/tests/killua/download.py b/tests/killua/download.py
new file mode 100644
index 000000000..b564f41c3
--- /dev/null
+++ b/tests/killua/download.py
@@ -0,0 +1,18 @@
+"""
+This file includes one "download" function which downloads all cards to a local file to be able to run
+tests with them offline later
+"""
+import json
+import aiohttp
+from .static.constants import CARDS_URL
+
+async def download():
+ async with aiohttp.ClientSession() as session:
+ async with session.get(CARDS_URL) as resp:
+ data = await resp.text()
+ data = json.loads(data)
+ with open("cards.json", "w") as f:
+ f.write(json.dumps(data))
+ f.close()
+ await session.close()
+
\ No newline at end of file
diff --git a/tests/killua/migrate.py b/tests/killua/migrate.py
new file mode 100644
index 000000000..0264e6b45
--- /dev/null
+++ b/tests/killua/migrate.py
@@ -0,0 +1,101 @@
+"""
+This file contains one function, `migrate`, which is used to migrate the database from one version to another once when
+an update is released. It can be run through the command line with `python3 -m killua --migrate`
+"""
+import logging
+from typing import Type
+from datetime import datetime
+from json import loads
+from pymongo.collection import Collection
+from discord.ext.commands import AutoShardedBot, HybridGroup
+from killua.static.constants import DB, CLUSTER
+
+def migrate_requiring_bot(bot: Type[AutoShardedBot]):
+ """
+ Migrates the database from one version to another, requiring a bot instance. Automatically called when the bot starts if `--migrate` was run before.
+ """
+ logging.info("Migrating database...")
+ const: Collection = DB._DB["const"]
+
+ if bot.is_dev:
+ const.insert_one({"_id": "usage", "command_usage": {}})
+ const.update_one({"_id": "migrate"}, {"$set": {"value": False}}) # Only migrate once
+ return
+
+ # Migrate the current command usage statistics the const collecting, adjusting its values
+ coll: Collection = CLUSTER["general"]["stats"]
+ usage = coll.find_one({"_id": "commands"})["command_usage"]
+
+ new = {}
+
+ # First handle case of already corrupt data
+ usage["8ball"] += usage["ball"]
+ del usage["ball"]
+
+ # Handle edge case
+ usage["dev info"] = usage["info"]
+ del usage["info"]
+
+ usage["economy leaderboard"] = usage["leaderboard"]
+ del usage["leaderboard"]
+
+ usage["economy guild"] = usage["guild"]
+ del usage["guild"]
+
+ usage["shush"] = usage["mute"]
+ usage["unshush"] = usage["unmute"]
+
+ for command in bot.walk_commands():
+
+ if "jishaku" in command.qualified_name:
+ continue
+ for key, val in usage.items():
+ if key == command.qualified_name and not isinstance(command, HybridGroup):
+ new[command.qualified_name] = val
+ elif key == command.name and not isinstance(command, HybridGroup):
+ new[command.qualified_name] = val
+
+ const.insert_one({"_id": "usage", "command_usage": new})
+ logging.info("Sucessfully migrated command usage")
+ const.update_one({"_id": "migrate"}, {"$set": {"value": False}}) # Only migrate once
+ logging.info("Finished migrating database")
+
+def migrate():
+ """
+ Migrates the database from one version to another
+ """
+ logging.info("Migrating database...")
+ # Migrate single item collection into a new "const" collection
+ const: Collection = DB._DB["const"]
+
+ # shop
+ const.insert_one({"_id": "shop", "offers": [], "log": []})
+ logging.info("Migrated shop")
+ # custom presence
+ const.insert_one({"_id": "presence", "text": None, "activity": None, "presence": None})
+ logging.info("Migrated presence")
+ # updates
+ const.insert_one({"_id": "updates", "updates": []})
+ logging.info("Migrated updates")
+ # stats (growth)
+ with open("data.json", "r") as file: # Getting historic growth data
+ data = list(loads(file.read()))
+
+ new_list = [{"date": datetime.fromtimestamp(int(item["timestamp"])), "guilds": item["guild"]} for item in data]
+ new_list.sort(key=lambda x: x["date"])
+ const.insert_one({"_id": "growth", "growth": new_list})
+ logging.info("Migrated growth")
+ # blacklist
+ const.insert_one({"_id": "blacklist", "blacklist": []})
+ logging.info("Migrated blacklist")
+
+ # Transfer all todo lists to another namespace
+ todo: Collection = DB._DB["todo"]
+ old_todo: Collection = CLUSTER["general"]["todo"]
+ for todo_list in old_todo.find():
+ todo.insert_one(todo_list)
+ logging.info("Migrated all todo lists")
+
+ # Ensure `migrate_requiring_bot` is called when the bot starts
+ const.insert_one({"_id": "migrate", "value": True})
+ logging.info("Completed database migration")
\ No newline at end of file
diff --git a/tests/killua/static/cards.py b/tests/killua/static/cards.py
new file mode 100644
index 000000000..67d178979
--- /dev/null
+++ b/tests/killua/static/cards.py
@@ -0,0 +1,647 @@
+import math
+import random
+import discord
+from discord.ext import commands
+from datetime import datetime
+from typing import List, Union
+
+from .constants import INDESTRUCTABLE, ALLOWED_AMOUNT_MULTIPLE, DEF_SPELLS, VIEW_DEF_SPELLS, FREE_SLOTS, DB
+from killua.utils.classes import User, SuccessfullDefense, CheckFailure, CardNotFound, Book
+from killua.utils.paginator import Paginator
+from killua.utils.interactions import Select, View, Button, ConfirmButton
+
+background_cache = {}
+
+class Card:
+ """This class makes it easier to access card information"""
+ cache = {}
+ cached_raw = []
+
+ @classmethod
+ def __get_cache(cls, card_id: int):
+ """Returns a cached object"""
+ return cls.cache[card_id] if card_id in cls.cache else None
+
+ def __new__(cls, name_or_id: Union[int, str], *args, **kwargs):
+ card_id = cls._find_card(name_or_id)
+ existing = cls.__get_cache(card_id)
+ if existing:
+ return existing
+ return super().__new__(cls)
+
+ @classmethod
+ def _find_card(self, name_or_id: Union[int, str]) -> Union[int, None]:
+
+ # This could be solved much easier but this allows the user to
+ # have case insensitivity when looking for a card
+ if not self.cached_raw:
+ self.cached_raw = [(c["name"], c["_id"]) for c in DB.items.find({})]
+ for c in self.cached_raw:
+
+ if not isinstance(name_or_id, int) and not name_or_id.isdigit():
+ if c[0].lower() == name_or_id.lower():
+ return c[1]
+ elif isinstance(name_or_id, int):
+ if c[1] == name_or_id:
+ return c[1]
+ else:
+ if c[1] == int(name_or_id):
+ return c[1]
+
+ def __init__(self, name_or_id: str):
+ card_id = self._find_card(name_or_id)
+
+ if card_id in self.cache:
+ return
+
+ if card_id is None:
+ raise CardNotFound
+
+ card = DB.items.find_one({"_id": card_id})
+
+ self.id: int = card["_id"]
+ self.name: str = card["name"]
+ self.image_url: str = card["Image"]
+ self.owners: list = card["owners"]
+ self.description: str = card["description"]
+ self.emoji: str = card["emoji"]
+ self.rank: str = card["rank"]
+ self.limit: int = card["limit"]
+ self.available: bool = card["available"] if "available" in card else True
+ try:
+ self.type:str = card["type"]
+ except KeyError:
+ DB.items.update_one({"_id": self.id}, {"$set":{"type": "normal"}})
+ self.type = "normal"
+
+ if self.id > 1000 and not self.id == 1217: # If the card is a spell card it has two additional properties
+ self.range: str = card["range"]
+ self.cls: list = card["class"]
+
+ self.cache[self.id] = self
+
+ def add_owner(self, user_id: int):
+ """Adds an owner to a card entry in my db. Only used in Card().add_card()"""
+ self.owners.append(user_id)
+ DB.items.update_one({"_id": self.id}, {"$set": {"owners": self.owners}})
+ return
+
+ def remove_owner(self, user_id:int):
+ """Removes an owner from a card entry in my db. Only used in Card().remove_card()"""
+ self.owners.remove(user_id)
+ DB.items.update_one({"_id": self.id}, {"$set": {"owners": self.owners}})
+ return
+
+ async def _wait_for_defense(self, ctx:commands.Context, other:User, effects:list) -> None:
+
+ if len(effects) == 0:
+ return
+
+ effects = [Card(c) for c in effects]
+ view = View(other.id, timeout=20)
+ view.add_item(Select(options=[discord.SelectOption(label=c.name, emoji=c.emoji, value=str(c.id)) for c in effects]))
+ view.add_item(Button(label="Ignore", style=discord.ButtonStyle.red, custom_id="ignore"))
+
+ msg = await ctx.send(f"<@{other.id}> {ctx.author} has used the spell `{self.id}` on you! You have {len(effects)} spells to defend yourself. You can either choose one of them to defend yourself with or let the attack go through", view=view)
+ await view.wait()
+ await view.disable(msg)
+
+ if not view.value:
+ if view.timed_out:
+ await ctx.send(f"No response from the attacked user, the attack goes through!", reference=msg)
+ else:
+ await ctx.send("You decided not to use a defense spell, the attack goes through!", reference=msg)
+ return
+
+ if isinstance(view.value, int):
+ other.remove_card(view.value)
+ raise SuccessfullDefense(f"<@{other.id}> successfully defended against your attack")
+ else:
+ await ctx.send("You decided not to use a defense spell, the attack goes through!", reference=msg)
+
+ async def _view_defense_check(self, ctx: commands.Context, other:User) -> None:
+ effects = []
+ for c in other.fs_cards:
+ if c[0] in VIEW_DEF_SPELLS and not c[0] in effects:
+ effects.append(c[0])
+
+ await self._wait_for_defense(ctx, other, effects)
+
+ async def _attack_defense_check(self, ctx: commands.Context, other: User, target_card:int) -> None:
+ if target_card in [x[0] for x in other.rs_cards]: # A list of cards that steal from restricted slots
+ if f"page_protection_{int((target_card-10)/18+2)}" in other.effects and not target_card in [x[0] for x in other.fs_cards]:
+ raise SuccessfullDefense("The user has protected the page this card is in against spells!")
+
+ if other.has_effect("1026")[0]:
+ if 1026 in [x[0] for x in other.all_cards]: # Card has to remain in posession
+ if other.effects["1026"]-1 == 0:
+ other.remove_effect("1026")
+ other.remove_card(1026)
+ else:
+ other.add_effect("1026", other.effects["1026"]-1)
+ raise SuccessfullDefense("The user had remaining protection from card 1026 thus your attack failed")
+
+ effects = []
+ for c in other.fs_cards:
+ if c[0] in DEF_SPELLS and not c[0] in effects:
+ if c[0] == 1019 and not self.range == "SR":
+ continue
+ if c[0] == 1004 and self.ctx.author.id not in other.met_user:
+ continue
+ effects.append(c[0])
+
+ await self._wait_for_defense(ctx, other, effects)
+
+ def _permission_check(self, ctx:commands.Context, member:discord.Member) -> None:
+ perms = ctx.channel.permissions_for(member)
+ if not perms.send_messages or not perms.read_messages:
+ raise CheckFailure(f"You can only attack a user in a channel they have read and write permissions to which isn't the case with {self.Member.display_name}")
+
+ def _has_cards_check(self, cards: List[list], card_type: str = "", is_self: bool = False, uses_up: bool = False) -> None:
+ if len(cards) == 0:
+ raise CheckFailure((f"You do not have cards{card_type}!" if is_self else f"This user does not have any cards{card_type}!") + f" This information uses up card {self.name}." if uses_up else "")
+
+ def _has_any_card(self, card_id:int, user:User) -> None:
+ if not user.has_any_card(card_id):
+ raise CheckFailure("The specified user doesn't have this card")
+
+ def _has_met_check(self, prefix: str, author: User, other: discord.Member) -> None:
+ if not author.has_met(other.id):
+ raise CheckFailure(f"You haven't met this user yet! Use `{prefix}meet <@someone>` if they send a message in a channel to be able to use this card on them")
+
+ def _has_other_card_check(self, cards: List[list]) -> None:
+ if len(cards) < 2:
+ raise CheckFailure(f"You don't have any cards other than card {self.name}!")
+
+ def _is_maxed_check(self, card: int) -> None:
+ c = Card(card)
+ if len(c.owners) >= c.limit * ALLOWED_AMOUNT_MULTIPLE:
+ raise CheckFailure(f"The maximum amount of existing cards with id {card} is reached!")
+
+ def _is_full_check(self, user: User) -> None:
+ if len(user.fs_cards) >= FREE_SLOTS:
+ raise CheckFailure("You don't have any space in your free slots left!")
+
+ def _is_valid_card_check(self, card_id: int) -> None:
+ try:
+ Card(card_id)
+ except CardNotFound:
+ raise CheckFailure("Specified card is invalid!")
+
+ def _has_effect_check(self, user: User, effect: str) -> None:
+ if user.has_effect(effect)[0]:
+ raise CheckFailure("You already have this effect in place!")
+
+ def _get_analysis_embed(self, card_id:int) -> discord.Embed:
+ card = Card(card_id)
+ fields = [
+ {"name": "Name", "value": card.name + " " + card.emoji, "inline": True},
+ {"name": "Type", "value": card.type.replace("normal", "item"), "inline": True},
+ {"name": "Rank", "value": card.rank, "inline": True},
+ {"name": "Limit", "value": str(card.limit*ALLOWED_AMOUNT_MULTIPLE), "inline": True},
+ {"name": "Available", "value": "Yes" if card.available else "No", "inline": True},
+ ]
+ if card.type == "spell":
+ fields.append({"name": "Class", "value": ", ".join(card.cls), "inline": True})
+ fields.append({"name": "Range", "value": card.range, "inline": True})
+
+ embed = discord.Embed.from_dict({
+ "title": f"Info about card {card_id}",
+ "thumbnail": {"url": card.image_url},
+ "color": 0x1400ff,
+ "description": card.description,
+ "fields": fields
+ })
+ return embed
+
+ def _get_list_embed(self, card_id: int) -> discord.Embed:
+ card = Card(card_id)
+
+ real_owners = []
+ for o in card.owners:
+ # Get the total number of owners
+ if not o in real_owners:
+ real_owners.append(o)
+ embed = discord.Embed.from_dict({
+ "title": f"Infos about card {card.name}",
+ "description": f"**Total copies in circulation**: {len(card.owners)}\n\n**Total owners**: {len(real_owners)}",
+ "image": {"url": card.image_url},
+ "color": 0x1400ff
+ })
+ return embed
+
+class Card1001(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs) -> None:
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, member: discord.Member) -> None:
+ author = User(self.ctx.author.id)
+ other = User(member.id)
+
+ self._has_met_check(self.ctx.bot.command_prefix(self.ctx.bot, self.ctx.message)[2], author, member)
+
+ self._permission_check(self.ctx, member)
+ author.remove_card(self.id)
+ await self._view_defense_check(self.ctx, other)
+
+ self._has_cards_check(other.fs_cards, " in their free slots", uses_up=True)
+
+ async def make_embed(page, *_):
+ return await Book(self.ctx.bot.session).create(member, page, True)
+
+ await Paginator(self.ctx, max_pages=math.ceil(len(other.fs_cards)/18), func=make_embed, has_file=True).start()
+
+class Card1002(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs) -> None:
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, member: discord.Member) -> None:
+ author = User(self.ctx.author.id)
+ other = User(member.id)
+
+ self._has_met_check(self.ctx.bot.command_prefix(self.ctx.bot, self.ctx.message)[2], author, member)
+
+ self._permission_check(self.ctx, member)
+ author.remove_card(self.id)
+ await self._view_defense_check(self.ctx, other)
+
+ async def make_embed(page, embed, pages):
+ return await Book(self.ctx.bot.session).create(member, page)
+
+ await Paginator(self.ctx, max_pages=6, func=make_embed, has_file=True).start()
+
+class Card1007(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs) -> None:
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, member:discord.Member):
+ self._permission_check(self.ctx, member)
+
+ author = User(self.ctx.author.id)
+ other = User(member.id)
+
+ self._has_cards_check(other.rs_cards, " in their restricted slots")
+
+ target_card = random.choice([x[0] for x in other.rs_cards if x[0] != 0])
+ author.remove_card(self.id)
+ await self._attack_defense_check(self.ctx, other, target_card)
+
+ removed_card = other.remove_card(target_card, restricted_slot=True)
+ author.add_card(target_card, removed_card[1]["fake"])
+ await self.ctx.send(f"Successfully stole card number `{target_card}` from `{member}`!")
+
+class Card1008(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, member:discord.Member) -> None:
+ self._permission_check(self.ctx, member)
+
+ author = User(self.ctx.author.id)
+ other = User(member.id)
+
+ self._has_cards_check(other.all_cards)
+ self._has_other_card_check(author.all_cards)
+
+ target_card = random.choice([x[0] for x in other.all_cards if x[0] != 1008 and x[0] != 0])
+ await self._attack_defense_check(self.ctx, other, target_card)
+
+ author.remove_card(self.id)
+ removed_card_other = other.remove_card(target_card)
+ removed_card_author = author.remove_card(random.choice([x[0] for x in author.all_cards if x[0] != 0]))
+ other.add_card(removed_card_author[0], removed_card_author[1]["fake"])
+ author.add_card(removed_card_other[0], removed_card_other[1]["fake"])
+
+ await self.ctx.send(f"Successfully swapped cards! Gave {member} the card `{removed_card_author[0]}` and took card number `{removed_card_other[0]}` from them!")
+
+class Card1010(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, card_id:int) -> None:
+ user = User(self.ctx.author.id)
+
+ if not user.has_any_card(card_id, False):
+ raise CheckFailure("Seems like you don't own this card You already need to own a (non-fake) copy of the card you want to duplicate")
+
+ self._is_maxed_check(card_id)
+ user.remove_card(self.id)
+ user.add_card(card_id, clone=True)
+
+ await self.ctx.send(f"Successfully added another copy of {card_id} to your book!")
+
+class Card1011(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, member:discord.Member) -> None:
+ author = User(self.ctx.author.id)
+ other = User(member.id)
+ author.remove_card(self.id)
+
+ self._has_cards_check(other.rs_cards, f" in their restricted slots!", uses_up=True)
+ card = random.choice([x for x in other.rs_cards if x[0] != 0])
+ self._is_maxed_check(card[0])
+
+ author.add_card(card[0], card[1]["fake"], True)
+ await self.ctx.send(f"Successfully added another copy of card No. {card[0]} to your book! This card is {'not' if card[1]['fake'] is False else ''} a fake!")
+
+class Card1015(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, member:discord.Member) -> None:
+ author = User(self.ctx.author.id)
+ other = User(member.id)
+
+ self._has_met_check(self.ctx.bot.command_prefix(self.ctx.bot, self.ctx.message)[2], author, member)
+
+ author.remove_card(self.id)
+
+ self._has_cards_check(other.all_cards)
+
+ async def make_embed(page, embed, pages):
+ return await Book(self.ctx.bot.session).create(member, page)
+
+ return await Paginator(self.ctx, max_pages=6+math.ceil(len(other.fs_cards)/18), func=make_embed, has_file=True).start()
+
+class Card1018(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self) -> None:
+ author = User(self.ctx.author.id)
+ author.remove_card(self.id)
+
+ users = []
+ stolen_cards = []
+
+ async for message in self.ctx.channel.history(limit=20):
+ if message.author not in users and message.author.bot is False and message.author != self.ctx.author:
+ users.append(message.author)
+
+ for user in users:
+ try:
+ self._permission_check(self.ctx, user)
+ u = User(user.id)
+ self._has_cards_check(u.all_cards)
+ target = random.choice([x for x in u.all_cards if x[0] != 0])
+ await self._attack_defense_check(self.ctx, u, target)
+ r = u.remove_card(target[0], target[1]["fake"])
+ stolen_cards.append(r)
+ except Exception as e:
+ continue
+
+ if len(stolen_cards) > 0:
+ author.add_multi(stolen_cards)
+ await self.ctx.send(f"Success! Stole the card{'s' if len(stolen_cards) > 1 else ''} {', '.join([str(x[0]) for x in stolen_cards])} from {len(stolen_cards)} user{'s' if len(users) > 1 else ''}!")
+ else:
+ await self.ctx.send("All targetted users were able to defend themselves!")
+
+class Card1020(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, card_id:int) -> None:
+ self._is_valid_card_check(card_id)
+
+ if card_id > 99 or card_id < 1:
+ raise CheckFailure(f"You can only use '{self.name}' on a card with id between 1 and 99!")
+
+ author = User(self.ctx.author.id)
+
+ author.remove_card(self.id)
+ author.add_card(card_id, True)
+ await self.ctx.send(f"Created a fake of card No. {card_id}! Make sure to remember that it's a fake, fakes don't count towards completion of the album")
+
+class Card1021(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, member:discord.Member, card_id:int) -> None:
+ self._permission_check(self.ctx, member)
+
+ if card_id == 0:
+ raise CheckFailure("You cannot steal card 0")
+
+ author = User(self.ctx.author.id)
+ other = User(member.id)
+
+ self._has_any_card(card_id, other)
+ author.remove_card(self.id)
+ await self._attack_defense_check(self.ctx, other, card_id)
+
+ stolen = other.remove_card(card_id)
+ author.add_card(stolen[0], stolen[1]["fake"])
+ await self.ctx.send(f"Stole card number {card_id} successfully!")
+
+class Card1024(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, member:discord.Member) -> None:
+ other = User(member.id)
+ author = User(self.ctx.author.id)
+
+ tbr = [x for x in other.all_cards if x[1]["fake"] or x[1]["clone"]]
+
+ if len(tbr) == 0:
+ raise CheckFailure("This user does not have any cards you could target with this spell!")
+
+ author.remove_card(self.id)
+
+ rs_tbr = [x for x in other.rs_cards if x[1]["fake"] is True or x[1]["clone"] is True]
+ fs_tbr = [x for x in other.fs_cards if x[1]["fake"] is True or x[1]["clone"] is True]
+
+ for c in rs_tbr:
+ other.rs_cards.remove(c)
+ for c in fs_tbr:
+ other.fs_cards.remove(c)
+
+ other._update_val("cards", {"rs": other.rs_cards, "fs": other.fs_cards, "effects": other.effects})
+ await self.ctx.send(f"Successfully removed all cloned and fake cards from `{member}`. Cards removed in total: {len(tbr)}")
+
+class Card1026(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self) -> None:
+ author = User(self.ctx.author.id)
+ try:
+ self._has_effect_check(author, str(self.id))
+ except CheckFailure:
+ if not author.count_card(self.id) > 1:
+ raise CheckFailure("You don't have another copy of this card to renew the effect")
+ view = ConfirmButton(user_id=self.ctx.author.id)
+ msg = await self.ctx.send(f"You still have {author.has_effect(str(self.id))[1]} protections left. Do you really want to use this card now and overwrite the current protection?", view=view)
+ await view.wait()
+ await view.disable(msg)
+
+ if view.timed_out:
+ raise CheckFailure("Timed out!")
+ elif view.value is False:
+ raise CheckFailure("Successfully canceled!")
+
+ if author.has_effect(str(self.id)):
+ author.remove_effect(str(self.id))
+
+ # if (amount:=author.count_card(self.id)) > 1:
+ # for i in range(amount):
+ # author.remove_card(self.id)
+
+ author.add_effect(str(self.id), 10)
+
+ await self.ctx.send("Done, you will be automatically protected from the next 10 attacks! You need to keep the card in your inventory until all 10 defenses are used up")
+
+class Card1028(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, member:discord.Member) -> None:
+ self._permission_check(self.ctx, member)
+
+ other = User(member.id)
+ author = User(self.ctx.author.id)
+
+ self._has_cards_check(other.fs_cards, " in their free slots")
+
+ target_card = random.choice([x for x in other.fs_cards if not x[0] in INDESTRUCTABLE])
+ author.remove_card(self.id)
+ await self._attack_defense_check(self.ctx, other, target_card)
+ other.remove_card(target_card[0], remove_fake=target_card[1]["fake"], restricted_slot=False, clone=target_card[1]["clone"])
+ await self.ctx.send(f"Success, you destroyed card No. {target_card[0]}!")
+
+class Card1029(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, member:discord.Member) -> None:
+ self._permission_check(self.ctx, member)
+
+ other = User(member.id)
+ author = User(self.ctx.author.id)
+
+ self._has_cards_check(other.rs_cards, " in their restricted slots")
+
+ target_card = random.choice([x for x in other.rs_cards if not x[0] in INDESTRUCTABLE and x[0] != 0])
+ author.remove_card(self.id)
+ await self._attack_defense_check(self.ctx, other, target_card)
+ other.remove_card(target_card[0], remove_fake=target_card[1]["fake"], restricted_slot=True, clone=target_card[1]["clone"])
+ await self.ctx.send(f"Success, you destroyed card No. {target_card[0]}!")
+
+class Card1031(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, card_id:int) -> None:
+ self._is_valid_card_check(card_id)
+
+ author = User(self.ctx.author.id)
+ author.remove_card(self.id)
+ embed = self._get_analysis_embed(card_id)
+ await self.ctx.send(embed=embed)
+
+class Card1032(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self) -> None:
+ author = User(self.ctx.author.id)
+ self._is_full_check(author)
+
+ target = random.choice([x["_id"] for x in DB.items.find({"type": "normal", "available": True}) if x["rank"] != "SS" and x["_id"] != 0]) # random card for lottery
+ author.remove_card(self.id)
+ self._is_maxed_check(target)
+ author.add_card(target)
+
+ await self.ctx.send(f"Successfully added card No. {target} to your inventory")
+
+class Card1035(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, page:int) -> None:
+ author = User(self.ctx.author.id)
+
+ if page > 6 or page < 1:
+ raise CheckFailure("You need to choose a page between 1 and 6")
+ self._has_effect_check(author, f"page_protection_{page}")
+ author.remove_card(self.id)
+ author.add_effect(f"page_protection_{page}", datetime.now()) # The valuedoesn't matter here
+ await self.ctx.send(f"Success! Page {page} is now permanently protected")
+
+class Card1036(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, effect:str, card_id:int) -> None:
+ author = User(self.ctx.author.id)
+
+ if not str(self.id) in author.effects and not author.has_fs_card(self.id):
+ raise CheckFailure(f"You need to have used the card {self.id} once to use this command")
+
+ if author.has_fs_card(self.id) and not str(self.id) in author.effects:
+ author.remove_card(self.id)
+ author.add_effect(str(self.id), datetime.now())
+
+ if not effect.lower() in ["list", "analysis", "1031", "1038"]:
+ raise CheckFailure(f"Invalid effect to use! You can use either `analysis` or `list` with this card. Usage: `{self.client.command_prefix(self.client, self.ctx.message)[2]}use {self.id} `")
+
+ if effect.lower() in ["list", "1038"]:
+ embed = self._get_list_embed(card_id)
+ if effect.lower() in ["analysis", "1031"]:
+ embed = self._get_analysis_embed(card_id)
+ await self.ctx.send(embed=embed)
+
+class Card1038(Card):
+
+ def __init__(self, ctx: commands.Context, **kwargs):
+ self.ctx = ctx
+ super().__init__(**kwargs)
+
+ async def exec(self, card_id:int) -> None:
+ self._is_valid_card_check(card_id)
+
+ if card_id == 0:
+ raise CheckFailure("Redacted card!")
+
+ User(self.ctx.author.id).remove_card(self.id)
+
+ embed = self._get_list_embed(card_id)
+ await self.ctx.send(embed=embed)
\ No newline at end of file
diff --git a/tests/killua/static/constants.py b/tests/killua/static/constants.py
new file mode 100644
index 000000000..dfff48879
--- /dev/null
+++ b/tests/killua/static/constants.py
@@ -0,0 +1,711 @@
+import json
+import io
+import discord
+from pymongo import MongoClient, collection
+from typing import Union
+
+from os.path import exists
+from killua.utils.test_db import TestingDatabase as Database
+import killua.args as args
+
+args.init()
+
+with open("config.json", "r") as config_file:
+ config = json.loads(config_file.read())
+
+CLUSTER = MongoClient(config["mongodb"])
+
+CONST_DEFAULT = [ # The default values for the const collection
+ {"_id": "migrate", "value": True},
+ {"_id": "usage", "command_usage": {}},
+ {"_id": "shop", "offers": [], "log": []},
+ {"_id": "presence", "text": None, "activity": None, "presence": None},
+ {"_id": "updates", "updates": []},
+ {"_id": "blacklist", "blacklist": []},
+]
+
+MAX_VOTES_DISPLAYED = 5
+
+CARDS_URL = "https://json.extendsclass.com/bin/7d2c78bde0cd"
+
+class DB:
+ _DB = None
+ const = None
+ _cards = None
+
+ def __init__(self):
+ if not args.Args.test:
+ self._DB = CLUSTER["Killua"]
+
+ @property
+ def teams(self) -> Union[collection.Collection, Database]:
+ return self._DB["teams"] if args.Args.test is None else Database("teams")
+
+ @property
+ def items(self) -> Union[collection.Collection, Database]:
+ if args.Args.test is not None:
+ if self._cards:
+ return self._cards
+ elif exists("cards.json"):
+ with open("cards.json", "r") as file:
+ res = json.loads(file.read())
+ db = Database("items")
+ db.db["items"] = res["data"]
+ self._cards = db
+ file.close()
+ return db
+ else:
+ raise FileNotFoundError("cards.json does not exist. Run `python3 -m killua -dl` to download the cards first.")
+ else:
+ return self._DB["items"]
+
+ @property
+ def guilds(self) -> Union[collection.Collection, Database]:
+ return self._DB["guilds"] if args.Args.test is None else Database("guilds")
+
+ @property
+ def todo(self) -> Union[collection.Collection, Database]:
+ return self._DB["todo"] if args.Args.test is None else Database("todo")
+
+ @property
+ def const(self) -> Union[collection.Collection, Database]:
+ if args.Args.test is not None:
+ db = Database("const")
+ db.insert_many(CONST_DEFAULT)
+
+ return db
+ else:
+ return self._DB["const"]
+
+DB = DB()
+
+IPC_TOKEN: str = config["ipc"]
+TOKEN = config["token"]
+PATREON = config["patreon"]
+PXLAPI = config["pxlapi"]
+PASSWORD = config["password"]
+PORT = config["port"]
+TOPGG_TOKEN = config["topgg_token"]
+DBL_TOKEN = config["dbl_token"]
+
+# Big boi from https://gist.github.com/gruber/8891611
+URL_REGEX = r"(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'\".,<>?ÂĢÂģââââ])|(?:(?
+ halved cooldowns
+ up to 1 premium guild
+ custom id for todo lists
+ exclusive role in support server
+ doubled daily jenny
+ weekly lootbox
+ exclusive badge
+
+Tier 2 <:tier_two_badge:879390669368614982>
+ invite dev bot and use not yet public features
+ up to two premium guilds
+
+Tier 3 <:tier_three_badge:879390807315087451>
+ up to 3 premium guilds
+ doubled jenny whenever gaining jenny
+
+Tier 4 <:tier_four_badge:879391090665467905>
+ up to 10 premium guilds
+
+
+Premium guild <:premium_guild_badge:883473807292121149>
+ exclusive server badge
+ halved cooldown for entire server (stacks with premium sub)
+ access to premium server restricted commands
+ doubled daily jenny for entire server (stacks with premium sub)
+ unlimted poll votes
+"""
+
+INFO = "This bot is themed after the character Killua from the anime [hunter x hunter](https://en.wikipedia.org/wiki/Hunter_Ã_Hunter)." + \
+"""
+I chose this character because it was sort of a role model I had during a tough time and I wanted to give back by creating a bot that would best represent the character.
+At that point I had never programmed in python before, but I had a goal and I taught myself (through some pingspams in the support servers) how to code step by step to achieve that goal.
+
+Killua has become a way I continue to teach myself programming and by now it has taught me a lot. The bot was never build to profit.
+And so even though I myself invested quite a lot of money into the bot, Killua will barely have any paywalls at all. If you do like the project, there is a patreon, however if you don't want to spend money, Killua will still have many things to offer for you.
+
+If you're reading this that means you're using Killua, so I want to thank you for that. Being the only developer on this pretty massive codebase is not easy, but knowing people enjoy bot makes it worth it :)
+"""
+
+# Tips that can be added to any send message send with bot.send_message
+TIPS = ["Do you own a big server? Chances are **you** qualify to become a partner, meaning your server will become a permanent premium server. For more infos & applying, join the support server.", "Got feedback? **We want to hear it!** Join the support server to let us know what you think about the bot.", "Killua is designed to have as little as possible paywalled, but if you enjoy the bot please enjoy becoming a Patreon.", "Join the support server to be the first to see new features!", "If you manage to beat Killua 25 times at rock paper scissors he will give you a present :)", "Need something to organise your tasks? Try **todo lists**. For more info, use `/help`", "If you have no one to play rps against, you can just play against me!", "Did you know you gain doubled jenny **every time** you collect jenny somehow with premium tier 3?", "With premium you can choose an *entire server* whose cooldowns will be halved", "Want to get started collecting cards and need a guide? Use `/cards use booklet`!", "Want to get lootboxes for free? You get a free lootbox every 5th time you vote for Killua!", "Get info on lootbox chances and lore by using `boxinfo`", "To invite Killua to your own server, use `invite`", "Did you know that you can search for books using `novel `", "You can translate 20+ languages using the `translate` command!", "Not sure how to use a command? Use `/help ` to get more infos!", "Take a screenshot of any website using the `screenshot` command.", "Did you forget if a card you own is a fake? No problem, check it with `/cards check`"]
+
+# TOPICS
+TOPICS = ["What's your least favorite genre of music?", "What's the most beautiful place youve ever been to?", "What's the best name for a pet dragon?", "What's the best name for a pet turtle?", "What's the best name for a pet snake?", "What do you enjoy doing most in your free time?", "Do you think technology will advance or ruin humanity?", "What's your favorite animal?", "What is your favorite TV show?", "If you could go anywhere in the world, where would you go?", "What did you used to do, stopped and wish you hadn't?", "What was the best day in your life?", "For what person are you the most thankful for?", "What is and has always been your least favorite subject?", "What always makes you laugh and/or smile when you think about it?", "Do you think there are aliens?", "What is your earliest memory?", "What's your favorite drink?", "Where do you like going most for vacation?", "What motivates you?", "What is the best thing about school/work?", "What's better, having high expectations or having low expectations?", "What was the last movie you saw?", "Have you read anything good recently?", "What is your favorite day of the year?", "What kind of music do you like to listen to?", "What things are you passionate about?", "What is your favorite childhood memory?", "If you could acquire any skill, what would you choose?", "What is the first thing that you think of in the morning?", "What was the biggest life change you have gone through?", "What is your favorite song of all time?", "If you won $1 million playing the lottery, what would you do?", "How would you know if you were in love?", "If you could choose to have any useless super power, what would you pick?",
+"What sport do you wish you were really good at?", "What's the strangest dream you've had recently?", "What's the best thing you've ever bought off Amazon?", "What is something people are always surprised to learn about you?", "What song do you wish you could put on right now?", "What do you think has been the best movie of the year so far?", "What do you think is the best show on Netflix right now?", "Do you think at some points there will be robot revolution? (I do Ã˛_Ãŗ)", "Who was your first crush on?", "What was something that changed your life?", "What did someone you know do that was so embarrassing that you acted like you didn't know them?", "What was a moment that completely changed your option about something or someone?", "What thing happened to you that you wouldn't believe it if someone told you it had happened to them?", "What's your favorite ice cream flavor?", "If you had to choose another username what would it be?", "Who is your role model?", "What's the best food you have ever eaten?", "What accomplishment are you most proud of?", "Would you rather be the most popular kid in school or the smartest kid in school?", "Do you prefer to cook or order take out?", "What is your dream job?", "What's your ideal way to celebrate your birthday?", "What is a short/long term goal of yours?", "What are your three must have smart phone apps?", "Would you rather be the smartest moron or dumbest genius?", "What was the last gift that you received?", "If you could give one piece of advice to the whole world, what would it be?", "Describe your perfect day.", "How would you define success?", "What is the first thing that you notice when meeting someone new?",
+"Who is the most important person in your life right now?", "What's the nicest thing anyone has ever done for you?", "What's the biggest risk you've ever taken?", "What are the top three things on your bucket list?", "What did you want to be when you were a kid?", "What did you want to be when you were a kid?", "How did you spend your last birthday?", "What's the best holiday?", "Do you prefer to take baths or showers?", "Do you like to sing out loud when no one else is around?", "What is the worst piece of advice you've ever gotten?", "When was the last time you laughed so hard you cried?", "Is a hot dog a sandwich?", "What's your go-to joke?", "Which celebrity would play you in a movie about your life?", "Tell me about the worst pickup line you've ever gotten.", "How would you describe your best friend?", "What qualities do you admire about your parents?", "What's the one thing that people always misunderstand about you?", "When have you felt your biggest adrenaline rush?", "What's something you hope will never change?", "What's your best memory so far this year?", "If your life had a theme song, what would it be?", "Do you believe we would be better off if we didn't have social media?", "What is one quality about yourself that you are most proud of?", "What's something that always makes you smile?", "Where would you go if you had to pack your stuff and relocate to another country tomorrow?", "Which website do you visit the most?", "What's the weirdest fact you've ever heard?", "What's the last lie you told?", "What bridges are you glad that you burned?", "What's the meanest thing you've ever said to someone else?", "Who are you most jealous of?",
+"What's one movie you're embarrassed to admit you enjoy?", "What's the cheapest gift you've ever gotten for someone else?", "What's your most embarrassing late night purchase?", "What is your greatest fear in a relationship?", "Have you ever regifted a present?", "Name one thing you'd change about every person in this chat.", "What's one useless skill you'd love to learn anyway?", "How many people have you kissed?", "What's something you would die if your mom found out about?", " Who was your first love?", "Who in this chat would you want to swap lives with for a week?", "Who's the most surprising person to ever slide into your DMs?", "What is something you've failed at recently?", "What word do you hate the most?", "If you could hire someone to do one thing for you, what would it be?", "What's the best lie you've ever told anyone?", "What do you think happens when you die?", "Who's the last person who called you?", "What's one thing about your partner that you find least attractive?", "When was the last time you were really angry? Why?", "Would you ever get plastic surgery?", "Who was the last person you said, âI love youâ to?", "What's the most bogus rumor you've ever heard about yourself?", "Do you think cheating can ever be justified? How?", "What's your best pickup line?", "What's the dumbest thing you've ever lied about?", "What's the biggest secret you've kept from your parents?", "What's something that takes up way too much of your time?", "What's your favorite thing to do when bored?", "If you had to pick three words to describe yourself, what would they be?", "What do you seek for in a romantic partner?", "What's the most useless invention you've ever heard of?",
+"What was the best thing about how your parents raised you?", "If you could have a fictional superhero for a best friend, who would it be?", "What does your name mean?", "Tell me about your childhood best friend.", "What is the thing you wish you would have known 10 years ago?", "What Netflix show or movie are you marathon-watching?", " What projects are you working on right now that bring you joy?", "What is one thing you should never say at a wedding?", "What do you think are the best traits for a person to have?", "What is something you wish you could do everyday?", "If someone gave you an envelope with your death date inside of it, would you open it?", "What scares you most about your future?", "What three things do you want to be remembered for?", "How would your best friend describe you?", "What is a significant event that has changed you?", "What are three fun facts about yourself?", "Who do you count on the most for help?", "What did you think was the most challenging part of being a kid?", "Have you ever really kept a New Year's resolution?", "How long can you go without checking your phone?", "Which of your family members or friends are you most like?", "How long do you think you'd survive in a zombie apocalypse?", "What's a special habit of yours?", "What's your least favorite color?"]
+ANSWERS = ["What would jesus do?", "My sources say no but my heart says yes", "\U000026a0 8ball.exe has stopped responding", "If you try hard enough, maybe", "Stop asking me >-<", "Only if you're wearing socks", "That's what the milk carton said", "Probably, if it's raining.", "Yep", "You are kidding, right?", "I think you know that better than me", "I am sorry to break it to you but... no", "I don't think so", "Yes, no more info needed", "No! Why would you ask that?", "Lets do it!", "Did you ask your mom?", "I seriously don't think that is a good idea", "Could you repeat that?", "Well... maybe", "Anything is possible", "If you really need an answer, google it", "Better to think about it yourself", "Yes....wait, no", "No...actually, yes"]
+
+# A list of whould you rather options
+WYR = [("Be able to see 10 minutes into the future", "Be able to see 150 years into the future"), ("Never be able to use your phone again", "Never be able to use the internet again"), ("Team up with wonder woman", "Team up with Captain Marvel"), ("Lose your sight", "Lose your memories"), ("Have a personal maid", "Have a personal chef"), ("Be royalty 1000 years ago", "Be an average person today"), ("Cuddle a coala", "Pal around with a Panda"), ("Sip gin with Ryan Renolds", "Take tequila shots with The Rock"), ("Have a child every year for 5 years", "Never have any children at all"), ("Hunt and butcher your own meat", "Never have meat again"), ("Walk in on your parents", "Have your parents walk in on you"), ("Have unlimited Battery life on all your devices", "Have unlimited wifi wherever you go"), ("Be in history books for something terrible", "Be completely forgotten after you die"), ("Be in a zombie apocalypse", "Be in a robot apocalypse"), ("Have a photographic memory", "Have an IQ of 200"), ("Forget your partners birthday every year", "Forget your anniversary every year"), ("Get to decide the outcome of the next election", "Change the outcome of the last election"), ("Have super sensitive taste buds", "Have super sensitive hearing"), ("Detect every lie you hear", "Get away with any lie you tell"), ("Be able to fly", "Be able to breathe underwater"), ("Be able to read minds", "Be able to control minds"), ("Be able to teleport", "Be able to time travel"), ("Be able to speak every language", "Be able to speak to animals"), ("Be able to see in the dark", "Be able to see through walls"), ("Be the funniest person in the room", "Be the smartest person in the room"),
+("Work for Michael Scott", "Work for Mr Burns"), ("Give up cursing forever", "Give up ice cream for 12 years"), ("Have a stranger see all the photos on your phone", "Have a stranger read all texts on your phone"), ("Have fortune", "Have fame"), ("Vistit the ISS for a week", "Spend a week in a hotel at the bottom of the ocean"), ("Be stranded in the jungle", "Be stranded in the desert"), ("Go back to kindergarden with everything you know", "Know everything your future self will learn now"), ("Be an unknown superhero", "Be an infamous villan"), ("Wear real fur", "Wear fake jewels"), ("Be able to erase your memeories", "Be able to erase someone elses memories"), ("Get drunk with one sip of alcohol", "Never get drunk"), ("Sell all of your possesions", "Sell one of your organs"), ("Unable to close any open door", "Unable to open any closed door"), ("Star in a Star Wars film", "Star in a Marvel film"), ("Always wear wet socks", "Always have a rock in your shoes"), ("Never age physically", "Never age mentally"), ("Know when you're going to die", "Know how you're going to die"), ("Be beloved by the public but hated by friends and family", "Be hated by the public but loved by friends and family"), ("Give up the internet for a month", "Give up showering for a month"), ("Be unable to move your body when it rains", "Be unable to stop moving when the sun is out"), ("Be the head of a company", "Be the head of a cult"), ("Be a famous actor", "Be a famous director"), ("Be unable to use search engines", "Unable to use social media"), ("Be a brilliant mathematician", "Be an amazing painter"), ("Never be able to wear pants", "Never be able to wear shorts"),
+("Sleep with 10 blankets", "Sleep with no blanket"), ("Eat the same thing for your entire life", "Drink the same thing for your entire life"), ("Work indoors", "Work outdoors"), ("Never hear again", "Never speak again"), ("Never use a phone again", "Never use a computer again"), ("Have unlimited bacon but no games", "Have games. Unlimited games. But no games"), ("Spend one year in jail", "Lose one year off your life"), ("All traffic lights you approach turn green for you", "Never have to stand in line again"), ("Be the first person to explore a planet", "Be the inventor of a drug that cures a deadly desease"), ("Always travel first class free", "Never have to pay for food again"), ("Be able to dodge bullets no matter how fast they're moving", "Ask 3 questions about anything and get an accurate answer"), ("Be an unimportant character in the last movie you sad", "Be an unimportant character in the last book you read"), ("Be completely insane and know it", "Be completely insane and think you're sane"), ("Have everything you think about in a bubble above you", "Life stream what you do 24/7 for anyone to see"), ("Be born again in the same country", "Be born again in a random country"), ("Have a successful Twitch channel", "Have a successfull YouTube channel"), ("Never be able to drink water again", "Only be able to drink water"), ("Control fire", "Control water"), ("Never be able to use a touchscreen again", "Never be able to use keyboard and mouse again"), ("Be able to type insanely fast", "Be able to read insanely fast"), ("Take amazing selfies, but all of your other pictures are horrible", "Take breathtaking photographs of anything but yourself"),
+("Lose all of your friends except your best friend", "Lose your best friend"), ("Never have to clean a bathroom again", "Never have to clean the dishes again"), ("Live in a nice house and boring town", "Live in a rough house but exciting town"), ("Have a top tier gaming pc", "Have the newest and best apple computer"), ("Read a hardback book", "Read a paperback book"), ("Owe someone a lot of money", "Owe someone a big favour"), ("Have your house completely carpeted", "Have your house completely tiled"), ("Clean rest stop toilets for living", "Work in a slaughterhouse for living"), ("Live without hot water for showers/baths", "Live without a washing machine"), ("Accindentally be responsible for the death of a child", "Accindentally be responsible for the death of three adults"), ("Have evrything you eat be too salty", "Have everything you eat be too sweet"), ("Be an amazing artist but never see the art you create", "Be an amazing musician but never hear the music you create"), ("Wake up in the middle of an unknown desert", "Wake up on a rowboat in the middle of an unknown body of water"), ("Constantly tired no matter how much you sleep", "Constantly hungry no matter how much you eat"), ("Lose the 3 possessions you hold most dear", "Lose everything but those 3 posessions"), ("Get a suitecase with $10k", "Get a suitcase which has the 50/50 chance of $50k or $1k"), ("Be completely offline for the next year", "Lose a finger or toe of your choice"), ("Have a non-venomous spider infestation in your house", "Have a mouse investation in your house"), ("Swallow 5 live worms", "Swallow one live cockroach"), ("Be held in high regard by your parents", "Be held in high regard by your friends"),
+("Know the uncomfortable truth", "Believe a comfortable lie"), ("Donate your body to science", "Donate your organs to people who need them"), ("Have real political power but be relatively poor", "Be ridiculously rich but have no political power (not even bought)"), ("Have a criminal justice system that works and is fair", "Have an administrative branch that is free of corruption"), ("Live iin utopia as a normal person", "Live in distopia but you're the surpreme ruler"), ("Know all the mysteries of the universe", "Know the outcome of every choice you could make"), ("Fight for a cause you believe in, but doubt will succeed", "Fight for a cause that you only partially believe in but have a high chance of your cause succeeding"), ("Eat at the same resturant you usually do", "Eat at a new resturant that just opened"), ("Live in a house that is incredibly unique and beautiful but plain on the inside", "Live in a house that is incredibly unique and beautiful on the inside but plain on the outside")
+]
+
+# ACTION IMAGES
+HUG_IMGS = ["https://pbs.twimg.com/media/E-R3q0HWYAQGC-8?format=jpg&name=900x900", "https://pbs.twimg.com/media/D2CMyE5WoAAYyNZ?format=jpg&name=small", "https://pbs.twimg.com/media/EZJPkcsXQAEIyPY?format=jpg&name=large", "https://pbs.twimg.com/media/BV23LRDCEAACjqL?format=jpg&name=small", f"https://i.pinimg.com/originals/66/9b/67/669b67ae57452f7afbbe5252b6230f85.gif", f"https://i.pinimg.com/originals/70/83/0d/70830dfba718d62e7af95e74955867ac.jpg", "https://cdn.discordapp.com/attachments/756945125568938045/756945463432839168/image0.gif", "https://cdn.discordapp.com/attachments/756945125568938045/756945308381872168/image0.gif", "https://cdn.discordapp.com/attachments/756945125568938045/756945151191941251/image0.gif", "https://pbs.twimg.com/media/Dl4PPE4UUAAsb7c.jpg", "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSJgTjRyQW3NzmDzlvskIS7GMjlFpyS7yt_SQ&usqp=CAU", "https://static.zerochan.net/Hunter.x.Hunter.full.1426317.jpg", "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQJjVWplBdqrasz8Fh-7nDkxRjnnNBqk0bZlQ&usqp=CAU", "https://i.pinimg.com/originals/75/2e/0a/752e0a5f813400dfebe322fc8b0ad0ae.jpg", "https://thumbs.gfycat.com/IllfatedComfortableAplomadofalcon-small.gif", "https://steamuserimages-a.akamaihd.net/ugc/492403625757327002/9B089509DDCB6D9F8E11446C7F1BC29B9BA57384/", f"https://cdn.discordapp.com/attachments/756945125568938045/758235270524698634/image0.gif", f"https://cdn.discordapp.com/attachments/756945125568938045/758236571974762547/image0.jpg", "https://cdn.discordapp.com/attachments/756945125568938045/758236721216749638/image0.jpg", "https://cdn.discordapp.com/attachments/756945125568938045/758237082484473856/image0.jpg",
+"https://cdn.discordapp.com/attachments/756945125568938045/758237352756903936/image0.png", "https://cdn.discordapp.com/attachments/756945125568938045/758237832954249216/image0.jpg", "https://i.pinimg.com/originals/22/66/3e/22663e7f60734f141c72ca659a3a90cc.jpg", "https://i.pinimg.com/originals/c5/38/d5/c538d54e493b118683c48ccbd0020311.jpg", "https://wallpapercave.com/wp/wp6522234.jpg", "https://i.pinimg.com/originals/48/db/98/48db98dac9d67143c4244991cb84b4f1.jpg", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQjXQW8tVJfFmPz8qokH3u7maX6haz_6Uyx2w&usqp=CAU", "https://i.pinimg.com/originals/f3/17/1b/f3171b2bb05b6c6ad90e6c094737d7e9.png", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQrukypBFocf_oqpSSJmEpzx5sLjnpUJqMD4Q&usqp=CAU", "https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/edb16fd5-2978-4a97-8568-7472c3205405/dbfi6uq-32adf5b9-e2d0-4892-8026-97012b9ae0d1.png/v1/fit/w_300,h_900,q_70,strp/happy_bday_killua_by_queijac_dbfi6uq-300w.jpg?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOiIsImlzcyI6InVybjphcHA6Iiwib2JqIjpbW3siaGVpZ2h0IjoiPD05MjkiLCJwYXRoIjoiXC9mXC9lZGIxNmZkNS0yOTc4LTRhOTctODU2OC03NDcyYzMyMDU0MDVcL2RiZmk2dXEtMzJhZGY1YjktZTJkMC00ODkyLTgwMjYtOTcwMTJiOWFlMGQxLnBuZyIsIndpZHRoIjoiPD05MDAifV1dLCJhdWQiOlsidXJuOnNlcnZpY2U6aW1hZ2Uub3BlcmF0aW9ucyJdfQ.ETgcZiDvdTQpDPQTQiMwW8ELS3xVXH_4nFYzEFpXJ8Y", "https://i.pinimg.com/originals/b5/c1/f3/b5c1f308052e51b79c9a38e5164fe89e.jpg",
+"https://dzt1km7tv28ex.cloudfront.net/u/466410804707590144_35s_d.jpg", "https://i.pinimg.com/originals/d5/bf/f3/d5bff3a697448536651892e90ecea059.png", "https://d.furaffinity.net/art/akitamonster/1416385290/1416385290.akitamonster_killuagonhugbehind.png", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTSrjPgwlZ86TckXAV8LudKe6Depz3l37rMcg&usqp=CAU", "https://i.pinimg.com/originals/a0/83/63/a083635d9813b7d3e2ce45cb12ccdc13.png", "https://i.quotev.com/img/q/u/20/9/2/rcu7je27oy.jpg", "https://pm1.narvii.com/6467/02892de9a2e459094adc2eab7b1f4ec1495a7a21_hq.jpg", "https://i.pinimg.com/originals/c8/ee/c8/c8eec84afc58789fe1656f339fb10d8e.jpg", ]
+PAT_IMGS = [f"https://i.pinimg.com/originals/be/75/ff/be75ff9f2ba20efb4dbda09c62802b39.gif", f"https://pbs.twimg.com/media/DmWlGrqX0AAKlT3.jpg"] # this is not used
+
+
+# ACTION TEXT
+HUG_TEXTS = [" makes blush by hugging them", " gives a hug. Their face lights up brighter than a star", " makes 's day by giving them a hug", " hugs so strong they can barely breathe", " hugs from behind like a hug-assassine :ninja:", " looked like they needed one of these", f" hugs as strong as they can", f" hugs and makes sure to not let go", f" gives the longest hug they have ever seen", f" cuddles ", f" uses as a teddybear", f" hugs until all their worries are gone and 5 minutes longer",f" clones themself and together they hug ", f" jumps in 's arms", f" gives a bearhug", f" finds a lamp with a Jinn and gets a wish. So they wish to hug ", f" asks for motivation and gets a hug"," looks at the floor, then up, then at the floor again and finally hugs with passion", " looks deep into 's eyes and then gives them a hug", " could do their homework but instead they decide to hug ", " wanted to go get food but wouldn't let go"]
+PAT_TEXTS = [" reaches over to pat lovingly", " is too far about to hug, so pats them", " wants to show appreciation, so they pat ", " pats like a cat", "'s head seems very pattable", " was too tired to hug so they gave a pat instead", " took 5 lp damage down so gives them a healing head pat", " tries to catch a spider, slips and instead pats . is also fine with that", " pats ", " thinks is a cat and starts to pat them", " looks at 's fluffy hair and starts to pat them", " didn't get pet so they pat instead"]
+SLAP_TEXTS = [" hits hard enough to send them flying", "Uh oh! gets slapped by because they said something did not like", " noticed staring off into the distance. So they obviously slap them", " did some unspeakable things... so slapped them!", " slaps ", " stares at for a long time and then slaps them", " has no mercy; they slap ", " is unsure how to react so they slap "]
+POKE_TEXTS = [" is needed here", " needs something from ", " launches a poke attack at ", " pokes