Skip to content
This repository has been archived by the owner on May 6, 2024. It is now read-only.

Commit

Permalink
Include maps n config
Browse files Browse the repository at this point in the history
  • Loading branch information
thboss committed Sep 2, 2023
1 parent 100fef2 commit 29bdeb0
Show file tree
Hide file tree
Showing 13 changed files with 96 additions and 316 deletions.
2 changes: 0 additions & 2 deletions bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ async def on_ready(self) -> None:
await db.sync_guilds([g.id for g in self.guilds])
for guild in self.guilds:
try:
await db.create_default_guild_maps(guild)
await self.check_guild_requirements(guild)
except: pass

Expand All @@ -106,7 +105,6 @@ async def on_ready(self) -> None:
async def on_guild_join(self, guild) -> None:
""""""
await db.sync_guilds([g.id for g in self.guilds])
await db.create_default_guild_maps(guild)
await self.check_guild_requirements(guild)

@commands.Cog.listener()
Expand Down
91 changes: 17 additions & 74 deletions bot/cogs/lobby.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import asyncio

from discord.ext import commands
from discord import app_commands, Interaction, Embed, Member, VoiceState, HTTPException, VoiceChannel, SelectOption
from discord import app_commands, Interaction, Embed, Member, VoiceState, HTTPException, SelectOption

from bot.helpers.db import db
from bot.helpers.api import api
Expand All @@ -15,6 +15,7 @@
from bot.views import ReadyView, DropDownView
from bot.bot import G5Bot
from bot.helpers.utils import COUNTRY_FLAGS
from bot.helpers.configs import Config


