meme dupe snitching/misc

This commit is contained in:
2025-05-15 15:49:28 -04:00
parent 6a1fd659e8
commit 3dac803305
8 changed files with 105 additions and 55 deletions

View File

@@ -4,6 +4,9 @@ import json
import io
import asyncio
import random
import copy
from PIL import Image, UnidentifiedImageError
import imagehash
from typing import LiteralString, Optional, Any, Union
import aiosqlite as sqlite3
import logging
@@ -132,9 +135,12 @@ class Meme(commands.Cog):
def __init__(self, bot: Havoc) -> None:
self.bot: Havoc = bot
self.stats_db_path: LiteralString = os.path.join(
self.stats_db_path: str = os.path.join(
"/usr/local/share", "sqlite_dbs", "stats.db"
)
self.memedb_path: str = os.path.join(
"/usr/local/share", "sqlite_dbs", "meme.db"
)
self.meme_choices: list = []
self.meme_counter: int = 0
self.THREADS: dict[str, dict[int, list]] = {
@@ -243,6 +249,45 @@ class Meme(commands.Cog):
count = result["count"]
self.meme_leaderboard[uid] = count
async def insert_meme(
self, discord_uid: int, timestamp: int, message_id: int, image_url: str
) -> Optional[bool]:
"""
INSERT MEME -> SQLITE DB
"""
try:
_image: io.BytesIO = io.BytesIO(
requests.get(image_url, stream=True, timeout=20).raw.read()
)
image_copy = copy.deepcopy(_image)
image = Image.open(image_copy)
except UnidentifiedImageError:
return None
phash: str = str(imagehash.phash(image))
query: str = "INSERT INTO memes(discord_uid, timestamp, image, message_ids, phash) VALUES(?, ?, ?, ?, ?)"
async with sqlite3.connect(self.memedb_path, timeout=2) as db_conn:
insert = await db_conn.execute_insert(
query, (discord_uid, timestamp, _image.read(), message_id, phash)
)
if insert:
await db_conn.commit()
return True
return None
async def dupe_check(self, image) -> bool | int:
"""
CHECK DB FOR DUPLICATE MEMES!
"""
phash: str = str(imagehash.phash(image))
query: str = "SELECT message_ids FROM memes WHERE phash = ? LIMIT 1"
async with sqlite3.connect(self.memedb_path, timeout=2) as db_conn:
db_conn.row_factory = sqlite3.Row
async with await db_conn.execute(query, (phash,)) as db_cursor:
result = await db_cursor.fetchone()
if result:
return result["message_ids"]
return False
@commands.Cog.listener()
async def on_ready(self) -> None:
"""Run on Bot Ready"""
@@ -644,6 +689,7 @@ class Meme(commands.Cog):
Also monitors for messages to #memes-top-10 to autodelete, only Havoc may post in #memes-top-10!
"""
lb_chanid: int = 1352373745108652145
meme_chanid: int = 1147229098544988261
if not self.bot.user: # No valid client instance
return
if not isinstance(message.channel, discord.TextChannel):
@@ -666,12 +712,37 @@ class Meme(commands.Cog):
return
if not message.guild:
return
if not message.channel.id == 1147229098544988261: # Not meme channel
if message.channel.id not in [
1157529874936909934,
meme_chanid,
]: # Not meme channel
return
if not message.attachments: # No attachments to consider a meme
return
await self.leaderboard_increment(message.author.id)
unique_memes: list = []
for item in message.attachments:
if item.url and len(item.url) >= 20:
image: io.BytesIO = io.BytesIO(
requests.get(item.url, stream=True, timeout=20).raw.read()
)
dupe_check = await self.dupe_check(Image.open(image))
if dupe_check:
channel = message.channel
original_message = await channel.fetch_message(dupe_check) # type: ignore
original_message_url = original_message.jump_url
await message.add_reaction(
emoji="<:quietscheentchen:1255956612804247635>"
)
await message.reply(original_message_url)
else:
unique_memes.append(item.url)
if unique_memes:
await self.leaderboard_increment(message.author.id)
for meme_url in unique_memes:
author_id: int = message.author.id
timestamp: int = int(message.created_at.timestamp())
await self.insert_meme(author_id, timestamp, message.id, meme_url)
async def get_top(self, n: int = 10) -> Optional[list[tuple]]:
"""
@@ -686,9 +757,7 @@ class Meme(commands.Cog):
out_top: list[tuple[int, int]] = []
async with sqlite3.connect(self.stats_db_path, timeout=2) as db_conn:
db_conn.row_factory = sqlite3.Row
query: str = (
"SELECT discord_uid, count FROM memes WHERE count > 0 ORDER BY count DESC"
)
query: str = "SELECT discord_uid, count FROM memes WHERE count > 0 ORDER BY count DESC"
async with db_conn.execute(query) as db_cursor:
db_result = await db_cursor.fetchall()
for res in db_result:
@@ -734,9 +803,7 @@ class Meme(commands.Cog):
if not member:
continue
display_name: str = member.display_name
top_formatted += (
f"{x+1}. **{discord.utils.escape_markdown(display_name)}**: *{count}*\n"
)
top_formatted += f"{x + 1}. **{discord.utils.escape_markdown(display_name)}**: *{count}*\n"
top_formatted = top_formatted.strip()
embed: discord.Embed = discord.Embed(
title=f"Top {n} Memes", description=top_formatted, colour=0x25BD6B