'/close' command and fixes

This commit is contained in:
guams 2025-03-28 18:30:39 +01:00
parent a166fff52a
commit f18987307b
3 changed files with 203 additions and 94 deletions

View File

@ -32,6 +32,51 @@ async def change_bet(conn: connection, user_id: str, guild_id: str, new_bet_amou
cur.execute("UPDATE member SET bet_value = %s WHERE user_id=%s AND guild_id=%s", cur.execute("UPDATE member SET bet_value = %s WHERE user_id=%s AND guild_id=%s",
(new_bet_amount, user_id, guild_id)) (new_bet_amount, user_id, guild_id))
conn.commit()
cur.close()
async def is_last_poll_created_opened(conn: connection, creator: str):
cur: cursor = conn.cursor()
cur.execute("select opened "
"from poll "
"where creator=%s "
"and opened=true",
(creator,)
)
result = cur.fetchone()
cur.close()
if result is not None:
return result[0]
return
async def close_poll(conn: connection, poll_id: str):
cur: cursor = conn.cursor()
cur.execute("UPDATE poll SET opened = false WHERE poll_id=%s",
(poll_id,))
conn.commit()
cur.close()
async def get_poll_id_opened(conn: connection, creator: str):
cur: cursor = conn.cursor()
cur.execute("select opened, poll_id, question "
"from poll "
"where creator=%s "
"and opened=true",
(creator,)
)
result = cur.fetchone()
cur.close()
return result
async def get_user_vote(conn: connection, user_id: str, poll_id: str): async def get_user_vote(conn: connection, user_id: str, poll_id: str):
cur: cursor = conn.cursor() cur: cursor = conn.cursor()
@ -44,9 +89,11 @@ async def get_user_vote(conn: connection, user_id: str, poll_id: str):
(user_id, poll_id) (user_id, poll_id)
) )
conn.commit() result = cur.fetchone()
cur.close() cur.close()
return result
async def bet(conn, vote_id: str, poll_id: str, user_id: str, guild_id: str): async def bet(conn, vote_id: str, poll_id: str, user_id: str, guild_id: str):
cur = conn.cursor() cur = conn.cursor()
@ -100,15 +147,18 @@ async def insert_guild(conn, guild_id):
cur.close() cur.close()
async def insert_user(conn, user_id, guild_id, global_name, avatar): async def insert_user(conn, user_id, guild_id, username, avatar):
cur = conn.cursor() cur = conn.cursor()
cur.execute( cur.execute(
"INSERT INTO " "INSERT INTO "
"member (user_id, guild_id, global_name, avatar) " "member (user_id, guild_id, username, avatar) "
"VALUES (%s, %s, %s, %s)", "VALUES (%s, %s, %s, %s)",
(user_id, guild_id, global_name, avatar) (user_id, guild_id, username, avatar)
) )
conn.commit() conn.commit()
cur.close() cur.close()
# nombre de vote par vote_id pour calculer l'issue du vote (et potentiellement la côte)
# select vote_id, count(distinct vote_member.user_id) from vote_member group by vote_id

View File

