Skip to content

Commit

Permalink
Merged the main branch
Browse files Browse the repository at this point in the history
  • Loading branch information
Endyya committed Nov 28, 2024
2 parents 455d707 + dbeb06c commit 63c31e7
Show file tree
Hide file tree
Showing 7 changed files with 324 additions and 27 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,4 @@ cython_debug/
#.idea/
.vscode/*
client_secrets.json
thalosdiscordbot-eb19ad40416e.json
45 changes: 43 additions & 2 deletions src/SilicaAnimus/discord_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class CheckModal(discord.ui.Modal, title = 'Informations'):
nom = discord.ui.TextInput(label = 'Nom')
prenom = discord.ui.TextInput(label = 'Prénom')


async def on_submit(self, interaction: discord.Interaction):
nom = self.nom
prenom = self.prenom
Expand All @@ -34,6 +35,42 @@ async def on_submit(self, interaction: discord.Interaction):
# last_name = nom
# )
is_member = True


class BureauCog(commands.Cog):
"""Commands used to get information the Bureau"""

def __init__(self, parent_client):
super().__init__()

self.parent_client = parent_client
self.logger = logging.getLogger(type(self).__name__)

@commands.command()
@commands.has_any_role(int(getenv("ADMIN_ROLE_ID")), int(getenv("BUREAU_ROLE_ID")))
async def nom_membre(self, ctx, *arg, **kwargs):
"""This command gets the name of the person from the google sheet"""

self.logger.info("Running nom_membre command")
tokens = ctx.message.content.split(" ")
if len(tokens) != 2:
self.logger.warning("Wrong check member command")
await ctx.channel.send(
"Invoke the command with !nom_membre *pseudo du membre*"
)
return

member_info: MemberInfo = (
await self.parent_client.gsheet_client.get_member_by_discord_name(tokens[1])
)

if member_info.in_spreadsheet:
await ctx.channel.send(
f"{tokens[1]} est {member_info.first_name} {member_info.last_name}"
)
else:
await ctx.channel.send(f"{tokens[1]} n'est pas dans la google sheet")
>>>>>>> origin/main
if is_member:
return_message = f"{prenom} {nom} is a member"
else:
Expand Down Expand Up @@ -62,8 +99,8 @@ def __init__(
self.intents.guilds = True
self.intents.dm_messages = True

self.helloasso_client = helloasso_client
self.gsheet_client = gsheet_client
self.helloasso_client: HelloAssoClient = helloasso_client
self.gsheet_client: GoogleSheetsClient = gsheet_client

self.client = commands.Bot(command_prefix = '?', intents = self.intents)
self.tree = self.client.tree
Expand Down Expand Up @@ -209,6 +246,10 @@ async def on_ready() -> None:
await self.client.tree.sync(guild = self.thalos_guild)
self.logger.info("Commands added")


await self.client.add_cog(BureauCog(self))
self.logger.info("Bureau commands added")

@self.client.event
async def on_message(message) -> None:
self.logger.debug(
Expand Down
148 changes: 140 additions & 8 deletions src/SilicaAnimus/google_sheets_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,17 @@
from dataclasses import dataclass
import logging

from typing import Union
from typing import List


@dataclass
class MemberInfo:
first_name: str = ""
last_name: str = ""
discord_nickname: str = ""
server_nickname: str = ""
in_spreadsheet: bool = False
member_current_year: bool = False
member_last_year: bool = False


class GoogleSheetsClient:
Expand All @@ -34,7 +35,7 @@ def __init__(self, clients_secrets_path: str):
self.sheets = self.google_service.spreadsheets()
self.logger.info("Succesfully logged into Gsheet API")

async def get_spreadsheet(self) -> Union[None, ResourceWarning]:
async def get_spreadsheet(self):
"""Returns the spreadsheet
Returns:
Expand All @@ -43,7 +44,10 @@ async def get_spreadsheet(self) -> Union[None, ResourceWarning]:
try:
result = (
self.sheets.values()
.get(spreadsheetId=getenv("GOOGLE_SPREADSHEET_ID"), range="A1:F1000")
.get(
spreadsheetId=getenv("GOOGLE_SPREADSHEET_ID"),
range=f"{getenv("GOOGLE_SHEET_ID")}!A1:F1000",
)
.execute()
)

Expand Down Expand Up @@ -86,6 +90,9 @@ async def get_member_by_discord_name(self, discord_name: str) -> MemberInfo:
"""Get the member's information using the discord name
Args:
discord_name (str): discord name of the user
Returns:
MemberInfo : The member's information from the spreadsheet
"""

self.logger.info(f"Looking up user {discord_name}")
Expand All @@ -106,10 +113,54 @@ async def get_member_by_discord_name(self, discord_name: str) -> MemberInfo:
member_info.last_name = values[row_index][0]
member_info.first_name = values[row_index][1]
member_info.server_nickname = values[row_index][2]

return member_info

return member_info

async def get_members_by_discord_names(
self, discord_names: List[str]
) -> List[MemberInfo]:
"""Get the members' information using the discord name
Args:
discord_names (List[str]): discord names of the users to query
Returns:
List[MemberInfo] : The members' information from the spreadsheet
"""

self.logger.info(f"Looking up {len(discord_names)} users")

ss = await self.get_spreadsheet()
if ss is None:
return None

values = ss.get("values", [])

members_list = []

for row_index in range(len(values)):
if len(values[row_index]) < 3:
continue

if values[row_index][2] in discord_names:
member_info = MemberInfo()
member_info.discord_nickname = values[row_index][2]
member_info.in_spreadsheet = True
member_info.last_name = values[row_index][0]
member_info.first_name = values[row_index][1]
if len(values[row_index]) < 4:
continue
member_info.member_last_year = values[row_index][3] == "Oui"
if len(values[row_index]) < 5:
continue
member_info.member_current_year = values[row_index][4] == "Oui"

members_list.append(member_info)

return members_list

async def add_member(self, member_info: MemberInfo) -> bool:
"""Add the member in the spreadsheet. If the member is already in the spreadsheet, update informations about the member.
Expand All @@ -119,15 +170,20 @@ async def add_member(self, member_info: MemberInfo) -> bool:

self.logger.info(f"Adding {member_info.first_name} {member_info.last_name}")

values = (await self.get_spreadsheet()).get("values", [])
ss = await self.get_spreadsheet()
if ss is None:
return False

values = ss.get("values", [])

body = {
"values": [
[
member_info.last_name,
member_info.first_name,
member_info.server_nickname,
member_info.discord_nickname,
"Oui" if member_info.member_current_year else "",
"Oui" if member_info.member_last_year else "",
]
]
}
Expand All @@ -147,7 +203,7 @@ async def add_member(self, member_info: MemberInfo) -> bool:
self.sheets.values()
.append(
spreadsheetId=getenv("GOOGLE_SPREADSHEET_ID"),
range="A1",
range=f"{getenv("GOOGLE_SHEET_ID")}!A1",
valueInputOption="USER_ENTERED",
body=body,
)
Expand All @@ -165,12 +221,88 @@ async def add_member(self, member_info: MemberInfo) -> bool:
self.sheets.values()
.update(
spreadsheetId=getenv("GOOGLE_SPREADSHEET_ID"),
range=f"A{member_sheet_row}:F{member_sheet_row}",
range=f"{getenv("GOOGLE_SHEET_ID")}!A{member_sheet_row}:F{member_sheet_row}",
valueInputOption="USER_ENTERED",
body=body,
)
.execute()
)
except HttpError as error:
self.logger.error(error.content)
return None

return True

async def add_members(self, members_info: List[MemberInfo]) -> bool:
"""Add the members in the spreadsheet. If a member is already in the spreadsheet, update informations about the member.
Args:
member_info (List[MemberInfo]): The member's information.
"""

self.logger.info(f"Adding {len(members_info)} members")

ss = await self.get_spreadsheet()
if ss is None:
return False

values = ss.get("values", [])

insert_values = {
(member_info.first_name.lower(), member_info.last_name.lower()): [
member_info.last_name,
member_info.first_name,
member_info.discord_nickname,
"Oui" if member_info.member_current_year else "",
"Oui" if member_info.member_last_year else "",
]
for member_info in members_info
}

names_list = [(value[1].lower(), value[0].lower()) for value in values]

update_data = []
append_data = []

for member_info in members_info:
name_tuple = (member_info.first_name.lower(), member_info.last_name.lower())
if names_list.count(name_tuple) > 0:
member_sheet_row = names_list.index(name_tuple) + 1
update_data.append(
{
"range": f"{getenv("GOOGLE_SHEET_ID")}!A{member_sheet_row}:F{member_sheet_row}",
"values": [insert_values[name_tuple]],
}
)
else:
append_data.append(insert_values[name_tuple])

try:
self.logger.info(f"Updating {len(update_data)} existing members")
body = {"valueInputOption": "USER_ENTERED", "data": update_data}
(
self.sheets.values()
.batchUpdate(spreadsheetId=getenv("GOOGLE_SPREADSHEET_ID"), body=body)
.execute()
)
except HttpError as error:
self.logger.error(error.content)
return None

try:
self.logger.info(f"Appending {len(append_data)} new members")
body = {"values": append_data}
(
self.sheets.values()
.append(
spreadsheetId=getenv("GOOGLE_SPREADSHEET_ID"),
range=f"{getenv("GOOGLE_SHEET_ID")}!A1",
valueInputOption="USER_ENTERED",
body=body,
)
.execute()
)

except HttpError as error:
self.logger.error(error.content)
return None
Expand Down
Loading

0 comments on commit 63c31e7

Please sign in to comment.