Skip to content

Commit

Permalink
Add more lint rules
Browse files Browse the repository at this point in the history
  • Loading branch information
hypergonial committed Dec 16, 2023
1 parent ee73cd1 commit a0362f2
Show file tree
Hide file tree
Showing 37 changed files with 271 additions and 435 deletions.
20 changes: 9 additions & 11 deletions extensions/automod.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,24 +77,23 @@ async def get_policies(guild: hikari.SnowflakeishOr[hikari.Guild]) -> dict[str,
dict[str, t.Any]
The guild's auto-moderation policies.
"""

guild_id = hikari.Snowflake(guild)

records = await automod.app.db_cache.get(table="mod_config", guild_id=guild_id)

policies = json.loads(records[0]["automod_policies"]) if records else default_automod_policies

for key in default_automod_policies.keys():
for key in default_automod_policies:
if key not in policies:
policies[key] = default_automod_policies[key]

for nested_key in default_automod_policies[key].keys():
for nested_key in default_automod_policies[key]:
if nested_key not in policies[key]:
policies[key][nested_key] = default_automod_policies[key][nested_key]

invalid = []
for key in policies.keys():
if key not in default_automod_policies.keys():
for key in policies:
if key not in default_automod_policies:
invalid.append(key)

for key in invalid:
Expand All @@ -107,8 +106,7 @@ async def get_policies(guild: hikari.SnowflakeishOr[hikari.Guild]) -> dict[str,


def can_automod_punish(me: hikari.Member, offender: hikari.Member) -> bool:
"""
Determine if automod can punish a member.
"""Determine if automod can punish a member.
This checks all required permissions and if the member is a cool person or not.
Parameters
Expand Down Expand Up @@ -141,6 +139,7 @@ def can_automod_punish(me: hikari.Member, offender: hikari.Member) -> bool:
return True


# TODO: Split this
async def punish(
message: hikari.PartialMessage,
policies: dict[str, t.Any],
Expand Down Expand Up @@ -341,8 +340,8 @@ async def detect_mass_mentions(message: hikari.PartialMessage, policies: dict[st
Returns
-------
bool
Whether or not the analysis should proceed to the next check."""

Whether or not the analysis should proceed to the next check.
"""
if policies["mass_mentions"]["state"] != AutoModState.DISABLED.value and message.user_mentions:
assert message.author
mentions = sum(user.id != message.author.id and not user.is_bot for user in message.user_mentions.values())
Expand Down Expand Up @@ -591,7 +590,7 @@ async def detect_perspective(message: hikari.PartialMessage, policies: dict[str,
try:
resp: kosu.AnalysisResponse = await automod.app.perspective.analyze(message.content, persp_attribs)
except kosu.PerspectiveException as e:
logger.debug(f"Perspective failed to analyze a message: {str(e)}")
logger.debug(f"Perspective failed to analyze a message: {e}")
else:
scores = {score.name.name: score.summary.value for score in resp.attribute_scores}

Expand All @@ -614,7 +613,6 @@ async def scan_messages(
plugin: SnedPlugin, event: hikari.GuildMessageCreateEvent | hikari.GuildMessageUpdateEvent
) -> None:
"""Scan messages for all possible offences."""

message = event.message

if not message.author:
Expand Down
13 changes: 8 additions & 5 deletions extensions/command_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
import datetime
import logging
import traceback
from typing import TYPE_CHECKING

import hikari
import lightbulb

from etc import const
from etc.perms_str import get_perm_str
from models import SnedContext
from models.bot import SnedBot
from models.context import SnedPrefixContext, SnedSlashContext
from models.errors import (
Expand All @@ -23,6 +23,9 @@
from models.plugin import SnedPlugin
from utils import helpers

if TYPE_CHECKING:
from models import SnedContext

logger = logging.getLogger(__name__)

ch = SnedPlugin("Command Handler")
Expand All @@ -42,7 +45,6 @@ async def log_exc_to_channel(
event : hikari.ExceptionEvent, optional
The event to use for additional information, by default None
"""

error_lines = error_str.split("\n")
paginator = lightbulb.utils.StringPaginator(max_chars=2000, prefix="```py\n", suffix="```")
if ctx:
Expand Down Expand Up @@ -258,9 +260,10 @@ async def application_command_error_handler(event: lightbulb.CommandErrorEvent)
@ch.listener(lightbulb.SlashCommandCompletionEvent)
@ch.listener(lightbulb.MessageCommandCompletionEvent)
async def application_command_completion_handler(event: lightbulb.events.CommandCompletionEvent):
if event.context.author.id in event.context.app.owner_ids: # Ignore cooldowns for owner c:
if cm := event.command.cooldown_manager:
await cm.reset_cooldown(event.context)
if event.context.author.id in event.context.app.owner_ids and (
cm := event.command.cooldown_manager
): # Ignore cooldowns for owner c:
await cm.reset_cooldown(event.context)


@ch.listener(lightbulb.PrefixCommandErrorEvent)
Expand Down
15 changes: 5 additions & 10 deletions extensions/dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import subprocess
import textwrap
import traceback
from contextlib import suppress

import hikari
import lightbulb
Expand Down Expand Up @@ -70,9 +71,7 @@ async def send_paginated(
prefix: str = "",
suffix: str = "",
) -> None:
"""
Send command output paginated if appropriate.
"""
"""Send command output paginated if appropriate."""
text = str(text)
channel_id = None
if not isinstance(messageable, hikari.User):
Expand Down Expand Up @@ -113,10 +112,7 @@ async def send_paginated(


async def run_shell(ctx: SnedPrefixContext, code: str) -> None:
"""
Run code in shell and return output to Discord.
"""

"""Run code in shell and return output to Discord."""
code = str(code).replace("```py", "").replace("`", "").strip()

await ctx.app.rest.trigger_typing(ctx.channel_id)
Expand Down Expand Up @@ -336,10 +332,9 @@ async def restore_db(ctx: SnedPrefixContext) -> None:
path = os.path.join(ctx.app.base_dir, "db", "backups", "dev_pg_restore_snapshot.pgdmp")
with open(path, "wb") as file:
file.write((await ctx.attachments[0].read()))
try:

with suppress(hikari.HikariError):
await ctx.event.message.delete()
except hikari.HikariError:
pass

await ctx.app.db_cache.stop()

Expand Down
1 change: 0 additions & 1 deletion extensions/fandom.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ async def search_fandom(site: str, query: str) -> str | None:
Optional[str]
A formatted string ready to display to the end user. `None` if no results were found.
"""

async with fandom.app.session.get(yarl.URL(FANDOM_QUERY_URL.format(query=query, site=site))) as response:
if response.status == 200:
results = await response.json()
Expand Down
92 changes: 44 additions & 48 deletions extensions/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
import os
import random
from enum import IntEnum
from fractions import Fraction
from io import BytesIO
from pathlib import Path
from textwrap import fill
from typing import TYPE_CHECKING

import hikari
import Levenshtein as lev
import Levenshtein as lev # noqa: N813
import lightbulb
import miru
from miru.ext import nav
Expand All @@ -24,10 +24,13 @@
from models.plugin import SnedPlugin
from models.views import AuthorOnlyNavigator, AuthorOnlyView
from utils import GlobalBucket, RateLimiter, helpers
from utils.dictionaryapi import DictionaryClient, DictionaryEntry, DictionaryException, UrbanEntry
from utils.dictionaryapi import DictionaryClient, DictionaryEntry, DictionaryError, UrbanEntry
from utils.ratelimiter import UserBucket
from utils.rpn import InvalidExpressionError, Solver

if TYPE_CHECKING:
from fractions import Fraction

ANIMAL_EMOJI_MAPPING: dict[str, str] = {
"dog": "🐶",
"cat": "🐱",
Expand All @@ -45,27 +48,22 @@

logger = logging.getLogger(__name__)

if api_key := os.getenv("DICTIONARYAPI_API_KEY"):
dictionary_client = DictionaryClient(api_key)
else:
dictionary_client = None
dictionary_client = DictionaryClient(key) if (key := os.getenv("DICTIONARYAPI_API_KEY")) else None


@lightbulb.Check # type: ignore
def has_dictionary_client(_: SnedContext) -> bool:
if dictionary_client:
return True
raise DictionaryException("Dictionary API key not set.")
raise DictionaryError("Dictionary API key not set.")


fun = SnedPlugin("Fun")


@fun.set_error_handler()
async def handle_errors(event: lightbulb.CommandErrorEvent) -> bool:
if isinstance(event.exception, lightbulb.CheckFailure) and isinstance(
event.exception.__cause__, DictionaryException
):
if isinstance(event.exception, lightbulb.CheckFailure) and isinstance(event.exception.__cause__, DictionaryError):
await event.context.respond(
embed=hikari.Embed(
title="❌ No Dictionary API key provided",
Expand Down Expand Up @@ -308,9 +306,7 @@ async def on_timeout(self) -> None:
)

def check_blocked(self) -> bool:
"""
Check if the board is blocked
"""
"""Check if the board is blocked."""
blocked_list = [False, False, False, False]

# TODO: Replace this old garbage
Expand Down Expand Up @@ -365,10 +361,7 @@ def check_blocked(self) -> bool:
return False

def check_winner(self) -> WinState | None:
"""
Check if there is a winner
"""

"""Check if there is a winner."""
# Check rows
for row in self.board:
value = sum(row)
Expand Down Expand Up @@ -483,7 +476,7 @@ def __init__(self, lctx: lightbulb.Context, *, entries: list[DictionaryEntry]) -
@lightbulb.implements(lightbulb.SlashCommand)
async def calc(ctx: SnedSlashContext, expr: str | None = None, display: str = "decimal") -> None:
if not expr:
view = CalculatorView(ctx, True if display == "fractional" else False)
view = CalculatorView(ctx, display == "fractional")
resp = await ctx.respond("```-```", components=view)
await view.start(resp)
return
Expand Down Expand Up @@ -571,11 +564,10 @@ async def typeracer(ctx: SnedSlashContext, difficulty: str | None = None, length
length = length or 5
difficulty = difficulty or "medium"

file = open(Path(ctx.app.base_dir, "etc", "text", f"words_{difficulty}.txt"), "r")
words = [word.strip() for word in file.readlines()]
with open(Path(ctx.app.base_dir, "etc", "text", f"words_{difficulty}.txt"), "r") as file:
words = [word.strip() for word in file.readlines()]

text = " ".join([random.choice(words) for _ in range(0, length)])
file.close()
text = " ".join([random.choice(words) for _ in range(0, length)])

resp = await ctx.respond(
embed=hikari.Embed(
Expand Down Expand Up @@ -642,11 +634,11 @@ def predicate(event: hikari.GuildMessageCreateEvent) -> bool:

if text.lower() == message.content.lower():
winners[message.author] = (helpers.utcnow() - start).total_seconds()
asyncio.create_task(message.add_reaction("✅"))
asyncio.create_task(message.add_reaction("✅")) # noqa: RUF006
end_trigger.set()

elif lev.distance(text.lower(), message.content.lower()) < 5:
asyncio.create_task(message.add_reaction("❌"))
asyncio.create_task(message.add_reaction("❌")) # noqa: RUF006

return False

Expand All @@ -669,16 +661,17 @@ def predicate(event: hikari.GuildMessageCreateEvent) -> bool:
await ctx.respond(
embed=hikari.Embed(
title="🏁 First Place",
description=f"**{list(winners.keys())[0]}** finished first, everyone else has **15 seconds** to submit their reply!",
description=f"**{next(iter(winners.keys()))}** finished first, everyone else has **15 seconds** to submit their reply!",
color=const.EMBED_GREEN,
)
)
await asyncio.sleep(15.0)
msg_listener.cancel()

desc = "**Participants:**\n"
winner_keys = list(winners.keys())
for winner in winners:
desc = f"{desc}**#{list(winners.keys()).index(winner)+1}** **{winner}** `{round(winners[winner], 1)}` seconds - `{round((len(text) / 5) / (winners[winner] / 60))}`WPM\n"
desc = f"{desc}**#{winner_keys.index(winner)+1}** **{winner}** `{round(winners[winner], 1)}` seconds - `{round((len(text) / 5) / (winners[winner] / 60))}`WPM\n"

await ctx.respond(
embed=hikari.Embed(
Expand Down Expand Up @@ -787,14 +780,15 @@ async def avatar_context(ctx: SnedUserContext, target: hikari.User | hikari.Memb
@lightbulb.implements(lightbulb.SlashCommand)
async def funfact(ctx: SnedSlashContext) -> None:
fun_path = Path(ctx.app.base_dir, "etc", "text", "funfacts.txt")
fun_facts = open(fun_path, "r").readlines()
await ctx.respond(
embed=hikari.Embed(
title="🤔 Did you know?",
description=f"{random.choice(fun_facts)}",
color=const.EMBED_BLUE,
with open(fun_path, "r") as file:
fun_facts = file.readlines()
await ctx.respond(
embed=hikari.Embed(
title="🤔 Did you know?",
description=f"{random.choice(fun_facts)}",
color=const.EMBED_BLUE,
)
)
)


@fun.command
Expand All @@ -803,14 +797,15 @@ async def funfact(ctx: SnedSlashContext) -> None:
@lightbulb.implements(lightbulb.SlashCommand)
async def penguinfact(ctx: SnedSlashContext) -> None:
penguin_path = Path(ctx.app.base_dir, "etc", "text", "penguinfacts.txt")
penguin_facts = open(penguin_path, "r").readlines()
await ctx.respond(
embed=hikari.Embed(
title="🐧 Penguin Fact",
description=f"{random.choice(penguin_facts)}",
color=const.EMBED_BLUE,
with open(penguin_path, "r") as file:
penguin_facts = file.readlines()
await ctx.respond(
embed=hikari.Embed(
title="🐧 Penguin Fact",
description=f"{random.choice(penguin_facts)}",
color=const.EMBED_BLUE,
)
)
)


def roll_dice(amount: int, sides: int, show_sum: bool) -> hikari.Embed:
Expand Down Expand Up @@ -960,14 +955,15 @@ async def animal(ctx: SnedSlashContext, animal: str) -> None:
@lightbulb.implements(lightbulb.SlashCommand)
async def eightball(ctx: SnedSlashContext, question: str) -> None:
ball_path = Path(ctx.app.base_dir, "etc", "text", "8ball.txt")
answers = open(ball_path, "r").readlines()
await ctx.respond(
embed=hikari.Embed(
title=f"🎱 {question}",
description=f"{random.choice(answers)}",
color=const.EMBED_BLUE,
with open(ball_path, "r") as file:
answers = file.readlines()
await ctx.respond(
embed=hikari.Embed(
title=f"🎱 {question}",
description=f"{random.choice(answers)}",
color=const.EMBED_BLUE,
)
)
)


@fun.command
Expand Down
2 changes: 1 addition & 1 deletion extensions/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
import lightbulb

import etc.const as const
from models.context import SnedSlashContext
from models.plugin import SnedPlugin

if t.TYPE_CHECKING:
from models import SnedBot
from models.context import SnedSlashContext


help = SnedPlugin("Help")
Expand Down
Loading

0 comments on commit a0362f2

Please sign in to comment.