CAPACITY_CHOICES = [
Expand Down Expand Up @@ -151,10 +152,10 @@ async def create_lobby(

await category.edit(name=f"Lobby #{lobby_id}")

guild_maps = await db.get_guild_maps(guild, game_mode.value)
lobby_model = await db.get_lobby_by_id(lobby_id, self.bot)
await db.insert_lobby_maps(lobby_id, guild_maps[:7])
all_maps = list(Config.maps[game_mode.value].keys())
await db.insert_lobby_maps(lobby_id, all_maps[:7])

lobby_model = await db.get_lobby_by_id(lobby_id, self.bot)
await self.update_queue_msg(lobby_model)

embed = Embed(
Expand Down Expand Up @@ -233,7 +234,7 @@ async def empty_lobby(self, interaction: Interaction, lobby_id: int):
embed = Embed(description=f"Lobby #{lobby_model.id} has been emptied.")
await interaction.followup.send(embed=embed, ephemeral=True)

@app_commands.command(name='edit-map-pool', description='Modify map pool')
@app_commands.command(name='map-pool', description='Modify map pool')
@app_commands.describe(lobby_id="Lobby ID.")
@app_commands.checks.has_permissions(administrator=True)
async def mpool(self, interaction: Interaction, lobby_id: int):
Expand All @@ -247,17 +248,18 @@ async def mpool(self, interaction: Interaction, lobby_id: int):
if not lobby_model or lobby_model.guild.id != guild.id:
raise CustomError("Invalid Lobby ID")

guild_maps = await db.get_guild_maps(guild, lobby_model.game_mode)
all_maps = Config.maps[lobby_model.game_mode]
lobby_maps = await db.get_lobby_maps(lobby_id)

placeholder = "Select maps from the list"
options = [
SelectOption(
label=map_model.display_name,
value=map_model.map_id,
default=map_model in lobby_maps
) for map_model in guild_maps
label=display_name,
value=map_name,
default=map_name in lobby_maps
) for map_name, display_name in all_maps.items()
]
max_maps = len(guild_maps) if lobby_model.series == "bo1" else 7
max_maps = len(all_maps) if lobby_model.series == "bo1" else 7
dropdown = DropDownView(user, placeholder, options, 7, max_maps)
message = await interaction.followup.send(view=dropdown, wait=True)
await dropdown.wait()
Expand All @@ -267,72 +269,13 @@ async def mpool(self, interaction: Interaction, lobby_id: int):
await message.edit(embed=embed, view=None)
return

active_maps = list(filter(lambda x: str(x.map_id) in dropdown.selected_options, guild_maps))
active_maps = list(filter(lambda x: x in dropdown.selected_options, all_maps.keys()))
await db.update_lobby_maps(lobby_id, active_maps, lobby_maps)

embed.description = f"Map pool for lobby **#{lobby_id}** updated successfully."
embed.add_field(name="Active Maps", value='\n'.join(m.display_name for m in active_maps))
embed.add_field(name="Active Maps", value='\n'.join(Config.maps[lobby_model.game_mode][m] for m in active_maps))
await message.edit(embed=embed, view=None)

@app_commands.command(name="add-map", description="Add a custom map")
@app_commands.describe(
display_name="Display map name. e.g. Dust II",
dev_name="Map name in CS:GO. e.g. de_dust2",
)
@app_commands.choices(game_mode=GAME_MODE_CHOICES)
@app_commands.checks.has_permissions(administrator=True)
async def add_custom_map(
self,
interaction: Interaction,
display_name: str,
dev_name: str,
game_mode: app_commands.Choice[str]
):
""""""
await interaction.response.defer(ephemeral=True)
embed = Embed()
guild_maps = await db.get_guild_maps(interaction.guild, game_mode.value)
count_maps = len(guild_maps)

if count_maps == 23:
raise CustomError("You have 23 maps, you cannot add more!")

map_added = await db.create_custom_guild_map(
interaction.guild, display_name, dev_name, game_mode.value
)

if map_added:
embed.description = f"Map **{display_name}** added successfully `{count_maps + 1}/23`"
else:
embed.description = f"Map **{display_name}** already exists `{count_maps}/23`"

await interaction.followup.send(embed=embed, ephemeral=True)

@app_commands.command(name='remove-map', description='Remove a custom map')
@app_commands.describe(dev_name='Map name in CS:GO. e.g. de_dust2')
@app_commands.choices(game_mode=GAME_MODE_CHOICES)
@app_commands.checks.has_permissions(administrator=True)
async def remove_custom_map(
self,
interaction: Interaction,
dev_name: str,
game_mode: app_commands.Choice[str]
):
""""""
await interaction.response.defer(ephemeral=True)
guild_maps = await db.get_guild_maps(interaction.guild, game_mode.value)
count_maps = len(guild_maps)
guild_maps = list(filter(lambda x: x.dev_name == dev_name, guild_maps))

if not guild_maps:
raise CustomError("Map not exist!")

await db.delete_guild_maps(interaction.guild, guild_maps, game_mode.value)

description = f'Map removed successfully `{count_maps-1}/23`'
embed = Embed(description=description)
await interaction.followup.send(embed=embed, ephemeral=True)

@app_commands.command(name="add-spectator", description="Add a user to the matches")
@app_commands.checks.has_permissions(administrator=True)
async def add_spectator(self, interaction: Interaction, user: Member):
Expand Down Expand Up @@ -444,7 +387,7 @@ async def _join(self, user: Member, lobby_model: LobbyModel):
if unreadied_users:
awaitables = [u.move_to(guild_model.prematch_channel) for u in unreadied_users]
awaitables.append(db.delete_lobby_users(lobby_model.id, unreadied_users))
await asyncio.gather(*awaitables)
await asyncio.gather(*awaitables, return_exceptions=True)
else:
embed = Embed(description='Starting match setup...')
setup_match_msg = await lobby_model.text_channel.send(embed=embed)
Expand All @@ -466,7 +409,7 @@ async def _join(self, user: Member, lobby_model: LobbyModel):
)
if not match_started:
awaitables = [u.move_to(guild_model.prematch_channel) for u in queued_users]
await asyncio.gather(*awaitables)
await asyncio.gather(*awaitables, return_exceptions=True)

await db.clear_lobby_users(lobby_model.id)
self.in_progress[lobby_model.id] = False
Expand Down
53 changes: 24 additions & 29 deletions bot/cogs/match.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# match.py

from discord.ext import commands, tasks
from discord.errors import HTTPException, NotFound
from discord.errors import HTTPException
from discord import Embed, app_commands, Member, Message, Interaction, Guild, SelectOption, Role, PermissionOverwrite
from typing import Literal, List, Optional

Expand All @@ -11,7 +11,7 @@

from bot.helpers.api import api, Match, MapStat, Server, Season
from bot.helpers.db import db
from bot.helpers.models import GuildModel, TeamModel, MatchModel, MapModel
from bot.helpers.models import GuildModel, TeamModel, MatchModel
from bot.bot import G5Bot
from bot.helpers.errors import CustomError, APIError
from bot.helpers.configs import Config
Expand Down Expand Up @@ -47,11 +47,17 @@ async def select_team_participants(self, team_model: TeamModel, capacity: int, i

return list(filter(lambda x: str(x.id) in dropdown.selected_options, team_users))

async def select_mpool(self, user: Member, guild_maps: List[MapModel], series: str, interaction: Interaction) -> List[MapModel]:
async def select_mpool(self, user: Member, game_mode: str, series: str, interaction: Interaction) -> List[str]:
""""""
placeholder = "Select map pool"
options = [SelectOption(label=m.display_name, value=m.map_id) for m in guild_maps]
max_maps = len(guild_maps) if series == "bo1" else 7
all_maps = Config.maps[game_mode]
options = [
SelectOption(
label=display_name,
value=map_name
) for map_name, display_name in all_maps.items()
]
max_maps = len(all_maps) if series == "bo1" else 7
dropdown = DropDownView(user, placeholder, options, 7, max_maps)
await interaction.edit_original_response(content=user.mention, view=dropdown)
await self.bot.notify(user, channel=interaction.channel)
Expand All @@ -60,7 +66,7 @@ async def select_mpool(self, user: Member, guild_maps: List[MapModel], series: s
if not dropdown.selected_options:
raise CustomError("Timeout! You haven't selected maps in time!")

return list(filter(lambda x: str(x.map_id) in dropdown.selected_options, guild_maps))
return list(filter(lambda x: x in dropdown.selected_options, all_maps.keys()))

async def setup_teams_match(
self,
Expand All @@ -71,18 +77,17 @@ async def setup_teams_match(
series: Literal["bo1", "bo2", "bo3"],
game_mode: Literal["competitive", "wingman"],
author: Member,
guild_maps: List[MapModel],
season_id: int=None
):
""""""
embed = Embed()
map_pool = await self.select_mpool(author, guild_maps, series, interaction)
map_pool = await self.select_mpool(author, game_mode, series, interaction)
team1_users = await self.select_team_participants(team1_model, capacity, interaction)
team2_users = await self.select_team_participants(team2_model, capacity, interaction)

embed.add_field(name=f"Team {team1_model.name}", value="\n".join(u.mention for u in team1_users))
embed.add_field(name=f"Team {team2_model.name}", value="\n".join(u.mention for u in team2_users))
embed.add_field(name="Map Pool", value="\n".join(m.display_name for m in map_pool))
embed.add_field(name="Map Pool", value="\n".join(Config.maps[game_mode][m] for m in map_pool))
message = await interaction.edit_original_response(embed=embed, view=None)
await asyncio.sleep(3)

Expand Down Expand Up @@ -143,7 +148,6 @@ async def create_match(
""""""
await interaction.response.defer()
user = interaction.user
guild = interaction.guild
team_capacity = int(capacity.value // 2)

team1_model = await db.get_team_by_role(team1, self.bot)
Expand All @@ -158,10 +162,6 @@ async def create_match(
season = await api.get_season(season_id)
if not season:
raise CustomError(f"Season #{season_id} not found.")

guild_maps = await db.get_guild_maps(guild, game_mode.value)
if len(guild_maps) < 7:
raise CustomError("No maps found in the server. Please use command `/add-map` to add **at least 7** maps.")

await self.setup_teams_match(
team1_model,
Expand All @@ -171,7 +171,6 @@ async def create_match(
series.value,
game_mode.value,
user,
guild_maps,
season_id
)

Expand Down Expand Up @@ -215,10 +214,6 @@ async def challenge(
if team1_model.id == team2_model.id:
raise CustomError("Opps! You can't challenge your team.")

guild_maps = await db.get_guild_maps(guild, game_mode.value)
if len(guild_maps) < 7:
raise CustomError("No maps found in the server.")

embed.description = f"Team **{team1_model.name}** wants to challenge your team **{team2_model.name}**"
confirm = ConfirmView(team2_model.captain)
await interaction.edit_original_response(content=team2_model.captain.mention, embed=embed, view=confirm)
Expand All @@ -238,8 +233,7 @@ async def challenge(
interaction,
series.value,
game_mode.value,
user,
guild_maps
user
)

@app_commands.command(name="cancel-match", description="Cancel a live match")
Expand Down Expand Up @@ -588,7 +582,7 @@ async def start_match(
self,
guild: Guild,
message: Message,
mpool: List[MapModel],
mpool: List[str],
game_mode: str='competitive',
queue_users: List[Member]=[],
team_method: str='captains',
Expand Down Expand Up @@ -643,19 +637,20 @@ async def start_match(
team2_id = await api.create_team(team2_name, dict_team2_users)

if map_method == 'veto':
veto_view = VetoView(message, mpool, series, team1_captain, team2_captain)
veto_view = VetoView(message, mpool, series, team1_captain, team2_captain, game_mode)
await message.edit(embed=veto_view.embed_veto(), view=veto_view)
await veto_view.wait()
if not veto_view.is_veto_done:
raise asyncio.TimeoutError
maps_list = veto_view.maps_pick
else:
maps_list = sample(mpool, int(series[2]))

str_maps = ' '.join(m.dev_name for m in maps_list)
str_maps = ' '.join(m for m in maps_list)

await message.edit(embed=Embed(description='Searching for available game servers...'), view=None)
await asyncio.sleep(2)

match_server = await self.find_match_server(region)

await message.edit(embed=Embed(description='Setting up match on game server...'), view=None)
await asyncio.sleep(2)

Expand Down Expand Up @@ -817,7 +812,7 @@ async def create_match_channels(
awaitables.append(user.move_to(team1_channel))
for user in team2_users:
awaitables.append(user.move_to(team2_channel))
await asyncio.gather(*awaitables)
await asyncio.gather(*awaitables, return_exceptions=True)

return match_catg, team1_channel, team2_channel

Expand All @@ -831,8 +826,8 @@ async def finalize_match(self, match_model: MatchModel, guild_model: GuildModel)
match_model.category.delete(),
db.delete_match(match_model.id)
]
await asyncio.gather(*move_aws)
await asyncio.gather(*delete_aws)
await asyncio.gather(*move_aws, return_exceptions=True)
await asyncio.gather(*delete_aws, return_exceptions=True)

async def update_match_stats(self, match_model: MatchModel):
""""""
Expand Down
1 change: 1 addition & 0 deletions bot/helpers/configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class Config:
guild_id = config['bot']['guild_id']
sync_commands_globally = config['bot']['sync_commands_globally']
debug = config['bot']['debug']
maps = config['bot']['maps']
base_url = config['web']['base_url']
api_key = config['web']['api_key']
POSTGRESQL_USER = config['db']['user']
Expand Down
Loading

0 comments on commit 29bdeb0

Please sign in to comment.