Skip to content

Commit

Permalink
A lot of commands rewritten/upgraded see full changelog :)
Browse files Browse the repository at this point in the history
Bot wide changes:
- Addition of fuzzy string matching for various commands
- Main process loop is now asynchronous
- Guild member intent is now used
- Better error handling
- Lots of docstrings added, stray comments and prints removed
- Many commands and classes were moved around
- Colour standardization

File/Plugin specific changes:
- adata.py:
    - The top command now uses anitrendz/animecorner for airing
    - The vn command now has no spoiler tags and human datetime
    - The vn character command now has dropdowns
    - The character command improved with fuzzy matching and a dropdowns
- anime_plots.py:
    - The command now has a datetime autoscaling option
    - The plot isn't written to memory anymore
- info.py:
    - inrole command has fuzzy string matching now
    - NEW: inevent command
    - NEW: removesticker command
    - NEW: addemote command (with image compression)
- reload.py:
    - reload slash command
- sauce.py:
    - auto-defer for the MessageCommand
- tasks_utils.py:
    - fuzzy command name matching
    - embed colour testing command
- yt.py:
    - asynchronous now

Utility changes:
- buttons.py: Preview temp-fixed
- components.py: CharacterSelect for character dropdown
- models.py: Character class, colour class, others lookup classes WIP
- NEW: search_images.py: scrape google images

No major/notable changes in the other files
  • Loading branch information
infernalsaber committed Aug 18, 2023
1 parent ad87edf commit e5d88c4
Show file tree
Hide file tree
Showing 21 changed files with 1,956 additions and 1,035 deletions.
1 change: 1 addition & 0 deletions .example.env
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@

# BOT_TOKEN = "" # Insert the bot token you get from discord dev portal here
# SAUCENAO_KEY "" # Insert saucenao key here
# YT_KEY = ""# Insert YouTube key here

# Don't forget to uncomment the variables
88 changes: 36 additions & 52 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""The main file of the bot, basically sets up and starts the bot """
import asyncio
import datetime
import logging
import os
import sqlite3
from datetime import datetime

import aiohttp_client_cache
import dotenv
Expand All @@ -12,12 +12,11 @@
import miru
from lightbulb.ext import tasks

from functions.help import BotHelpCommand
from functions.utils import verbose_timedelta

dotenv.load_dotenv()

from functions.help import BotHelpCommand


# Setting the prefix as , for windows (where i run the test bot)
# and - for others (where it's deployed :) )
Expand All @@ -28,6 +27,16 @@ def return_prefix() -> list:
return ["-"]


guild_prefix_map = {980479965726404670: [","]}


def make_prefix(app, message: hk.Message) -> list:
try:
return guild_prefix_map[message.guild_id]
except:
return ["-"]


# The following snippet is borrowed from:
# https://github.com/Nereg/ARKMonitorBot/blob/
# 1a6cedf34d531bddf0f5b11b3238344192998997/src/main.py#L14
Expand Down Expand Up @@ -61,12 +70,13 @@ def setup_logging() -> None:
bot = lb.BotApp(
token=os.getenv("BOT_TOKEN"),
intents=hk.Intents.ALL_UNPRIVILEGED
| hk.Intents.MESSAGE_CONTENT
| hk.Intents.GUILD_MEMBERS,
prefix=lb.when_mentioned_or(return_prefix()),
# | hk.Intents.ALL_PRIVILEGED,
| hk.Intents.MESSAGE_CONTENT | hk.Intents.GUILD_MEMBERS,
prefix=lb.when_mentioned_or(make_prefix),
help_class=BotHelpCommand,
logs="INFO",
owner_ids=[1002964172360929343, 701090852243505212],
owner_ids=[701090852243505212],
help_slash_command=True,
)

miru.install(bot)
Expand All @@ -90,7 +100,7 @@ async def on_starting(event: hk.StartingEvent) -> None:
], # Keep using the cached response even if this param changes
timeout=3,
)
bot.d.timeup = datetime.datetime.now().astimezone()
bot.d.timeup = datetime.now().astimezone()
bot.d.chapter_info = {}
bot.d.update_channels = ["1127609035374461070"]
bot.d.con = sqlite3.connect("akane_db.db")
Expand All @@ -108,7 +118,7 @@ async def on_stopping(event: hk.StoppingEvent) -> None:

await bot.rest.create_message(
1129030476695343174,
f"Bot closed with {verbose_timedelta(datetime.datetime.now().astimezone()-bot.d.timeup)} uptime",
f"Bot closed with {verbose_timedelta(datetime.now().astimezone()-bot.d.timeup)} uptime",
)


Expand All @@ -122,7 +132,6 @@ async def ping(ctx: lb.Context) -> None:
ctx (lb.Context): The event context (irrelevant to the user)
"""
await ctx.respond(f"Pong! Latency: {bot.heartbeat_latency*1000:.2f}ms")
bot.d.ncom += 1


@bot.listen(lb.CommandErrorEvent)
Expand Down Expand Up @@ -151,7 +160,7 @@ async def on_error(event: lb.CommandErrorEvent) -> None:
elif isinstance(exception, lb.CommandIsOnCooldown):
await event.context.respond(
f"The command is on cooldown, you can use it after {int(exception.retry_after)}s",
delete_after=int(exception.retry_after),
delete_after=min(15, int(exception.retry_after)),
)

elif isinstance(exception, lb.MissingRequiredPermission):
Expand All @@ -164,58 +173,33 @@ async def on_error(event: lb.CommandErrorEvent) -> None:
await event.context.respond("I don't have the permissions to do this 😔")

elif isinstance(exception, lb.NotEnoughArguments):
# await event.context.respond(
# (
# f"Missing arguments, use `-help {event.context.command.name}`"
# f"for the correct invocation"
# )
# )\
try:
ctx = event.context
command = ctx.command

if command.hidden:
return

await ctx.respond("Missing arguments, initializing command help...")
await asyncio.sleep(0.3)

command = ctx.command
helper = BotHelpCommand(ctx.bot)

long_help = command.get_help(ctx)

if len(command.aliases) > 0:
aliases = f"Aliases: {', '.join(command.aliases)}\n\n"
else:
aliases = ""

# embed = (

# )
# lines = [
# ">>> ```adoc",
# "==== Command Help ====",
# f"{command.name} - {command.description}",
# "",
# f"Usage: {prefix}{command.signature}",
# "",
# long_help if long_help else "No additional details provided.",
# "```",
# ]
await ctx.edit_last_response(
content=None,
embed=hk.Embed(
color=0x000000,
title="Command Help",
description=(
f"**{command.name}** \n"
f"{command.description} \n\n"
f"Usage: `{ctx.prefix}{command.signature}` \n\n"
f"{aliases}"
f"{long_help or ''}"
),
),
)
await helper.send_command_help(ctx=ctx, command=command)

except Exception as e:
await event.context.respond(f"Stop, {e}")

elif isinstance(exception, lb.OnlyInGuild):
await event.context.respond("This command can't be invoked in DMs")

elif isinstance(exception, lb.ConverterFailure):
await event.context.respond(f"The argument `{exception.raw_value}` is invalid")

elif isinstance(exception, lb.CommandNotFound):
pass
# To move the fuzzy matching here


if __name__ == "__main__":
if os.name == "nt":
Expand Down
Loading

0 comments on commit e5d88c4

Please sign in to comment.