Added start game command

This commit is contained in:
Elnath 2021-06-08 01:34:29 +02:00
parent 3673a10669
commit c42f017241
2 changed files with 70 additions and 10 deletions

View File

@ -1,10 +1,15 @@
from typing import Dict, Callable from typing import Dict, Callable, List, Union
import discord
import logging
logger = logging.getLogger(__name__)
class Game: class Game:
""" """
Game state for one guild Game state for one guild
""" """
def __init__(self, config_dict: Dict, save_function: Callable): def __init__(self, config_dict: Dict, save_function: Callable):
self.config = config_dict self.config = config_dict
self.save_function = save_function self.save_function = save_function
@ -18,5 +23,61 @@ class Game:
def is_started(self): def is_started(self):
return self.config["game_started"] return self.config["game_started"]
async def start(self): def get_players(self) -> List[int]:
raise NotImplementedError("Start game") return self.config["players"]
def get_player_info(self, player: Union[int, discord.Member]):
if isinstance(player, discord.Member):
player = player.id
return self.config["player_info"][str(player)]
async def start(self, guild: discord.Guild, dm_role: discord.Role, player_role: discord.Role):
if self.is_started():
raise ValueError("Game already started")
logger.info(f"[{guild.name}] Starting game")
self.config["dm_role"] = dm_role.id
self.config["player_role"] = player_role.id
self.config["players"] = [member.id for member in player_role.members]
self.config["player_info"] = {str(player): {} for player in self.config["players"]}
permissions = {
guild.default_role: discord.PermissionOverwrite(send_messages = False),
dm_role: discord.PermissionOverwrite(send_messages = True),
player_role: discord.PermissionOverwrite(send_messages = True),
}
game_category = await guild.create_category("In-game", overwrites = permissions)
self.config["category"] = game_category.id
logger.debug(f"[{guild.name}] Created game category")
permissions = {
guild.default_role: discord.PermissionOverwrite(read_messages = False),
dm_role: discord.PermissionOverwrite(read_messages = True),
}
self.config["admin_chan"] = (await game_category.create_text_channel("admin", overwrites = permissions)).id
logger.debug(f"[{guild.name}] Created admin channel")
permissions = {
guild.default_role: discord.PermissionOverwrite(send_messages = False),
dm_role: discord.PermissionOverwrite(send_messages = True),
}
self.config["announce_chan"] = (await game_category.create_text_channel("announce", overwrites = permissions)).id
self.config["votes_chan"] = (await game_category.create_text_channel("votes", overwrites = permissions)).id
logger.debug(f"[{guild.name}] Created announcements and votes channels")
self.config["discussion_chan"] = (await game_category.create_text_channel("discussion")).id # Permissions are inherited from the category
logger.debug(f"[{guild.name}] Created discussion channel")
for player in self.get_players():
player_member: discord.Member = guild.get_member(player)
channel_permissions = {
guild.default_role: discord.PermissionOverwrite(read_messages = False),
player_member: discord.PermissionOverwrite(read_messages = True),
dm_role: discord.PermissionOverwrite(read_messages = True),
}
player_channel = await game_category.create_text_channel(player_member.name, overwrites = channel_permissions)
self.get_player_info(player)["channel"] = player_channel.id
logger.debug(f"[{guild.name}] Created player channels")
self.config["game_started"] = True
self.save_function()

View File

@ -22,7 +22,7 @@ class SecretBot(commands.Cog):
self.bot = commands.Bot( self.bot = commands.Bot(
"!", "!",
help_command = commands.MinimalHelpCommand(), help_command = commands.MinimalHelpCommand(),
intents = discord.Intents(guild_messages = True, guilds = True), intents = discord.Intents(guild_messages = True, guilds = True, members = True),
allowed_mentions = discord.AllowedMentions.none(), # By default we do not allow mentions, as we will white-list them on each required message allowed_mentions = discord.AllowedMentions.none(), # By default we do not allow mentions, as we will white-list them on each required message
) )
self.bot.add_cog(self) self.bot.add_cog(self)
@ -33,7 +33,7 @@ class SecretBot(commands.Cog):
def get_command_usage_message(self, command: commands.Command, prepend = "Usage: ") -> str: def get_command_usage_message(self, command: commands.Command, prepend = "Usage: ") -> str:
command_elements = [str(cmd) for cmd in command.parents] + [command.name] command_elements = [str(cmd) for cmd in command.parents] + [command.name]
return f"{prepend}`{self.command_prefix}{' '.join(command_elements)} {command.signature}`" return f"{prepend}`{self.bot.command_prefix}{' '.join(command_elements)} {command.signature}`"
@commands.Cog.listener() @commands.Cog.listener()
async def on_ready(self): async def on_ready(self):
@ -42,7 +42,7 @@ class SecretBot(commands.Cog):
oauth_url = discord.utils.oauth_url( oauth_url = discord.utils.oauth_url(
self.bot.user.id, self.bot.user.id,
discord.Permissions(manage_channels = True, read_messages = True, send_messages = True) discord.Permissions(read_messages = True, send_messages = True, manage_channels = True, manage_roles = True, mention_everyone = True, manage_messages = True)
) )
logger.info(f"You can invite the bot to your server using the following link: {oauth_url}") logger.info(f"You can invite the bot to your server using the following link: {oauth_url}")
@ -90,14 +90,13 @@ class SecretBot(commands.Cog):
await ctx.reply(":ping_pong:", mention_author = True) await ctx.reply(":ping_pong:", mention_author = True)
@commands.command("StartGame") @commands.command("StartGame")
async def start_game(self, ctx: commands.Context): async def start_game(self, ctx: commands.Context, dm_role: discord.Role, player_role: discord.Role):
game = self.games_file[ctx.guild] game = self.games_file[ctx.guild]
if game.is_started(): if game.is_started():
await ctx.reply(":x: a game is already running") await ctx.reply(":x: a game is already running")
else: else:
await game.start() await ctx.guild.get_member(self.bot.user.id).add_roles(dm_role)
await game.start(ctx.guild, dm_role, player_role)
if __name__ == '__main__': if __name__ == '__main__':