Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
japandotorg committed Sep 24, 2023
2 parents 4b2aa7d + dd87ce3 commit 6f1f7fe
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 39 deletions.
8 changes: 4 additions & 4 deletions battleroyale/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
"{killed} perished under the hand of {killer}.",
"{killer} pulled the trigger, ended {killed}'s life",
"{killer} obliterated {killed} without hesitation.",
"{killer} inflicated a fatal blow upon {killed}.",
"{killer} inflicted a fatal blow upon {killed}.",
"{killed} succumbed to {killer}'s murderous ways.",
"{killed} fell victim to {killer}'s deadly plot.",
"{killer} brought about the demise of {killed} with precision.",
Expand All @@ -96,7 +96,7 @@
"{killed} met a horrifying end at the hands of {killer}.",
"{killer} unleashed unspeakable terror upon {killed}.",
"{killer} plunged {killed} into a world of eternal darkness.",
"{killed} becaome a mere puppet in {killer}'s twisted game of death.",
"{killed} became a mere puppet in {killer}'s twisted game of death.",
"{killer} revealed in the screams of agony as they extinguished {killed}'s life.",
"{killer} casted {killed} into a realm of overlasting torment and despair.",
"{killer} painted a macabre masterpiece with {killed}'s lifeblood as their brush.",
Expand All @@ -105,7 +105,7 @@
"{killer} carved a path of devastation, leaving {killed} in ruins.",
"{killer} tore through {killed} with savage ferocity, leaving a trail of devastation in their wake.",
"{killer} descended upon {killed} with ferocious intent, their wrath leaving a trail of devastation in its wake.",
"{killer} was caught in a deadly dance with {killer}, their fate sealed with each leathal movement.",
"{killer} was caught in a deadly dance with {killer}, their fate sealed with each lethal movement.",
"{killed} encountered {killer} in a battle of wills, their struggle culminating in a cataclysmic clash of life and death.",
]

Expand All @@ -124,7 +124,7 @@
"Winning is not everything, but the effort to win is. {winner} You did it!",
"You freaking did it {winner}! You won!",
"You are the winner {winner}! You are the best!",
"Ayoo {winne}, Victory has a hundred fathers, but defeat is an orphan.",
"Ayoo {winner}, Victory has a hundred fathers, but defeat is an orphan.",
"Yesterday I dared to struggle. Today I dare to win and you did it {winner}!",
"Why do I win every time? {winner} Because I'm the best, and everyone else sucks.",
"You are a winner {winner}! You are just a winner i swear, congrats!🏆",
Expand Down
101 changes: 66 additions & 35 deletions battleroyale/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@
import aiohttp
import discord
import prettytable as pt
from PIL import Image
from PIL import Image, UnidentifiedImageError
from redbot.core import Config, bank, commands
from redbot.core.bot import Red
from redbot.core.data_manager import bundled_data_path
from redbot.core.data_manager import bundled_data_path, cog_data_path
from redbot.core.utils.chat_formatting import box, humanize_list, pagify
from redbot.core.utils.views import SimpleMenu

Expand Down Expand Up @@ -71,6 +71,7 @@ def __init__(self, bot: Red) -> None:
self.games: Dict[discord.Message, Game] = {}

self.backgrounds_path: Path = bundled_data_path(self) / "backgrounds"
self.custom_backgrounds_path: Path = cog_data_path(self) / "backgrounds"
self.config: Config = Config.get_conf(self, identifier=14, force_registration=True)

