From ae56590bb9b4403fd9f32d2989c6db6b8570fbb4 Mon Sep 17 00:00:00 2001 From: Zevaryx Date: Sat, 26 Jun 2021 02:28:23 -0600 Subject: [PATCH] Added joke cog --- config.example.yaml | 5 +++ jarvis/__init__.py | 5 ++- jarvis/cogs/jokes.py | 81 ++++++++++++++++++++++++++++++++++++++++ jarvis/config.py | 8 +--- jarvis/utils/__init__.py | 9 ++++- jarvis/utils/db.py | 7 ++++ 6 files changed, 106 insertions(+), 9 deletions(-) create mode 100644 jarvis/cogs/jokes.py create mode 100644 jarvis/utils/db.py diff --git a/config.example.yaml b/config.example.yaml index 5276ff6..d654f45 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -7,3 +7,8 @@ - user - ids logo: alligator2 + mongo: + username: user + password: pass + host: localhost + port: 27017 diff --git a/jarvis/__init__.py b/jarvis/__init__.py index 2bbb544..ab22306 100644 --- a/jarvis/__init__.py +++ b/jarvis/__init__.py @@ -6,8 +6,8 @@ from psutil import Process import asyncio from jarvis.config import get_config -from jarvis import utils -from jarvis import logo +from jarvis import utils, logo + if asyncio.get_event_loop().is_closed(): asyncio.set_event_loop(asyncio.new_event_loop()) @@ -16,6 +16,7 @@ intents = Intents.default() intents.members = True restart_ctx = None + jarvis = commands.Bot(command_prefix=utils.get_prefix, intents=intents) jarvis_self = Process() __version__ = "0.1.0" diff --git a/jarvis/cogs/jokes.py b/jarvis/cogs/jokes.py new file mode 100644 index 0000000..d05cfb9 --- /dev/null +++ b/jarvis/cogs/jokes.py @@ -0,0 +1,81 @@ +import jarvis +import discord +from random import randint +import html +import re +from jarvis.utils import build_embed, db +from jarvis.utils.field import Field +from discord.ext import commands +from datetime import datetime + + +class JokeCog(commands.Cog): + def __init__(self, bot): + self.bot = bot + self.db = db.create_connection() + + # TODO: Make this a command group with subcommands + @commands.command(name="joke", help="Hear a joke") + async def _joke(self, ctx, id: str = None): + if randint(1, 100_000) == 5779 and id is None: + await ctx.send(f"<@{ctx.message.author.id}>") + return + # TODO: Add this as a parameter that can be passed in + threshold = 500 # Minimum score + coll = self.db.jokes.reddit + result = None + if id: + result = coll.find_one({"id": id}) + else: + result = list( + coll.aggregate( + [ + {"$match": {"score": {"$gt": threshold}}}, + {"$sample": {"size": 1}}, + ] + ) + )[0] + while result["body"] in ["[removed]", "[deleted]"]: + result = list( + coll.aggregate( + [ + {"$match": {"score": {"$gt": threshold}}}, + {"$sample": {"size": 1}}, + ] + ) + )[0] + # TODO: Build a custom embed to show the joke + if result is None: + await ctx.send("Humor module failed. Please try again later.") + return + emotes = re.findall(r"(&#x[a-fA-F0-9]*;)", result["body"]) + for match in emotes: + result["body"] = result["body"].replace( + match, html.unescape(match) + ) + emotes = re.findall(r"(&#x[a-fA-F0-9]*;)", result["title"]) + for match in emotes: + result["title"] = result["title"].replace( + match, html.unescape(match) + ) + fields = [ + Field("​", result["body"], False), + Field("Score", result["score"]), + Field( + "Created At", + str(datetime.fromtimestamp(result["created_utc"])), + ), + Field("ID", result["id"]), + ] + embed = build_embed( + title=result["title"], + desc=None, + fields=fields, + url=f"https://reddit.com/r/jokes/comments/{result['id']}", + ) + await ctx.send(embed=embed) + # await ctx.send(f"**{result['title']}**\n\n{result['body']}") + + +def setup(bot): + bot.add_cog(JokeCog(bot)) diff --git a/jarvis/config.py b/jarvis/config.py index aef734f..690b935 100644 --- a/jarvis/config.py +++ b/jarvis/config.py @@ -13,15 +13,11 @@ class Config: client_id: str admins: list logo: str + mongo: dict @classmethod def from_yaml(cls, y): - instance = cls( - token=y["token"], - client_id=y["client_id"], - admins=y["admins"], - logo=y["logo"], - ) + instance = cls(**y) return instance diff --git a/jarvis/utils/__init__.py b/jarvis/utils/__init__.py index 4fb9dfa..f02633b 100644 --- a/jarvis/utils/__init__.py +++ b/jarvis/utils/__init__.py @@ -2,8 +2,11 @@ from discord.ext import commands from discord import Embed, Color from pkgutil import iter_modules import jarvis.cogs +import jarvis.utils.db import git +__all__ = ["field", "db"] + def convert_bytesize(bytes: int) -> str: bytes = float(bytes) @@ -34,7 +37,11 @@ def parse_color_hex(hex: str) -> Color: def build_embed( - title: str, desc: str, fields: list, color: str = "#FF0000", **kwargs + title: str, + desc: str, + fields: list, + color: str = "#FF0000", + **kwargs, ) -> Embed: embed = Embed( title=title, desc=desc, color=parse_color_hex(color), **kwargs diff --git a/jarvis/utils/db.py b/jarvis/utils/db.py new file mode 100644 index 0000000..20a79d6 --- /dev/null +++ b/jarvis/utils/db.py @@ -0,0 +1,7 @@ +from pymongo import MongoClient +from jarvis.config import get_config + + +def create_connection() -> MongoClient: + config = get_config() + return MongoClient(**config.mongo)