Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a currency along with various uses #296

Open
wants to merge 33 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
de1ab70
Initial work on coins
flaree Jun 27, 2024
ec7b71d
add back return
flaree Jun 27, 2024
3c2d869
Add coin trade feature and admin panel coin addition
MaxxMXSZ Jun 30, 2024
56d7b0e
Revert "Add coin trade feature and admin panel coin addition"
MaxxMXSZ Jun 30, 2024
c25a36a
hhh
MaxxMXSZ Jul 1, 2024
ba3cb9a
yippie
MaxxMXSZ Jul 1, 2024
d0398de
comma
MaxxMXSZ Jul 1, 2024
710c995
mcchicken
MaxxMXSZ Jul 1, 2024
2c320a7
quick fixes
MaxxMXSZ Jul 2, 2024
4650679
sorry was trying something else forgot to remove
MaxxMXSZ Jul 2, 2024
fb28805
Merge pull request #5 from MaxxMXSZ/coin
flaree Jul 23, 2024
c112f22
add coins to trade - draft
flaree Jul 30, 2024
6e48da8
Added a way to add or remove coins from a user
MaxxMXSZ Aug 21, 2024
374a8ad
Kowlin requested update
MaxxMXSZ Sep 13, 2024
e412be0
add false deleted stuff back
MaxxMXSZ Sep 13, 2024
ebc4fad
Merge pull request #6 from flaree/Coins2.0
MaxxMXSZ Sep 14, 2024
856287a
admin: fixed coins command logic
laggron42 Oct 15, 2024
12163dc
history: fix coin display
laggron42 Oct 15, 2024
710120e
change line endings
laggron42 Oct 15, 2024
1aaca24
Merge branch 'master' into feat/coins
laggron42 Oct 15, 2024
0f4bfb7
migrations: regenerate
laggron42 Oct 15, 2024
e5663ea
Update ballsdex/packages/balls/cog.py
MaxxMXSZ Oct 27, 2024
b75d286
Update ballsdex/packages/balls/cog.py
MaxxMXSZ Oct 27, 2024
ab3f5d3
Update ballsdex/packages/trade/cog.py
MaxxMXSZ Oct 27, 2024
f432b4e
Update ballsdex/packages/trade/cog.py
MaxxMXSZ Oct 27, 2024
9a421ad
Update ballsdex/settings.py
MaxxMXSZ Oct 27, 2024
e076313
Update ballsdex/settings.py
MaxxMXSZ Oct 27, 2024
6c3fe13
Bug fixes regarding display, settings and trade's cog.py
MaxxMXSZ Oct 27, 2024
f40926d
Bug fixes regardings display and changes to trade's cog.py and settings
MaxxMXSZ Oct 27, 2024
91c0b06
Merge branch 'master' into feat/coins
laggron42 Oct 28, 2024
f3deb78
Merge branch 'master' into feat/coins
laggron42 Dec 17, 2024
1034f6d
Apply suggestions from code review
laggron42 Dec 17, 2024
84b80ab
oopsie during merge
laggron42 Dec 17, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ballsdex/core/admin/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ class PlayerResource(Model):
"balls",
"donation_policy",
"privacy_policy",
"coins",
]


Expand Down
35 changes: 35 additions & 0 deletions ballsdex/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
from tortoise.expressions import Q

from ballsdex.core.image_generator.image_gen import draw_card
from ballsdex.core.utils.enums import RarityTiers
from ballsdex.settings import settings

if TYPE_CHECKING:
from tortoise.backends.base.client import BaseDBAsyncClient
Expand Down Expand Up @@ -199,6 +201,26 @@ def cached_regime(self) -> Regime:
def cached_economy(self) -> Economy | None:
return economies.get(self.economy_id, self.economy)

@property
def rarity_tier(self) -> RarityTiers:
rarity_scale = settings.rarities
if self.rarity <= rarity_scale["legendary"]["rarity"]:
return RarityTiers.legendary
elif self.rarity <= rarity_scale["epic"]["rarity"]:
return RarityTiers.epic
elif self.rarity <= rarity_scale["rare"]["rarity"]:
return RarityTiers.rare
elif self.rarity <= rarity_scale["uncommon"]["rarity"]:
return RarityTiers.uncommon
else:
return RarityTiers.common

@property
def coin_amount(self) -> int:
rarity_scale = settings.rarities
ball_rarity = self.rarity_tier
return rarity_scale[ball_rarity.name].get("coins", 0)


Ball.register_listener(signals.Signals.pre_save, lower_catch_names)
Ball.register_listener(signals.Signals.pre_save, lower_translations)
Expand Down Expand Up @@ -424,6 +446,7 @@ class Player(models.Model):
discord_id = fields.BigIntField(
description="Discord user ID", unique=True, validators=[DiscordSnowflakeValidator()]
)
coins = fields.IntField(default=0)
donation_policy = fields.IntEnumField(
DonationPolicy,
description="How you want to handle donations",
Expand All @@ -449,6 +472,16 @@ class Player(models.Model):
def __str__(self) -> str:
return str(self.discord_id)

async def add_coins(self, amount: int):
self.coins += amount
await self.save(update_fields=("coins",))

async def remove_coins(self, amount: int):
if self.coins < amount:
raise ValueError("Not enough coins")
self.coins -= amount
await self.save(update_fields=("coins",))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add_coins and remove_coins should probably return some output on its status as confirmation.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think raising an error is appropriate as a way to confirm things went well


async def is_friend(self, other_player: "Player") -> bool:
return await Friendship.filter(
(Q(player1=self) & Q(player2=other_player))
Expand Down Expand Up @@ -515,6 +548,8 @@ class Trade(models.Model):
)
date = fields.DatetimeField(auto_now_add=True)
tradeobjects: fields.ReverseRelation[TradeObject]
player1_coins = fields.IntField(default=0)
player2_coins = fields.IntField(default=0)

def __str__(self) -> str:
return str(self.pk)
Expand Down
9 changes: 9 additions & 0 deletions ballsdex/core/utils/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@

PRIVATE_POLICY_MAP = {1: "Public", 2: "Private", 3: "Mutual Servers", 4: "Friends"}


class RarityTiers(enum.Enum):
legendary = "Legendary"
epic = "Epic"
rare = "Rare"
uncommon = "Uncommon"
common = "Common"


MENTION_POLICY_MAP = {1: "Allow all mentions", 2: "Deny all mentions"}

FRIEND_POLICY_MAP = {1: "Allow all friend requests", 2: "Deny all friend requests"}
Expand Down
123 changes: 123 additions & 0 deletions ballsdex/packages/admin/cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ def __init__(self, bot: "BallsDexBot"):
logs = app_commands.Group(name="logs", description="Bot logs management")
history = app_commands.Group(name="history", description="Trade history management")
info = app_commands.Group(name="info", description="Information Commands")
coins = app_commands.Group(name=settings.currency_name, description="Coins management")

@app_commands.command()
@app_commands.checks.has_any_role(*settings.root_role_ids)
Expand Down Expand Up @@ -1552,3 +1553,125 @@ async def user(
)
embed.set_thumbnail(url=user.display_avatar) # type: ignore
await interaction.followup.send(embed=embed, ephemeral=True)

@coins.command()
@app_commands.checks.has_any_role(*settings.root_role_ids)
async def add(
self,
interaction: discord.Interaction,
user: discord.User | None = None,
user_id: str | None = None,
amount: int = 0,
Comment on lines +1562 to +1564
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

amount should be a required parameter

Suggested change
user: discord.User | None = None,
user_id: str | None = None,
amount: int = 0,
amount: int,
user: discord.User | None = None,
user_id: str | None = None,

):
"""
Add coins to a user.

Parameters
----------
user: discord.User | None
The user you want to add coins to.
user_id: str | None
The ID of the user you want to add coins to.
amount: int
The number of coins to add.
"""
if (user is None and user_id is None) or (user is not None and user_id is not None):
await interaction.response.send_message(
"You must provide either `user` or `user_id`", ephemeral=True
)
return

if amount < 0:
await interaction.response.send_message(
f"The amount of {settings.currency_name} " "to add cannot be negative.",
ephemeral=True,
)
return

if user_id is not None:
try:
user = await self.bot.fetch_user(int(user_id))
except ValueError:
await interaction.response.send_message(
"The user ID you provided is not valid.", ephemeral=True
)
return
except discord.NotFound:
await interaction.response.send_message(
"The given user ID could not be found.", ephemeral=True
)
return

assert user
player, created = await Player.get_or_create(discord_id=user.id)
await player.add_coins(amount)
await interaction.response.send_message(
f"Added {amount} {settings.currency_name} to {user.name}.", ephemeral=True
)

await log_action(
f"{interaction.user} added {amount} {settings.currency_name} "
f"to {user.name} ({user.id}).",
self.bot,
)

@coins.command()
@app_commands.checks.has_any_role(*settings.root_role_ids)
async def remove(
self,
interaction: discord.Interaction,
user: discord.User | None = None,
user_id: str | None = None,
amount: int = 0,
Comment on lines +1623 to +1625
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Suggested change
user: discord.User | None = None,
user_id: str | None = None,
amount: int = 0,
amount: int,
user: discord.User | None = None,
user_id: str | None = None,

):
"""
Remove coins from a user.

Parameters
----------
user: discord.User | None
The user you want to remove coins from.
user_id: str | None
The ID of the user you want to remove coins from.
amount: int
The number of coins to remove.
"""
if (user is None and user_id is None) or (user is not None and user_id is not None):
await interaction.response.send_message(
"You must provide either `user` or `user_id`", ephemeral=True
)
return

if amount < 0:
await interaction.response.send_message(
f"The amount of {settings.currency_name} " "to remove cannot be negative.",
ephemeral=True,
)
return

if user_id is not None:
try:
user = await self.bot.fetch_user(int(user_id))
except ValueError:
await interaction.response.send_message(
"The user ID you provided is not valid.", ephemeral=True
)
return
except discord.NotFound:
await interaction.response.send_message(
"The given user ID could not be found.", ephemeral=True
)
return

assert user
player, created = await Player.get_or_create(discord_id=user.id)
await player.remove_coins(amount)
await interaction.response.send_message(
f"Removed {amount} {settings.currency_name} to {user.name}.", ephemeral=True
)

await log_action(
f"{interaction.user} removed {amount} {settings.currency_name} "
f"to {user.name} ({user.id}).",
self.bot,
)
38 changes: 38 additions & 0 deletions ballsdex/packages/balls/cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -660,3 +660,41 @@ async def count(
f"You have {balls} {special_str}{shiny_str}"
f"{country}{settings.collectible_name}{plural}{guild}."
)

@app_commands.command()
async def dispose(self, interaction: discord.Interaction, ball: BallInstanceTransform):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if dispose is the best naming for this command, it seems a bit negative. perhaps exchange

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dispose sounds fine to me, exchange may be confused with trading. What about sell maybe?

"""Dispose a countryball for coins.

Parameters
----------
ball: BallInstance
The countryball you want to dispose of."""
if not ball:
return
if not ball.countryball.enabled or not ball.is_tradeable:
await interaction.response.send_message(
f"You cannot dispose of this {settings.collectible_name}.", ephemeral=True
)
return
await interaction.response.defer()
coins = ball.countryball.coin_amount // 2
view = ConfirmChoiceView(interaction)
await interaction.followup.send(
f"Are you sure you want to dispose of the {settings.collectible_name} "
f"{ball.description(include_emoji=True, bot=self.bot)} "
f"for {coins} {settings.currency_name}?",
view=view,
ephemeral=True,
)
await view.wait()
if not view.value:
return
player = await Player.get(discord_id=interaction.user.id)
await player.add_coins(coins)
message = (
f"You disposed of the {settings.collectible_name} "
f"{ball.description(include_emoji=True, bot=self.bot)} "
f"for {coins} {settings.currency_name}."
)
await ball.delete()
await interaction.followup.send(message)
2 changes: 2 additions & 0 deletions ballsdex/packages/countryballs/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@ async def catch_ball(
server_id=user.guild.id,
spawned_time=self.ball.time,
)
coins = self.ball.model.coin_amount
await player.add_coins(coins)
if user.id in bot.catch_log:
log.info(
f"{user} caught {settings.collectible_name}"
Expand Down
10 changes: 10 additions & 0 deletions ballsdex/packages/players/cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ def __init__(self, bot: "BallsDexBot"):
if privacy_command:
privacy_command.parameters[0]._Parameter__parent.choices.pop() # type: ignore

@app_commands.command()
async def balance(self, interaction: discord.Interaction):
"""
Check your balance.
"""
player, _ = await PlayerModel.get_or_create(discord_id=interaction.user.id)
await interaction.response.send_message(
f"You have {player.coins} {settings.currency_name}.", ephemeral=True
)

friend = app_commands.Group(name="friend", description="Friend commands")
blocked = app_commands.Group(name="block", description="Block commands")
policy = app_commands.Group(name="policy", description="Policy commands")
Expand Down
Loading
Loading