jarvis-bot/jarvis/cogs/jokes.py
2021-06-27 15:32:22 -06:00

88 lines
2.8 KiB
Python
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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):
"""
Joke library for J.A.R.V.I.S.
May adapt over time to create jokes using machine learning
"""
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"],
description="",
fields=fields,
url=f"https://reddit.com/r/jokes/comments/{result['id']}",
timestamp=datetime.fromtimestamp(result["created_utc"]),
)
await ctx.send(embed=embed)
# await ctx.send(f"**{result['title']}**\n\n{result['body']}")
def setup(bot):
bot.add_cog(JokeCog(bot))