such cleanup

This commit is contained in:
2025-02-15 08:36:45 -05:00
parent d60828df07
commit 9d23438b13
12 changed files with 357 additions and 209 deletions

View File

@ -6,12 +6,13 @@ import json
import io
import asyncio
import random
from typing import LiteralString, Optional
from typing import LiteralString, Optional, Any
import logging
import textwrap
import regex
import requests
import discord
from disc_havoc import Havoc
from aiohttp import ClientSession
from discord.ext import bridge, commands, tasks
from jesusmemes import JesusMemeGenerator
@ -56,6 +57,8 @@ class MemeView(discord.ui.View):
async def select_callback(self, select: discord.ui.Select,
interaction: discord.Interaction) -> None:
"""Meme Selection Callback"""
if not isinstance(select.values[0], str):
return
modal: discord.ui.Modal = MemeModal(meme=select.values[0], title="Meme Selected")
await interaction.response.send_modal(modal)
@ -63,7 +66,7 @@ class MemeModal(discord.ui.Modal):
"""Meme Creation discord.ui.Modal"""
def __init__(self, *args, meme: Optional[str] = None, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.selected_meme: str = meme
self.selected_meme: Optional[str] = meme
self.meme_generator = JesusMemeGenerator()
self.TEXT_LIMIT: int = 80
@ -73,7 +76,14 @@ class MemeModal(discord.ui.Modal):
style=discord.InputTextStyle.singleline))
async def callback(self, interaction: discord.Interaction) -> None:
if not self.selected_meme: # No meme selected
return
selected_meme: str = self.selected_meme
if not self.children or len(self.children) < 2: # Invalid request
return
if not isinstance(self.children[0].value, str)\
or not isinstance(self.children[1].value, str): # Invalid request
return
meme_top_line: str = self.children[0].value.strip()
meme_bottom_line: str = self.children[1].value.strip()
if len(meme_top_line) > self.TEXT_LIMIT or len(meme_bottom_line) > self.TEXT_LIMIT:
@ -85,18 +95,18 @@ class MemeModal(discord.ui.Modal):
embed: discord.Embed = discord.Embed(title="Generated Meme")
embed.set_image(url=meme_link)
embed.add_field(name="Meme", value=self.selected_meme, inline=True)
embed.add_field(name="Meme", value=selected_meme, inline=True)
await interaction.response.send_message(embeds=[embed])
return
class Meme(commands.Cog):
"""Meme Cog for Havoc"""
def __init__(self, bot) -> None:
self.bot: discord.Bot = bot
def __init__(self, bot: Havoc) -> None:
self.bot: Havoc = bot
self.meme_choices: list = []
self.meme_counter: int = 0
self.THREADS: dict[dict[list]] = {
self.THREADS: dict[str, dict[int, list]] = {
# Format: Guild1: [ChanId : [Webhook, ThreadId], Guild2: [ChanId : [Webhook, ThreadId]
'comic_explosm': {
1298729744216359055: [constants.EXPLOSM_WEBHOOK, 1299165855493390367],
@ -120,7 +130,7 @@ class Meme(commands.Cog):
}
}
self.NO_THREAD_WEBHOOKS: dict[list] = {
self.NO_THREAD_WEBHOOKS: dict[str, list] = {
'theonion': [constants.ONION_WEBHOOK, constants.ONION_WEBHOOK2],
'thn': [constants.THN_WEBHOOK],
'memes': [constants.MEME_WEBHOOK1, constants.MEME_WEBHOOK2],
@ -132,7 +142,7 @@ class Meme(commands.Cog):
self.meme_stream_loop.start()
self.explosm_loop.start()
def is_spamchan() -> bool: # pylint: disable=no-method-argument
def is_spamchan() -> bool: # type: ignore
"""Check if channel is spamchan"""
def predicate(ctx):
try:
@ -142,7 +152,7 @@ class Meme(commands.Cog):
except:
traceback.print_exc()
return False
return commands.check(predicate)
return commands.check(predicate) # type: ignore
@ -163,39 +173,43 @@ class Meme(commands.Cog):
dino_grabber = dinog.DinosaurGrabber()
onion_grabber = oniong.OnionGrabber()
thn_grabber = thng.THNGrabber()
explosm_comics = xkcd_comics = smbc_comics = qc_comics = dino_comics\
= onions = thns = []
memes: list[tuple] = await meme_grabber.get()
explosm_comics: list[Optional[tuple]] = []
xkcd_comics: list[Optional[tuple]] = []
smbc_comics: list[Optional[tuple]] = []
dino_comics: list[Optional[tuple]] = []
onions: list[Optional[tuple]] = []
thns: list[Optional[tuple]] = []
memes: list[Optional[tuple]] = await meme_grabber.get()
try:
try:
explosm_comics: list[tuple] = await explosm_grabber.get()
explosm_comics = await explosm_grabber.get()
except:
pass
try:
xkcd_comics: list[tuple] = await xkcd_grabber.get()
xkcd_comics = await xkcd_grabber.get()
except:
pass
try:
smbc_comics: list[tuple] = await smbc_grabber.get()
smbc_comics = await smbc_grabber.get()
except:
pass
try:
qc_comics: list[tuple] = await qc_grabber.get()
qc_comics = await qc_grabber.get()
print(f"QC: {qc_comics}")
except:
pass
try:
dino_comics: list[tuple] = await dino_grabber.get()
dino_comics = await dino_grabber.get()
except Exception as e:
logging.debug("Dino failed: %s", str(e))
pass
try:
onions: list[tuple] = await onion_grabber.get()
onions = await onion_grabber.get()
except Exception as e:
logging.debug("Onion failed: %s", str(e))
pass
try:
thns: list[tuple] = await thn_grabber.get()
thns = await thn_grabber.get()
except Exception as e:
logging.debug("THNs failed: %s", str(e))
pass
@ -208,12 +222,14 @@ class Meme(commands.Cog):
if not only_comics:
try:
for meme in memes:
if not meme:
continue
(meme_id, meme_title, meme_url) = meme # pylint: disable=unused-variable
request = requests.get(meme_url, stream=True, timeout=(5, 30), headers=headers)
if not request.status_code == 200:
continue
meme_content: bytes = request.raw.read()
for meme_hook in self.NO_THREAD_WEBHOOKS.get('memes'):
for meme_hook in self.NO_THREAD_WEBHOOKS.get('memes', {}):
meme_image: io.BytesIO = io.BytesIO(meme_content)
ext: str = meme_url.split(".")[-1]\
.split("?")[0].split("&")[0]
@ -227,24 +243,27 @@ class Meme(commands.Cog):
pass
try:
for comic in explosm_comics:
if not comic:
continue
(comic_title, comic_url) = comic
comic_title: str = discord.utils.escape_markdown(comic_title)
comic_title = discord.utils.escape_markdown(comic_title)
comic_request = requests.get(comic_url, stream=True, timeout=(5, 20), headers=headers)
comic_request.raise_for_status()
comic_content: bytes = comic_request.raw.read()
ext: str = comic_url.split(".")[-1]\
ext = comic_url.split(".")[-1]\
.split("?")[0].split("&")[0]
async with ClientSession() as session:
for chanid, _hook in self.THREADS.get('comic_explosm').items():
for chanid, _hook in self.THREADS.get('comic_explosm', {}).items():
comic_image: io.BytesIO = io.BytesIO(comic_content)
channel: int = chanid
hook_uri: str = _hook[0]
thread_id: int = _hook[1]
webhook: discord.Webhook = discord.Webhook.from_url(hook_uri,
(hook_uri, thread_id) = _hook
webhook = discord.Webhook.from_url(hook_uri,
session=session)
thread: discord.Thread = self.bot.get_channel(channel)\
.get_thread(thread_id)
_channel: Any = self.bot.get_channel(channel)
if not _channel:
return
thread = _channel.get_thread(thread_id)
await webhook.send(f"**{comic_title}**", file=discord.File(comic_image, filename=f'img.{ext}'),
username="Cyanide & Happiness", thread=thread)
await asyncio.sleep(2)
@ -252,25 +271,28 @@ class Meme(commands.Cog):
pass
try:
for comic in xkcd_comics:
if not comic:
continue
(comic_title, comic_url) = comic
comic_title: str = discord.utils.escape_markdown(comic_title)
comic_title = discord.utils.escape_markdown(comic_title)
comic_request = requests.get(comic_url, stream=True, timeout=(5, 20), headers=headers)
comic_request.raise_for_status()
comic_content: bytes = comic_request.raw.read()
comic_image: io.BytesIO = io.BytesIO(comic_request.raw.read())
ext: str = comic_url.split(".")[-1]\
comic_content = comic_request.raw.read()
comic_image = io.BytesIO(comic_request.raw.read())
ext = comic_url.split(".")[-1]\
.split("?")[0].split("&")[0]
async with ClientSession() as session:
for chanid, _hook in self.THREADS.get('comic_xkcd').items():
comic_image: io.BytesIO = io.BytesIO(comic_content)
channel: int = chanid
hook_uri: str = _hook[0]
thread_id: int = _hook[1]
webhook: discord.Webhook = discord.Webhook.from_url(hook_uri,
for chanid, _hook in self.THREADS.get('comic_xkcd', {}).items():
comic_image = io.BytesIO(comic_content)
channel = chanid
(hook_uri, thread_id) = _hook
webhook = discord.Webhook.from_url(hook_uri,
session=session)
thread: discord.Thread = self.bot.get_channel(channel)\
.get_thread(thread_id)
_channel = self.bot.get_channel(channel)
if not _channel:
return
thread = _channel.get_thread(thread_id)
await webhook.send(f"**{comic_title}**", file=discord.File(comic_image, filename=f'img.{ext}'),
username="xkcd", thread=thread)
await asyncio.sleep(2)
@ -278,24 +300,27 @@ class Meme(commands.Cog):
pass
try:
for comic in smbc_comics:
if not comic:
continue
(comic_title, comic_url) = comic
comic_title: str = discord.utils.escape_markdown(comic_title)
comic_title = discord.utils.escape_markdown(comic_title)
comic_request = requests.get(comic_url, stream=True, timeout=(5, 20), headers=headers)
comic_request.raise_for_status()
comic_content: bytes = comic_request.raw.read()
ext: str = comic_url.split(".")[-1]\
comic_content = comic_request.raw.read()
ext = comic_url.split(".")[-1]\
.split("?")[0].split("&")[0]
async with ClientSession() as session:
for chanid, _hook in self.THREADS.get('comic_smbc').items():
comic_image: io.BytesIO = io.BytesIO(comic_content)
channel: int = chanid
hook_uri: str = _hook[0]
thread_id: int = _hook[1]
webhook: discord.Webhook = discord.Webhook.from_url(hook_uri,
for chanid, _hook in self.THREADS.get('comic_smbc', {}).items():
comic_image = io.BytesIO(comic_content)
channel = chanid
(hook_uri, thread_id) = _hook
webhook = discord.Webhook.from_url(hook_uri,
session=session)
thread = self.bot.get_channel(channel)\
.get_thread(thread_id)
_channel = self.bot.get_channel(channel)
if not _channel:
return
thread = _channel.get_thread(thread_id)
await webhook.send(f"**{comic_title}**", file=discord.File(comic_image, filename=f'img.{ext}'),
username="SMBC", thread=thread)
await asyncio.sleep(2)
@ -304,29 +329,32 @@ class Meme(commands.Cog):
try:
for comic in qc_comics:
logging.debug("Trying QC...")
if not comic:
continue
(comic_title, comic_url) = comic
comic_title: str = discord.utils.escape_markdown(comic_title)
comic_url: str = regex.sub(r'^http://ww\.', 'http://www.',
comic_title = discord.utils.escape_markdown(comic_title)
comic_url = regex.sub(r'^http://ww\.', 'http://www.',
comic_url)
comic_url: str = regex.sub(r'\.pmg$', '.png',
comic_url = regex.sub(r'\.pmg$', '.png',
comic_url)
comic_request = requests.get(comic_url, stream=True,
timeout=(5, 20), headers=headers)
comic_request.raise_for_status()
comic_content: bytes = comic_request.raw.read()
ext: str = comic_url.split(".")[-1]\
comic_content = comic_request.raw.read()
ext = comic_url.split(".")[-1]\
.split("?")[0].split("&")[0]
async with ClientSession() as session:
for chanid, _hook in self.THREADS.get('comic_qc').items():
comic_image: io.BytesIO = io.BytesIO(comic_content)
channel: int = chanid
hook_uri: str = _hook[0]
thread_id: int = _hook[1]
webhook: discord.Webhook = discord.Webhook.from_url(hook_uri,
for chanid, _hook in self.THREADS.get('comic_qc', {}).items():
comic_image = io.BytesIO(comic_content)
channel = chanid
(hook_uri, thread_id) = _hook
webhook = discord.Webhook.from_url(hook_uri,
session=session)
thread: discord.Thread = self.bot.get_channel(channel)\
.get_thread(thread_id)
_channel = self.bot.get_channel(channel)
if not _channel:
return
thread = _channel.get_thread(thread_id)
await webhook.send(f"**{comic_title}**", file=discord.File(comic_image, filename=f'img.{ext}'),
username="Questionable Content", thread=thread)
await asyncio.sleep(2)
@ -335,24 +363,27 @@ class Meme(commands.Cog):
pass
try:
for comic in dino_comics:
if not comic:
continue
(comic_title, comic_url) = comic
comic_title: str = discord.utils.escape_markdown(comic_title)
comic_title = discord.utils.escape_markdown(comic_title)
comic_request = requests.get(comic_url, stream=True, timeout=(5, 20), headers=headers)
comic_request.raise_for_status()
comic_content: bytes = comic_request.raw.read()
comic_content = comic_request.raw.read()
ext = comic_url.split(".")[-1]\
.split("?")[0].split("&")[0]
async with ClientSession() as session:
for chanid, _hook in self.THREADS.get('comic_dino').items():
comic_image: io.BytesIO = io.BytesIO(comic_content)
channel: int = chanid
hook_uri: str = _hook[0]
thread_id: int = _hook[1]
webhook: discord.Webhook = discord.Webhook.from_url(hook_uri,
for chanid, _hook in self.THREADS.get('comic_dino', {}).items():
comic_image = io.BytesIO(comic_content)
channel = chanid
(hook_uri, thread_id) = _hook
webhook = discord.Webhook.from_url(hook_uri,
session=session)
thread: discord.Thread = self.bot.get_channel(channel)\
.get_thread(thread_id)
_channel = self.bot.get_channel(channel)
if not _channel:
return
thread = _channel.get_thread(thread_id)
await webhook.send(f"**{comic_title}**", file=discord.File(comic_image, filename=f'img.{ext}'),
username="Dinosaur Comics", thread=thread)
await asyncio.sleep(2)
@ -360,15 +391,17 @@ class Meme(commands.Cog):
pass
try:
for onion in onions:
if not onion:
continue
(onion_title, onion_description, onion_link, onion_video) = onion
onion_description: list[str] = textwrap.wrap(text=onion_description,
onion_description = textwrap.wrap(text=onion_description,
width=860, max_lines=1)[0]
embed: discord.Embed = discord.Embed(title=onion_title)
embed.add_field(name="Content", value=f"{onion_description[0:960]}\n-# {onion_link}")
async with ClientSession() as session:
for hook in self.NO_THREAD_WEBHOOKS.get('theonion'):
hook_uri: str = hook
webhook: discord.Webhook = discord.Webhook.from_url(hook_uri,
for hook in self.NO_THREAD_WEBHOOKS.get('theonion', {}):
hook_uri = hook
webhook = discord.Webhook.from_url(hook_uri,
session=session)
await webhook.send(embed=embed, username="The Onion")
if onion_video:
@ -379,16 +412,18 @@ class Meme(commands.Cog):
try:
for thn in thns:
logging.debug("Trying thn...")
if not thn:
continue
(thn_title, thn_description, thn_link, thn_pubdate, thn_video) = thn
thn_description: list[str] = textwrap.wrap(text=thn_description,
thn_description = textwrap.wrap(text=thn_description,
width=860, max_lines=1)[0]
embed: discord.Embed = discord.Embed(title=thn_title)
embed = discord.Embed(title=thn_title)
embed.add_field(name="Content", value=f"{thn_description[0:960]}\n-# {thn_link}")
embed.add_field(name="Published", value=thn_pubdate, inline=False)
async with ClientSession() as session:
for hook in self.NO_THREAD_WEBHOOKS.get('thn'):
hook_uri: str = hook
webhook: discord.Webhook = discord.Webhook.from_url(hook_uri,
for hook in self.NO_THREAD_WEBHOOKS.get('thn', {}):
hook_uri = hook
webhook = discord.Webhook.from_url(hook_uri,
session=session)
await webhook.send(embed=embed, username="The Hacker News")
if thn_video:
@ -422,11 +457,11 @@ class Meme(commands.Cog):
except:
traceback.print_exc()
@bridge.bridge_command()
@is_spamchan() # pylint: disable=too-many-function-args
async def meme(self, ctx) -> None:
@bridge.bridge_command() # type: ignore
@is_spamchan()
async def meme(self, ctx) -> None:
"""Create Meme"""
await ctx.respond(view=MemeView())
await ctx.respond(view=MemeView())
@bridge.bridge_command(hidden=True)
@commands.is_owner()