mirror of
https://github.com/Cog-Creators/Red-DiscordBot.git
synced 2025-11-22 18:57:59 -05:00
[Economy] Detect max balance and prevent OverflowError (#2211)
Resolves #2091. This doesn't fix every OverflowError with MongoDB; but at least the seemingly easiest one to achieve with core cogs. Signed-off-by: Toby Harradine <tobyharradine@gmail.com>
This commit is contained in:
@@ -4,9 +4,10 @@ from typing import Union, List, Optional
|
||||
|
||||
import discord
|
||||
|
||||
from redbot.core import Config
|
||||
from . import Config, errors
|
||||
|
||||
__all__ = [
|
||||
"MAX_BALANCE",
|
||||
"Account",
|
||||
"get_balance",
|
||||
"set_balance",
|
||||
@@ -26,6 +27,8 @@ __all__ = [
|
||||
"set_default_balance",
|
||||
]
|
||||
|
||||
MAX_BALANCE = 2 ** 63 - 1
|
||||
|
||||
_DEFAULT_GLOBAL = {
|
||||
"is_global": False,
|
||||
"bank_name": "Twentysix bank",
|
||||
@@ -170,10 +173,22 @@ async def set_balance(member: discord.Member, amount: int) -> int:
|
||||
------
|
||||
ValueError
|
||||
If attempting to set the balance to a negative number.
|
||||
BalanceTooHigh
|
||||
If attempting to set the balance to a value greater than
|
||||
``bank.MAX_BALANCE``
|
||||
|
||||
"""
|
||||
if amount < 0:
|
||||
raise ValueError("Not allowed to have negative balance.")
|
||||
if amount > MAX_BALANCE:
|
||||
currency = (
|
||||
await get_currency_name()
|
||||
if await is_global()
|
||||
else await get_currency_name(member.guild)
|
||||
)
|
||||
raise errors.BalanceTooHigh(
|
||||
user=member.display_name, max_balance=MAX_BALANCE, currency_name=currency
|
||||
)
|
||||
if await is_global():
|
||||
group = _conf.user(member)
|
||||
else:
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import importlib.machinery
|
||||
from typing import Optional
|
||||
|
||||
import discord
|
||||
|
||||
from .i18n import Translator
|
||||
|
||||
_ = Translator(__name__, __file__)
|
||||
|
||||
|
||||
class RedError(Exception):
|
||||
@@ -14,3 +21,24 @@ class PackageAlreadyLoaded(RedError):
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"There is already a package named {self.spec.name.split('.')[-1]} loaded"
|
||||
|
||||
|
||||
class BankError(RedError):
|
||||
"""Base error class for bank-related errors."""
|
||||
|
||||
|
||||
class BalanceTooHigh(BankError, OverflowError):
|
||||
"""Raised when trying to set a user's balance to higher than the maximum."""
|
||||
|
||||
def __init__(
|
||||
self, user: discord.abc.User, max_balance: int, currency_name: str, *args, **kwargs
|
||||
):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.user = user
|
||||
self.max_balance = max_balance
|
||||
self.currency_name = currency_name
|
||||
|
||||
def __str__(self) -> str:
|
||||
return _("{user}'s balance cannot rise above {max:,} {currency}.").format(
|
||||
user=self.user, max=self.max_balance, currency=self.currency_name
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user