@ -32,7 +32,7 @@ CREATE TABLE member
( (
user_id VARCHAR(255), user_id VARCHAR(255),
guild_id VARCHAR(255), guild_id VARCHAR(255),
global_name VARCHAR(255), username VARCHAR(255),
points bigint DEFAULT 50, points bigint DEFAULT 50,
bet_value bigint DEFAULT 50, bet_value bigint DEFAULT 50,
avatar TEXT, avatar TEXT,

77
main.py
View File

@ -8,7 +8,8 @@ import requests
import websockets import websockets
from database import (user_exists, insert_user, guild_exists, insert_guild, from database import (user_exists, insert_user, guild_exists, insert_guild,
insert_poll, insert_vote_options, bet, get_user_vote, change_bet) insert_poll, insert_vote_options, bet, get_user_vote, change_bet,
is_last_poll_created_opened, get_poll_id_opened, close_poll)
from enums import OpCode, EventTitle, InteractionType from enums import OpCode, EventTitle, InteractionType
with open('configuration.json', 'r') as file: with open('configuration.json', 'r') as file:
@ -52,6 +53,11 @@ async def create_command():
} }
] ]
}, },
{
"name": "close",
"type": 1,
"description": "Pour clôturer un sondage",
},
{ # à améliorer en /profil <@user_id> { # à améliorer en /profil <@user_id>
"name": "me", "name": "me",
"type": 1, "type": 1,
@ -92,7 +98,6 @@ async def create_poll(guild_id: str, creator_id: str, poll_created_id: str, inte
if "vote" in comp["components"][0]["custom_id"] and comp["components"][0]["value"] != "": if "vote" in comp["components"][0]["custom_id"] and comp["components"][0]["value"] != "":
vote_text = comp["components"][0]["value"] vote_text = comp["components"][0]["value"]
vote_options += f"Option {index}: {vote_text}\n" vote_options += f"Option {index}: {vote_text}\n"
buttons.append({ buttons.append({
"type": 2, "type": 2,
"label": vote_text, "label": vote_text,
@ -161,10 +166,14 @@ async def identify(websocket):
await websocket.send(json.dumps(payload)) await websocket.send(json.dumps(payload))
async def create_poll_form(interaction_id: str, interaction_token: str, guild_id: str): async def create_poll_form(interaction_id: str, interaction_token: str, guild_id: str, user_id: str, username: str,
avatar: str):
poll_id = uuid4() poll_id = uuid4()
if not await guild_exists(conn=conn, guild_id=guild_id): if not await guild_exists(conn=conn, guild_id=guild_id):
await insert_guild(conn=conn, guild_id=guild_id) await insert_guild(conn=conn, guild_id=guild_id)
if not await user_exists(conn=conn, user_id=user_id, guild_id=guild_id):
await insert_user(conn=conn, user_id=user_id, guild_id=guild_id, username=username, avatar=avatar)
if not await is_last_poll_created_opened(conn=conn, creator=user_id):
body = { body = {
"type": 9, "type": 9,
"data": { "data": {
@ -244,7 +253,15 @@ async def create_poll_form(interaction_id: str, interaction_token: str, guild_id
] ]
} }
} }
else:
body = {
"type": 4,
"data": {
"content": f"<@{user_id}>, il faut d'abord clôturer ton sondage avant de pouvoir en créer un nouveau. "
f"(commande: **/close**)",
"flags": 64
}
}
res = requests.post(f"{API_URL}/interactions/{interaction_id}/{interaction_token}/callback", json=body, res = requests.post(f"{API_URL}/interactions/{interaction_id}/{interaction_token}/callback", json=body,
headers={"Authorization": f"Bot {TOKEN}"}) headers={"Authorization": f"Bot {TOKEN}"})
if res.status_code == 400: if res.status_code == 400:
@ -261,9 +278,9 @@ async def heartbeat(websocket, interval):
async def vote_confirmation(interaction_id: str, interaction_token: str, custom_id: str, user_id: str, async def vote_confirmation(interaction_id: str, interaction_token: str, custom_id: str, user_id: str,
guild_id: str, guild_id: str,
avatar: str, global_name: str): avatar: str, username: str):
user_vote = await get_user_vote(conn=conn, user_id=user_id, poll_id=custom_id.split("_")[0]) user_vote = await get_user_vote(conn=conn, user_id=user_id, poll_id=custom_id.split("_")[0])
if user_vote: if user_vote is not None:
body = { body = {
"type": 4, "type": 4,
"data": { "data": {
@ -275,7 +292,7 @@ async def vote_confirmation(interaction_id: str, interaction_token: str, custom_
if not await user_exists(conn=conn, user_id=user_id, guild_id=guild_id): if not await user_exists(conn=conn, user_id=user_id, guild_id=guild_id):
if not await guild_exists(conn=conn, guild_id=guild_id): if not await guild_exists(conn=conn, guild_id=guild_id):
await insert_guild(conn=conn, guild_id=guild_id) await insert_guild(conn=conn, guild_id=guild_id)
await insert_user(conn=conn, user_id=user_id, avatar=avatar, guild_id=guild_id, global_name=global_name) await insert_user(conn=conn, user_id=user_id, avatar=avatar, guild_id=guild_id, username=username)
await bet(conn=conn, guild_id=guild_id, user_id=user_id, vote_id=custom_id, await bet(conn=conn, guild_id=guild_id, user_id=user_id, vote_id=custom_id,
poll_id=custom_id.split("_")[0]) poll_id=custom_id.split("_")[0])
body = { body = {
@ -297,6 +314,37 @@ async def vote_confirmation(interaction_id: str, interaction_token: str, custom_
print(res) print(res)
async def close_poll_cmd(guild_id: str, user_id: str, interaction_id: str, interaction_token: str, username: str,
avatar: str):
if not await guild_exists(conn=conn, guild_id=guild_id):
await insert_guild(conn=conn, guild_id=guild_id)
if not await user_exists(conn=conn, user_id=user_id, guild_id=guild_id):
await insert_user(conn=conn, user_id=user_id, guild_id=guild_id, username=username, avatar=avatar)
poll: tuple = await get_poll_id_opened(conn=conn, creator=user_id)
if poll is not None:
await close_poll(conn=conn, poll_id=poll[1])
body = {
"type": 4,
"data": {
"content": f'@everyone le sondage "{poll[2]}" est terminé !',
}
}
else:
body = {
"type": 4,
"data": {
"content": f"<@{user_id}>, tu n'as actuellement aucun sondage en cours.",
"flags": 64
}
}
res = requests.post(f"{API_URL}/interactions/{interaction_id}/{interaction_token}/callback", json=body,
headers={"Authorization": f"Bot {TOKEN}"})
if res.status_code == 400:
print(res.json())
else:
print(res)
async def get_event(response: Any): async def get_event(response: Any):
match response["t"]: match response["t"]:
case EventTitle.MESSAGE_CREATE: case EventTitle.MESSAGE_CREATE:
@ -320,12 +368,23 @@ async def get_event(response: Any):
user_id=user_id, user_id=user_id,
guild_id=response["d"]["guild"]["id"], guild_id=response["d"]["guild"]["id"],
avatar=response["d"]["member"]["user"]["avatar"], avatar=response["d"]["member"]["user"]["avatar"],
global_name=response["d"]["member"]["user"]["global_name"]) username=response["d"]["member"]["user"]["username"])
elif (response["d"]["type"] == InteractionType.APPLICATION_COMMAND and elif (response["d"]["type"] == InteractionType.APPLICATION_COMMAND and
response["d"]["data"]["name"] == 'poll'): response["d"]["data"]["name"] == 'poll'):
await create_poll_form(interaction_id=response["d"]["id"], await create_poll_form(interaction_id=response["d"]["id"],
user_id=response["d"]["member"]["user"]["id"],
interaction_token=response["d"]["token"], interaction_token=response["d"]["token"],
guild_id=response["d"]["guild_id"]) guild_id=response["d"]["guild_id"],
avatar=response["d"]["member"]["user"]["avatar"],
username=response["d"]["member"]["user"]["username"])
elif (response["d"]["type"] == InteractionType.APPLICATION_COMMAND and
response["d"]["data"]["name"] == 'close'):
await close_poll_cmd(guild_id=response["d"]["guild_id"],
user_id=response["d"]["member"]["user"]["id"],
interaction_id=response["d"]["id"],
interaction_token=response["d"]["token"],
avatar=response["d"]["member"]["user"]["avatar"],
username=response["d"]["member"]["user"]["username"])
elif (response["d"]["type"] == InteractionType.APPLICATION_COMMAND and elif (response["d"]["type"] == InteractionType.APPLICATION_COMMAND and
response["d"]["data"]["name"] == 'bet'): response["d"]["data"]["name"] == 'bet'):
try: try: