Skip to content

Commit

Permalink
Added GuildContext for guild_only commands
Browse files Browse the repository at this point in the history
  • Loading branch information
nfearnley committed Jun 1, 2024
1 parent 0643ec8 commit 1e8a104
Show file tree
Hide file tree
Showing 36 changed files with 764 additions and 677 deletions.
8 changes: 4 additions & 4 deletions sizebot/cogs/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from discord.ext import commands

from sizebot.lib import userdb
from sizebot.lib.types import BotContext
from sizebot.lib.types import GuildContext

logger = logging.getLogger("sizebot")

Expand All @@ -19,7 +19,7 @@ def __init__(self, bot: commands.Bot):
hidden = True
)
@commands.is_owner()
async def halt(self, ctx: BotContext):
async def halt(self, ctx: GuildContext):
"""RIP SizeBot."""
logger.critical(f"Help, {ctx.author.display_name} is closing me!")
await ctx.send("Stopping SizeBot. ☠️")
Expand All @@ -29,7 +29,7 @@ async def halt(self, ctx: BotContext):
hidden = True
)
@commands.is_owner()
async def dump(self, ctx: BotContext, *, user: discord.Member = None):
async def dump(self, ctx: GuildContext, *, user: discord.Member = None):
"""Dump a user's data."""
if user is None:
user = ctx.author
Expand All @@ -40,7 +40,7 @@ async def dump(self, ctx: BotContext, *, user: discord.Member = None):
hidden = True
)
@commands.is_owner()
async def sudo(self, ctx: BotContext, victim: discord.Member, *, command: str):
async def sudo(self, ctx: GuildContext, victim: discord.Member, *, command: str):
"""Take control."""
logger.warn(f"{ctx.author.display_name} made {victim.display_name} run {command}.")
new_message = copy(ctx.message)
Expand Down
109 changes: 37 additions & 72 deletions sizebot/cogs/change.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import importlib.resources as pkg_resources
import logging
import random
from typing import cast
from typing import Self, cast
from sizebot.lib import errors, utils

from discord import Member
Expand All @@ -12,7 +12,7 @@
from sizebot.lib.diff import Diff, LimitedRate, Rate
from sizebot.lib.errors import ChangeMethodInvalidException
from sizebot.lib.objs import DigiObject, objects
from sizebot.lib.types import BotContext, StrToSend
from sizebot.lib.types import BotContext, GuildContext, StrToSend
from sizebot.lib.units import SV, Decimal

logger = logging.getLogger("sizebot")
Expand All @@ -28,15 +28,16 @@ async def on_first_ready(self):
# Don't start the change tasks until the bot is properly connected
self.changeTask.start()

def cog_unload(self):
def cog_unload(self): # type: ignore (Bad typing in discord.py)
self.changeTask.cancel()