self.log: logging.LoggerAdapter[logging.Logger] = logging.LoggerAdapter(
Expand Down Expand Up @@ -134,19 +135,34 @@ async def cog_load(self) -> None:
async def generate_image(
self, user_1: discord.Member, user_2: discord.Member, to_file: bool = True
) -> Union[discord.File, Image.Image]:
backgrounds = os.listdir(self.backgrounds_path)
background = random.choice(backgrounds)
with open(self.backgrounds_path / background, mode="rb") as f:
background_bytes = f.read()
img = Image.open(BytesIO(background_bytes))
backgrounds = [
self.backgrounds_path / background for background in os.listdir(self.backgrounds_path)
]
if self.custom_backgrounds_path.exists():
backgrounds.extend(
[
self.custom_backgrounds_path / background
for background in os.listdir(self.custom_backgrounds_path)
]
)
while True:
background = random.choice(backgrounds)
with open(background, mode="rb") as f:
background_bytes = f.read()
try:
img = Image.open(BytesIO(background_bytes))
except UnidentifiedImageError:
continue
else:
break
img = img.convert("RGBA")
avatar_1 = Image.open(BytesIO(await self._get_content_from_url(user_1.display_avatar.url)))
avatar_1 = Image.open(BytesIO(await user_1.display_avatar.read()))
avatar_1 = avatar_1.resize((400, 400))
img.paste(
avatar_1,
((0 + 30), (int(img.height / 2) - 200), (0 + 30 + 400), (int(img.height / 2) + 200)),
)
avatar_2 = Image.open(BytesIO(await self._get_content_from_url(user_2.display_avatar.url)))
avatar_2 = Image.open(BytesIO(await user_2.display_avatar.read()))
avatar_2 = avatar_2.resize((400, 400))
img.paste(
avatar_2,
Expand Down Expand Up @@ -203,8 +219,8 @@ async def _get_background_path(self, ctx: commands.Context):
"""
Get folder path for this cog's default backgrounds.
"""
path: str = os.path.join(self.backgrounds_path)
await ctx.send(f"Your default background folder path is:\n- `{path}`")
path: str = os.path.join(self.custom_backgrounds_path)
await ctx.send(f"Your default custom backgrounds folder path is:\n- `{path}`")

@commands.is_owner()
@setbattleroyale.command(name="addbackground", aliases=["ab"])
Expand Down Expand Up @@ -237,7 +253,7 @@ async def _add_background(
raise commands.UserFeedbackCheckFailure("I was unable to get the file from Discord.")
if preferred_filename:
filename = f"{preferred_filename}.{ext}"
filepath = os.path.join(self.backgrounds_path, filename)
filepath = os.path.join(self.custom_backgrounds_path, filename)
with open(filepath, "wb") as f:
f.write(bytes_file)
await ctx.send(f"Your custom background has been saved as `{filename}`.")
Expand All @@ -248,8 +264,12 @@ async def _remove_background(self, ctx: commands.Context, filename: str):
"""
Remove a background from the cog's backgrounds folder.
"""
path = os.path.join(self.backgrounds_path)
for f in os.listdir(path):
path = self.custom_backgrounds_path
if not path.exists() or not (custom_backgrounds := os.listdir(path)):
raise commands.UserFeedbackCheckFailure(
"I could not find any background images with that name."
)
for f in custom_backgrounds:
if filename.lower() in f.lower():
break
else:
Expand All @@ -263,6 +283,24 @@ async def _remove_background(self, ctx: commands.Context, filename: str):
await ctx.send(f"Could not delete file: {str(exc)}.")
await ctx.send(f"Backgorund `{f}` been removed.")

@commands.is_owner()
@setbattleroyale.command(name="listbackgrounds")
async def _list_backgrounds(self, ctx: commands.Context):
"""
List your cog's custom backgrounds.
"""
path = self.custom_backgrounds_path
if not path.exists() or not (custom_backgrounds := os.listdir(path)):
raise commands.UserFeedbackCheckFailure("You don't have any custom background images.")
await SimpleMenu(
pages=[
box(page, lang="py")
for page in pagify(
"\n".join(f"- {custom_background}" for custom_background in custom_backgrounds)
)
]
).start(ctx)

@bank.is_owner_if_bank_global()
@setbattleroyale.command(name="prize")
async def _prize(self, ctx: commands.Context, amount: commands.Range[int, 10, 2**30]):
Expand All @@ -273,7 +311,7 @@ async def _prize(self, ctx: commands.Context, amount: commands.Range[int, 10, 2*

@commands.is_owner()
@setbattleroyale.command(name="emoji")
async def _emoji(self, ctx: commands.Context, emoji: EmojiConverter):
async def _emoji(self, ctx: commands.Context, emoji: EmojiConverter = None):
"""
Set an emoji to be used with Battle Royale.
"""
Expand Down Expand Up @@ -325,9 +363,10 @@ async def _settings(self, ctx: commands.Context):
await ctx.send(embed=embed)

@commands.guild_only()
@commands.dynamic_cooldown(_cooldown, commands.BucketType.guild)
@commands.max_concurrency(1, commands.BucketType.channel)
@commands.bot_has_permissions(embed_links=True)
@commands.group(aliases=["br"], invoke_without_command=True)
@commands.dynamic_cooldown(_cooldown, commands.BucketType.guild)
async def battleroyale(
self, ctx: commands.Context, delay: commands.Range[int, 10, 20] = 10, skip: bool = False
):
Expand Down Expand Up @@ -365,10 +404,7 @@ async def battleroyale(

game: Game = Game(cog=self, delay=delay, skip=skip)
self.games[join_view._message] = game
try:
await game.start(ctx, players=players, original_message=join_view._message)
except Exception as e:
self.log.exception("Something went wrong while starting the game.", exc_info=True)
await game.start(ctx, players=players, original_message=join_view._message)

@battleroyale.command()
async def auto(
Expand All @@ -388,10 +424,13 @@ async def auto(
- `delay`: min 10, max 20.
- `skip`: will skip to results.
"""
users: List[discord.Member] = random.sample(list(ctx.guild.members), players - 1)
player: List[discord.Member] = list(filter(lambda u: not u.bot, users))
if ctx.author not in player:
player.append(ctx.author)
guild_members = list(ctx.guild.members)
users: List[discord.Member] = random.sample(
guild_members, min(players - 1, len(guild_members))
)
players: List[discord.Member] = list(filter(lambda u: not u.bot, users))
if ctx.author not in players:
players.append(ctx.author)
game: Game = Game(cog=self, delay=delay, skip=skip)
embed: discord.Embed = discord.Embed(
title="Battle Royale",
Expand All @@ -401,10 +440,7 @@ async def auto(
embed.set_thumbnail(url=SWORDS)
message = await ctx.send(embed=embed)
self.games[message] = game
try:
await game.start(ctx, players=player, original_message=message)
except Exception as e:
self.log.exception("Something went wrong while starting the game.", exc_info=True)
await game.start(ctx, players=players, original_message=message)

@battleroyale.command()
async def role(
Expand Down Expand Up @@ -434,9 +470,7 @@ async def role(
).set_thumbnail(url=SWORDS)
)
return
users: List[discord.Member] = []
for member in role.members:
users.append(member)
users: List[discord.Member] = list(role.members)
players: List[discord.Member] = list(filter(lambda u: not u.bot, users))
if ctx.author not in players:
players.append(ctx.author)
Expand All @@ -457,10 +491,7 @@ async def role(
embed.set_thumbnail(url=SWORDS)
message = await ctx.send(embed=embed)
self.games[message] = game
try:
await game.start(ctx, players=players, original_message=message)
except Exception as e:
self.log.exception("Something went wrong while starting the game.", exc_info=True)
await game.start(ctx, players=players, original_message=message)

@battleroyale.command(name="profile", aliases=["stats"])
async def profile(self, ctx: commands.Context, *, user: Optional[discord.Member] = None):
Expand Down

0 comments on commit 6f1f7fe

Please sign in to comment.