@commands.command(
aliases = ["c"],
category = "change",
usage = "<change> [rate] [stop]"
)
async def change(self, ctx: BotContext, *, arg: LimitedRate | Rate | Diff | str):
@commands.guild_only()
async def change(self, ctx: GuildContext, *, arg: LimitedRate | Rate | Diff | str):
"""Either change or slow-change your height.
Can be used in essentially the three following ways:
Expand Down Expand Up @@ -66,7 +67,7 @@ async def change(self, ctx: BotContext, *, arg: LimitedRate | Rate | Diff | str)
elif style == "power":
userdata.scale = userdata.scale ** cast(Decimal, amount)
else:
raise ChangeMethodInvalidException
raise ChangeMethodInvalidException(style)
await nickmanager.nick_update(ctx.author)
userdb.save(userdata)
await ctx.send(f"{userdata.nickname} is now {userdata.height:m} ({userdata.height:u}) tall.")
Expand Down Expand Up @@ -96,7 +97,7 @@ async def changes(self, ctx: BotContext):
category = "change"
)
@commands.guild_only()
async def stopchange(self, ctx: BotContext):
async def stopchange(self, ctx: GuildContext):
"""Stop a currently active slow change."""
await ctx.send(**stop_changes(ctx.author))

Expand All @@ -105,16 +106,16 @@ async def stopchange(self, ctx: BotContext):
category = "change"
)
@commands.guild_only()
async def eatme(self, ctx: BotContext):
async def eatme(self, ctx: GuildContext):
"""Eat me!
Increases your height by a random amount between 2x and 20x."""
guildid = ctx.guild.id
userid = ctx.author.id

userdata = userdb.load(guildid, userid)
randmult = round(random.randint(2, 20), 1)
change_user(guildid, userid, "multiply", randmult)
randmult = Decimal(random.randint(2, 20))
change_user_mul(guildid, ctx.author.id, randmult)
await nickmanager.nick_update(ctx.author)
userdata = userdb.load(guildid, userid)

Expand All @@ -130,16 +131,16 @@ async def eatme(self, ctx: BotContext):
category = "change"
)
@commands.guild_only()
async def drinkme(self, ctx: BotContext):
async def drinkme(self, ctx: GuildContext):
"""Drink me!
Decreases your height by a random amount between 2x and 20x."""
guildid = ctx.guild.id
userid = ctx.author.id

userdata = userdb.load(guildid, userid)
randmult = round(random.randint(2, 20), 1)
change_user(guildid, ctx.author.id, "divide", randmult)
randmult = Decimal(random.randint(2, 20))
change_user_div(guildid, ctx.author.id, randmult)
await nickmanager.nick_update(ctx.author)
userdata = userdb.load(guildid, userid)

Expand All @@ -154,21 +155,21 @@ async def drinkme(self, ctx: BotContext):
category = "change"
)
@commands.guild_only()
async def pushme(self, ctx: BotContext):
async def pushme(self, ctx: GuildContext):
"""Push me!
Increases or decreases your height by a random amount between 2x and 20x."""
c = random.randint(1, 2)
if c == 1:
await ctx.invoke(self.bot.get_command("eatme"))
else:
await ctx.invoke(self.bot.get_command("drinkme"))
next_cmd_name = random.choice(["eatme", "drinkme"])
next_cmd = cast(commands.Command[Self, ..., None] | None, self.bot.get_command(next_cmd_name))
if next_cmd is None:
raise errors.ThisShouldNeverHappenException(f"Missing command: {next_cmd_name}")
await ctx.invoke(next_cmd)

@commands.command(
category = "change"
)
@commands.guild_only()
async def outgrow(self, ctx: BotContext, *, obj: DigiObject = None):
async def outgrow(self, ctx: GuildContext, *, obj: DigiObject | None = None):
"""Outgrows the next object in the object database, or an object you specify."""
guildid = ctx.guild.id
userid = ctx.author.id
Expand All @@ -186,7 +187,7 @@ async def outgrow(self, ctx: BotContext, *, obj: DigiObject = None):
return

random_factor = Decimal(random.randint(11, 20) / 10)
userdata.height = SV(obj.unitlength * random_factor)
userdata.height = obj.unitlength * random_factor
userdb.save(userdata)

await ctx.send(f"You outgrew {obj.article} **{obj.name}** *({obj.unitlength:,.3mu})* and are now **{userdata.height:,.3mu}** tall!")
Expand All @@ -195,7 +196,7 @@ async def outgrow(self, ctx: BotContext, *, obj: DigiObject = None):
category = "change"
)
@commands.guild_only()
async def outshrink(self, ctx: BotContext, *, obj: DigiObject = None):
async def outshrink(self, ctx: GuildContext, *, obj: DigiObject | None = None):
"""Outshrinks the next object in the object database or an object you specify."""
guildid = ctx.guild.id
userid = ctx.author.id
Expand All @@ -214,7 +215,7 @@ async def outshrink(self, ctx: BotContext, *, obj: DigiObject = None):
return

random_factor = Decimal(random.randint(11, 20) / 10)
userdata.height = SV(obj.unitlength / random_factor)
userdata.height = obj.unitlength / random_factor
userdb.save(userdata)

await ctx.send(f"You outshrunk {obj.article} **{obj.name}** *({obj.unitlength:,.3mu})* and are now **{userdata.height:,.3mu}** tall!")
Expand All @@ -230,59 +231,23 @@ async def changeTask(self):
logger.error(utils.format_traceback(e))


def change_user(guildid: int, userid: int, changestyle: str, amount: SV):
changestyle = changestyle.lower()
if changestyle in ["add", "+", "a", "plus"]:
changestyle = "add"
if changestyle in ["subtract", "sub", "-", "minus"]:
changestyle = "subtract"
if changestyle in ["power", "exp", "pow", "exponent", "^", "**"]:
changestyle = "power"
if changestyle in ["multiply", "mult", "m", "x", "times", "*"]:
changestyle = "multiply"
if changestyle in ["divide", "d", "/", "div"]:
changestyle = "divide"
if changestyle in ["percent", "per", "perc", "%"]:
changestyle = "percent"

if changestyle not in ["add", "subtract", "multiply", "divide", "power", "percent"]:
raise errors.ChangeMethodInvalidException(changestyle)

amountSV = None
amountVal = None
newamount = None

if changestyle in ["add", "subtract"]:
amountSV = SV.parse(amount)
elif changestyle in ["multiply", "divide", "power"]:
amountVal = Decimal(amount)
if amountVal == 1:
raise errors.ValueIsOneException
if amountVal == 0:
raise errors.ValueIsZeroException
elif changestyle in ["percent"]:
amountVal = Decimal(amount)
if amountVal == 0:
raise errors.ValueIsZeroException

def change_user_mul(guildid: int, userid: int, amount: Decimal):
if amount == 1:
raise errors.ValueIsOneException
if amount == 0:
raise errors.ValueIsZeroException
userdata = userdb.load(guildid, userid)
userdata.height = userdata.height * amount
userdb.save(userdata)

if changestyle == "add":
newamount = userdata.height + amountSV
elif changestyle == "subtract":
newamount = userdata.height - amountSV
elif changestyle == "multiply":
newamount = userdata.height * amountVal
elif changestyle == "divide":
newamount = userdata.height / amountVal
elif changestyle == "power":
userdata = userdata ** amountVal
elif changestyle == "percent":
newamount = userdata.height * (amountVal / 100)

if changestyle != "power":
userdata.height = newamount

def change_user_div(guildid: int, userid: int, amount: Decimal):
if amount == 1:
raise errors.ValueIsOneException
if amount == 0:
raise errors.ValueIsZeroException
userdata = userdb.load(guildid, userid)
userdata.height = userdata.height / amount
userdb.save(userdata)


Expand Down
20 changes: 13 additions & 7 deletions sizebot/cogs/edge.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from sizebot.lib import guilddb, userdb, nickmanager
from sizebot.lib.checks import is_mod
from sizebot.lib.types import BotContext
from sizebot.lib.types import GuildContext
from sizebot.lib.units import SV, Decimal

logger = logging.getLogger("sizebot")
Expand Down Expand Up @@ -60,7 +60,8 @@ def __init__(self, bot: commands.Bot):
hidden = True
)
@is_mod()
async def edges(self, ctx: BotContext):
@commands.guild_only()
async def edges(self, ctx: GuildContext):
"""See who is set to be the smallest and largest users."""
guilddata = guilddb.load_or_create(ctx.guild.id)
await ctx.send(f"**SERVER-SET SMALLEST AND LARGEST USERS:**\nSmallest: {'*Unset*' if guilddata.small_edge is None else guilddata.small_edge}\nLargest: {'*Unset*' if guilddata.large_edge is None else guilddata.large_edge}")
Expand All @@ -72,7 +73,8 @@ async def edges(self, ctx: BotContext):
category = "mod"
)
@is_mod()
async def setsmallest(self, ctx: BotContext, *, member: discord.Member):
@commands.guild_only()
async def setsmallest(self, ctx: GuildContext, *, member: discord.Member):
"""Set the smallest user."""
guilddata = guilddb.load_or_create(ctx.guild.id)
guilddata.small_edge = member.id
Expand All @@ -87,7 +89,8 @@ async def setsmallest(self, ctx: BotContext, *, member: discord.Member):
category = "mod"
)
@is_mod()
async def setlargest(self, ctx: BotContext, *, member: discord.Member):
@commands.guild_only()
async def setlargest(self, ctx: GuildContext, *, member: discord.Member):
"""Set the largest user."""
guilddata = guilddb.load_or_create(ctx.guild.id)
guilddata.large_edge = member.id
Expand All @@ -101,7 +104,8 @@ async def setlargest(self, ctx: BotContext, *, member: discord.Member):
category = "mod"
)
@is_mod()
async def clearsmallest(self, ctx: BotContext):
@commands.guild_only()
async def clearsmallest(self, ctx: GuildContext):
"""Clear the role of 'smallest user.'"""
guilddata = guilddb.load_or_create(ctx.guild.id)
guilddata.small_edge = None
Expand All @@ -115,7 +119,8 @@ async def clearsmallest(self, ctx: BotContext):
category = "mod"
)
@is_mod()
async def clearlargest(self, ctx: BotContext):
@commands.guild_only()
async def clearlargest(self, ctx: GuildContext):
"""Clear the role of 'largest user.'"""
guilddata = guilddb.load_or_create(ctx.guild.id)
guilddata.large_edge = None
Expand All @@ -128,7 +133,8 @@ async def clearlargest(self, ctx: BotContext):
category = "mod"
)
@is_mod()
async def edgedebug(self, ctx: BotContext):
@commands.guild_only()
async def edgedebug(self, ctx: GuildContext):
userdata = userdb.load(ctx.guild.id, ctx.author.id)
usersizes = getUserSizes(ctx.guild)
guilddata = guilddb.load(ctx.guild.id)
Expand Down
5 changes: 3 additions & 2 deletions sizebot/cogs/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from sizebot.lib import userdb
from sizebot.lib.constants import ids
from sizebot.lib.loglevels import EGG
from sizebot.lib.types import BotContext
from sizebot.lib.types import BotContext, GuildContext

tasks = {}

Expand All @@ -36,7 +36,8 @@ async def sbsay(self, ctx: BotContext, *, message: str):
aliases = ["tra"],
category = "fun"
)
async def report(self, ctx: BotContext, *, user: discord.User):
@commands.guild_only()
async def report(self, ctx: GuildContext, *, user: discord.User):
"""Report a user to the Tiny Rights Alliance."""
ud = userdb.load(ctx.guild.id, user.id)
ud.tra_reports += 1
Expand Down
2 changes: 1 addition & 1 deletion sizebot/cogs/holiday.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def __init__(self, bot: commands.Bot):
self.bot = bot
self.holidayTask.start()

def cog_unload(self):
def cog_unload(self): # type: ignore (Bad typing in discord.py)
self.holidayTask.cancel()

# TODO: CamelCase
Expand Down
Loading

0 comments on commit 1e8a104

Please sign in to comment.