Update WIPBOT.py

This commit is contained in:
kl3z
2025-08-05 08:52:08 +01:00
committed by GitHub
parent 563d950e36
commit fb4d4ee025
+273 -156
View File
@@ -28,14 +28,16 @@ DUNGEONS = [
] ]
DIFICULDADES = [str(i) for i in range(0, 21)] + ["20+"] DIFICULDADES = [str(i) for i in range(0, 21)] + ["20+"]
LIMITES = {"Tank": 1, "Healer": 1, "DPS": 3} LIMITES = {"Tank": 1, "Healer": 1, "DPS": 3}
grupo_mensagem_id = None # grupo_mensagem_id = None
inscritos = {"Tank": [], "Healer": [], "DPS": []} # inscritos = {"Tank": [], "Healer": [], "DPS": []}
classes_escolhidas = {} # classes_escolhidas = {}
dungeon_escolhida = DUNGEONS[2] # dungeon_escolhida = DUNGEONS[2]
dificuldade_escolhida = "10" # dificuldade_escolhida = "10"
data_formatada = "06/08/2025" # data_formatada = "06/08/2025"
hora_escolhida = "22:00" # hora_escolhida = "22:00"
alteracoes_feitas = {"dungeon": False, "dificuldade": False, "data": False} # alteracoes_feitas = {"dungeon": False, "dificuldade": False, "data": False}
# jogador_em_progresso = None
def format_grupo_embed(): def format_grupo_embed():
def format_role(role): def format_role(role):
players = inscritos[role] players = inscritos[role]
@@ -59,7 +61,6 @@ def format_grupo_embed():
async def criar_grupo_customizado(canal): async def criar_grupo_customizado(canal):
global grupo_mensagem_id, inscritos, dungeon_escolhida, dificuldade_escolhida, data_formatada, hora_escolhida, alteracoes_feitas global grupo_mensagem_id, inscritos, dungeon_escolhida, dificuldade_escolhida, data_formatada, hora_escolhida, alteracoes_feitas
inscritos = {"Tank": [], "Healer": [], "DPS": []} inscritos = {"Tank": [], "Healer": [], "DPS": []}
classes_escolhidas.clear() classes_escolhidas.clear()
dungeon_escolhida = DUNGEONS[2] dungeon_escolhida = DUNGEONS[2]
@@ -67,18 +68,16 @@ async def criar_grupo_customizado(canal):
data_formatada = "06/08/2025" data_formatada = "06/08/2025"
hora_escolhida = "22:00" hora_escolhida = "22:00"
alteracoes_feitas = {"dungeon": False, "dificuldade": False, "data": False} alteracoes_feitas = {"dungeon": False, "dificuldade": False, "data": False}
embed = format_grupo_embed() embed = format_grupo_embed()
mensagem = await canal.send(embed=embed, view=DungeonView()) mensagem = await canal.send(embed=embed, view=DungeonView())
grupo_mensagem_id = mensagem.id grupo_mensagem_id = mensagem.id
await canal.send( await canal.send(
"Escolher a tua **Role**:", "Escolher a tua **Role**:",
view=RoleView("Novo jogador", canal.id, grupo_mensagem_id) view=RoleView("Novo jogador", canal.id, grupo_mensagem_id)
) )
class StackDropdown(Select): class StackDropdown(Select):
def __init__(self): def __init__(self, grupo):
self.grupo = grupo
options = [ options = [
discord.SelectOption(label="Plate Stack"), discord.SelectOption(label="Plate Stack"),
discord.SelectOption(label="Leather Stack"), discord.SelectOption(label="Leather Stack"),
@@ -90,128 +89,166 @@ class StackDropdown(Select):
async def callback(self, interaction: discord.Interaction): async def callback(self, interaction: discord.Interaction):
escolha = self.values[0] escolha = self.values[0]
forum_channel = discord.utils.get(interaction.guild.channels, name="lfg", type=discord.ChannelType.forum) forum_channel = discord.utils.get(interaction.guild.channels, name="lfg", type=discord.ChannelType.forum)
if not forum_channel: if not forum_channel:
await interaction.response.send_message("❌ Canal de fórum 'lfg' não encontrado ou não é do tipo fórum.", ephemeral=True) await interaction.response.send_message("❌ Canal de fórum 'lfg' não encontrado ou não é do tipo fórum.", ephemeral=True)
return return
# Cria o post no fórum
thread = await forum_channel.create_thread(name=escolha, content=escolha) thread = await forum_channel.create_thread(name=escolha, content=escolha)
# Apaga a mensagem original com a combobox
await interaction.message.delete() await interaction.message.delete()
# Evita erro de timeout
await interaction.response.defer() await interaction.response.defer()
class StackView(View):
def __init__(self, grupo):
super().__init__()
self.grupo = grupo
self.add_item(StackDropdown(grupo))
@bot.command(name="bot") @bot.command(name="bot")
async def bot_command(ctx): async def bot_command(ctx):
await ctx.send(view=StackView()) grupo_temporario = GrupoDungeon()
await ctx.send(view=StackView(grupo_temporario))
class StackView(View): membro = discord.utils.get(ctx.guild.members, name="carlitosqt")
def __init__(self): if membro:
super().__init__() await ctx.send(f"Parabéns {membro.mention}!")
self.add_item(StackDropdown())
CLASSES_POR_ROLE = { CLASSES_POR_ROLE = {
"Tank": [ "Tank": [
("Protection Paladin", "https://wow.zamimg.com/images/wow/icons/large/spell_holy_avengershield.jpg"), ("Paladin", "https://wow.zamimg.com/images/wow/icons/large/spell_holy_avengershield.jpg"),
("Protection Warrior", "https://wow.zamimg.com/images/wow/icons/large/spell_warrior_protetion_spec.jpg"), ("Warrior", "https://wow.zamimg.com/images/wow/icons/large/spell_warrior_protetion_spec.jpg"),
("Blood Death Knight", "https://wow.zamimg.com/images/wow/icons/large/spell_deathknight_bloodpresence.jpg"), ("Death Knight", "https://wow.zamimg.com/images/wow/icons/large/spell_deathknight_bloodpresence.jpg"),
("Vengeance Demon Hunter","https://wow.zamimg.com/images/wow/icons/large/ability_demonhunter_specdps.jpg"), ("Demon Hunter","https://wow.zamimg.com/images/wow/icons/large/ability_demonhunter_specdps.jpg"),
("Brewmaster Monk", "https://wow.zamimg.com/images/wow/icons/large/spell_monk_brewmaster_spec.jpg"), ("Monk", "https://wow.zamimg.com/images/wow/icons/large/spell_monk_brewmaster_spec.jpg"),
("Guardian Druid", "https://wow.zamimg.com/images/wow/icons/large/ability_racial_bearform.jpg") ("Druid", "https://wow.zamimg.com/images/wow/icons/large/ability_racial_bearform.jpg")
], ],
"Healer": [ "Healer": [
("Discipline Priest", "https://wow.zamimg.com/images/wow/icons/large/spell_holy_powerwordshield.jpg"), ("Priest", "https://wow.zamimg.com/images/wow/icons/large/spell_holy_powerwordshield.jpg"),
("Restoration Shaman", "https://wow.zamimg.com/images/wow/icons/large/spell_nature_magicimmunity.jpg"), ("Shaman", "https://wow.zamimg.com/images/wow/icons/large/spell_nature_magicimmunity.jpg"),
("Mistweaver Monk", "https://wow.zamimg.com/images/wow/icons/large/spell_monk_mistweaver_spec.jpg"), ("Monk", "https://wow.zamimg.com/images/wow/icons/large/spell_monk_mistweaver_spec.jpg"),
("Restoration Druid", "https://wow.zamimg.com/images/wow/icons/large/spell_nature_healingtouch.jpg"), ("Druid", "https://wow.zamimg.com/images/wow/icons/large/spell_nature_healingtouch.jpg"),
("Holy Paladin", "https://wow.zamimg.com/images/wow/icons/large/spell_holy_holybolt.jpg"), ("Paladin", "https://wow.zamimg.com/images/wow/icons/large/spell_holy_holybolt.jpg"),
("Preservation Evoker", "https://wow.zamimg.com/images/wow/icons/large/spell_spec_evoker_preservation.jpg") ("Evoker", "https://wow.zamimg.com/images/wow/icons/large/spell_spec_evoker_preservation.jpg")
], ],
"DPS": [ "DPS": [
("Arcane Mage", "https://wow.zamimg.com/images/wow/icons/large/spell_holy_magicalsentry.jpg"), ("Mage", "https://wow.zamimg.com/images/wow/icons/large/spell_holy_magicalsentry.jpg"),
("Balance Druid", "https://wow.zamimg.com/images/wow/icons/large/spell_nature_starfall.jpg"), ("Druid", "https://wow.zamimg.com/images/wow/icons/large/spell_nature_starfall.jpg"),
("Unholy Death Knight", "https://wow.zamimg.com/images/wow/icons/large/spell_deathknight_unholypresence.png"), ("Paladin", "https://wow.zamimg.com/images/wow/icons/large/spell_holy_auraoflight.jpg"),
("Retribution Paladin", "https://wow.zamimg.com/images/wow/icons/large/spell_holy_auraoflight.jpg"), ("Shaman", "https://wow.zamimg.com/images/wow/icons/large/spell_nature_lightning.jpg"),
("Fire Mage", "https://wow.zamimg.com/images/wow/icons/large/spell_fire_flamebolt.jpg"), ("Hunter", "https://wow.zamimg.com/images/wow/icons/large/ability_hunter_bestialdiscipline.jpg"),
("Elemental Shaman", "https://wow.zamimg.com/images/wow/icons/large/spell_nature_lightning.jpg"), ("Rogue", "https://wow.zamimg.com/images/wow/icons/large/ability_rogue_deadlybrew.jpg"),
("Enhancement Shaman", "https://wow.zamimg.com/images/wow/icons/large/spell_shaman_improvedstormstrike.jpg"), ("Demon Hunter","https://wow.zamimg.com/images/wow/icons/large/ability_demonhunter_specdps.jpg"),
("Marksmanship Hunter", "https://wow.zamimg.com/images/wow/icons/large/ability_hunter_focusedaim.jpg"), ("Priest", "https://wow.zamimg.com/images/wow/icons/large/spell_shadow_shadowwordpain.jpg"),
("Havoc Demon Hunter", "https://wow.zamimg.com/images/wow/icons/large/ability_demonhunter_specdps.jpg"), ("Death Knight", "https://wow.zamimg.com/images/wow/icons/large/spell_deathknight_frostpresence.png"),
("Beast Mastery Hunter", "https://wow.zamimg.com/images/wow/icons/large/ability_hunter_bestialdiscipline.jpg"), ("Monk", "https://wow.zamimg.com/images/wow/icons/large/spell_monk_windwalkerspec.jpg"),
("Assassination Rogue", "https://wow.zamimg.com/images/wow/icons/large/ability_rogue_deadlybrew.jpg"), ("Warrior", "https://wow.zamimg.com/images/wow/icons/large/ability_warrior_innerrage.jpg"),
("Outlaw Rogue", "https://wow.zamimg.com/images/wow/icons/large/ability_rogue_waylay.jpg"), ("Warlock", "https://wow.zamimg.com/images/wow/icons/large/spell_shadow_deathcoil.jpg"),
("Shadow Priest", "https://wow.zamimg.com/images/wow/icons/large/spell_shadow_shadowwordpain.jpg"), ("Evoker", "https://wow.zamimg.com/images/wow/icons/large/spell_spec_evoker_devastation.jpg")
("Frost Death Knight", "https://wow.zamimg.com/images/wow/icons/large/spell_deathknight_frostpresence.png"),
("Windwalker Monk", "https://wow.zamimg.com/images/wow/icons/large/spell_monk_windwalkerspec.jpg"),
("Fury Warrior", "https://wow.zamimg.com/images/wow/icons/large/ability_warrior_innerrage.jpg"),
("Arms Warrior", "https://wow.zamimg.com/images/wow/icons/large/ability_warrior_savageblow.jpg"),
("Affliction Warlock", "https://wow.zamimg.com/images/wow/icons/large/spell_shadow_deathcoil.jpg"),
("Destruction Warlock", "https://wow.zamimg.com/images/wow/icons/large/spell_shadow_rainoffire.jpg"),
("Feral Druid", "https://wow.zamimg.com/images/wow/icons/large/ability_druid_catform.jpg"),
("Devastation Evoker", "https://wow.zamimg.com/images/wow/icons/large/spell_spec_evoker_devastation.jpg"),
("Survival Hunter", "https://wow.zamimg.com/images/wow/icons/large/ability_hunter_camouflage.jpg"),
("Frost Mage", "https://wow.zamimg.com/images/wow/icons/large/spell_frost_frostbolt02.jpg")
] ]
} }
class DungeonDropdown(Select):
class GrupoDungeon:
def __init__(self): def __init__(self):
self.inscritos = {"Tank": [], "Healer": [], "DPS": []}
self.classes_escolhidas = {}
self.dungeon_escolhida = DUNGEONS[2]
self.dificuldade_escolhida = "10"
self.data_formatada = "06/08/2025"
self.hora_escolhida = "22:00"
self.alteracoes_feitas = {"dungeon": False, "dificuldade": False, "data": False}
self.jogador_em_progresso = None
self.mensagem_id = None
self.canal_id = None
self.thread = None
def format_grupo_embed(self):
def format_role(role):
players = self.inscritos[role]
if not players:
return "None"
return "\n".join(f"{p} ({self.classes_escolhidas.get(p, 'sem classe')})" for p in players)
embed = discord.Embed(
title=f"Dungeon: {self.dungeon_escolhida}",
description=(
f"Dificuldade: {self.dificuldade_escolhida}\n"
f"Marcação: {self.data_formatada} às {self.hora_escolhida}"
),
color=0x00ffcc
)
embed.add_field(name=f"{EMOJI_TANK} Tank", value=format_role("Tank"), inline=False)
embed.add_field(name=f"{EMOJI_HEALER} Healer", value=format_role("Healer"), inline=False)
embed.add_field(name=f"{EMOJI_DPS} DPS", value=format_role("DPS"), inline=False)
embed.set_footer(text="Bot created by Kl3z")
return embed
grupos_ativos = {}
class DungeonDropdown(Select):
def __init__(self, grupo: GrupoDungeon):
self.grupo = grupo
options = [discord.SelectOption(label=d, value=d) for d in DUNGEONS] options = [discord.SelectOption(label=d, value=d) for d in DUNGEONS]
super().__init__(placeholder="Escolhe a dungeon", min_values=1, max_values=1, options=options) super().__init__(placeholder="Escolhe a dungeon", min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction): async def callback(self, interaction: discord.Interaction):
global dungeon_escolhida if self.grupo.alteracoes_feitas["dungeon"]:
if alteracoes_feitas["dungeon"]:
await interaction.response.send_message("❌ A dungeon já foi escolhida e não pode ser alterada novamente.", ephemeral=True) await interaction.response.send_message("❌ A dungeon já foi escolhida e não pode ser alterada novamente.", ephemeral=True)
return return
dungeon_escolhida = self.values[0]
alteracoes_feitas["dungeon"] = True
mensagem = await interaction.channel.fetch_message(grupo_mensagem_id) self.grupo.dungeon_escolhida = self.values[0]
nova_view = DungeonView() self.grupo.alteracoes_feitas["dungeon"] = True
if all(alteracoes_feitas.values()):
canal = bot.get_channel(self.grupo.canal_id)
mensagem = await canal.fetch_message(self.grupo.mensagem_id)
nova_view = DungeonView(self.grupo)
if all(self.grupo.alteracoes_feitas.values()):
nova_view.clear_items() nova_view.clear_items()
await mensagem.edit(embed=format_grupo_embed(), view=nova_view) await mensagem.edit(embed=self.grupo.format_grupo_embed(), view=nova_view)
if isinstance(interaction.channel, discord.Thread):
await interaction.channel.edit(name=f"{dungeon_escolhida} - Key {dificuldade_escolhida}") if self.grupo.thread:
await self.grupo.thread.edit(name=f"{self.grupo.dungeon_escolhida} - Key {self.grupo.dificuldade_escolhida}")
await interaction.response.defer() await interaction.response.defer()
class DificuldadeDropdown(Select): class DificuldadeDropdown(Select):
def __init__(self): def __init__(self, grupo):
self.grupo = grupo
options = [discord.SelectOption(label=f"Chave {d}", value=d) for d in DIFICULDADES] options = [discord.SelectOption(label=f"Chave {d}", value=d) for d in DIFICULDADES]
super().__init__(placeholder="Escolhe a dificuldade", min_values=1, max_values=1, options=options) super().__init__(placeholder="Escolhe a dificuldade", min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction): async def callback(self, interaction: discord.Interaction):
global dificuldade_escolhida if self.grupo.alteracoes_feitas["dificuldade"]:
if alteracoes_feitas["dificuldade"]:
await interaction.response.send_message("❌ A dificuldade já foi definida e não pode ser alterada novamente.", ephemeral=True) await interaction.response.send_message("❌ A dificuldade já foi definida e não pode ser alterada novamente.", ephemeral=True)
return return
dificuldade_escolhida = self.values[0]
alteracoes_feitas["dificuldade"] = True self.grupo.dificuldade_escolhida = self.values[0]
mensagem = await interaction.channel.fetch_message(grupo_mensagem_id) self.grupo.alteracoes_feitas["dificuldade"] = True
nova_view = DungeonView()
if all(alteracoes_feitas.values()): canal = bot.get_channel(self.grupo.canal_id)
mensagem = await canal.fetch_message(self.grupo.mensagem_id)
nova_view = DungeonView(self.grupo)
if all(self.grupo.alteracoes_feitas.values()):
nova_view.clear_items() nova_view.clear_items()
await mensagem.edit(embed=format_grupo_embed(), view=nova_view)
if isinstance(interaction.channel, discord.Thread): await mensagem.edit(embed=self.grupo.format_grupo_embed(), view=nova_view)
await interaction.channel.edit(name=f"{dungeon_escolhida} - Key {dificuldade_escolhida}")
if self.grupo.thread:
await self.grupo.thread.edit(name=f"{self.grupo.dungeon_escolhida} - Key {self.grupo.dificuldade_escolhida}")
await interaction.response.defer() await interaction.response.defer()
class DataModal(Modal, title="Definir Data da Dungeon"): class DataModal(Modal, title="Definir Data da Dungeon"):
dia = TextInput(label="Dia do mês (1-31)", placeholder="Ex: 6", max_length=2) def __init__(self, grupo):
hora = TextInput(label="Hora (HH:MM)", placeholder="Ex: 22:30", max_length=5) super().__init__()
self.grupo = grupo
self.dia = TextInput(label="Dia do mês (1-31)", placeholder="Ex: 6", max_length=2)
self.hora = TextInput(label="Hora (HH:MM)", placeholder="Ex: 22:30", max_length=5)
self.add_item(self.dia)
self.add_item(self.hora)
async def on_submit(self, interaction: discord.Interaction): async def on_submit(self, interaction: discord.Interaction):
global data_formatada, hora_escolhida if self.grupo.alteracoes_feitas["data"]:
if alteracoes_feitas["data"]:
await interaction.response.send_message("❌ A data e hora já foram definidas e não podem ser alteradas novamente.", ephemeral=True) await interaction.response.send_message("❌ A data e hora já foram definidas e não podem ser alteradas novamente.", ephemeral=True)
return return
try: try:
@@ -219,6 +256,7 @@ class DataModal(Modal, title="Definir Data da Dungeon"):
if not 1 <= dia_num <= 31: if not 1 <= dia_num <= 31:
raise ValueError("Dia fora do intervalo") raise ValueError("Dia fora do intervalo")
hora_val = datetime.strptime(self.hora.value, "%H:%M").strftime("%H:%M") hora_val = datetime.strptime(self.hora.value, "%H:%M").strftime("%H:%M")
hoje = datetime.now() hoje = datetime.now()
mes = hoje.month mes = hoje.month
ano = hoje.year ano = hoje.year
@@ -228,106 +266,135 @@ class DataModal(Modal, title="Definir Data da Dungeon"):
mes = 1 mes = 1
ano += 1 ano += 1
data_completa = datetime(year=ano, month=mes, day=dia_num) data_completa = datetime(year=ano, month=mes, day=dia_num)
self.grupo.data_formatada = data_completa.strftime("%d/%m/%Y")
self.grupo.hora_escolhida = hora_val
self.grupo.alteracoes_feitas["data"] = True
canal = bot.get_channel(self.grupo.canal_id)
mensagem = await canal.fetch_message(self.grupo.mensagem_id)
nova_view = DungeonView(self.grupo)
if all(self.grupo.alteracoes_feitas.values()):
nova_view.clear_items()
await mensagem.edit(embed=self.grupo.format_grupo_embed(), view=nova_view)
await interaction.response.defer()
except Exception: except Exception:
await interaction.response.send_message("❌ Data ou hora inválida.", ephemeral=True) await interaction.response.send_message("❌ Data ou hora inválida.", ephemeral=True)
return
data_formatada = data_completa.strftime("%d/%m/%Y")
hora_escolhida = hora_val
alteracoes_feitas["data"] = True
mensagem = await interaction.channel.fetch_message(grupo_mensagem_id)
nova_view = DungeonView()
if all(alteracoes_feitas.values()):
nova_view.clear_items()
await mensagem.edit(embed=format_grupo_embed(), view=nova_view)
await interaction.response.defer()
class BotaoData(Button): class BotaoData(Button):
def __init__(self): def __init__(self, grupo):
super().__init__(label="🗓️ Definir Data", style=discord.ButtonStyle.primary) super().__init__(label="🗓️ Definir Data", style=discord.ButtonStyle.primary)
self.grupo = grupo
async def callback(self, interaction: discord.Interaction): async def callback(self, interaction: discord.Interaction):
await interaction.response.send_modal(DataModal()) await interaction.response.send_modal(DataModal(self.grupo))
class DungeonView(View): class DungeonView(View):
def __init__(self): def __init__(self, grupo):
super().__init__(timeout=None) super().__init__(timeout=None)
if not alteracoes_feitas["dungeon"]: self.grupo = grupo
self.add_item(DungeonDropdown()) if not self.grupo.alteracoes_feitas["dungeon"]:
if not alteracoes_feitas["dificuldade"]: self.add_item(DungeonDropdown(self.grupo))
self.add_item(DificuldadeDropdown()) if not self.grupo.alteracoes_feitas["dificuldade"]:
if not alteracoes_feitas["data"]: self.add_item(DificuldadeDropdown(self.grupo))
self.add_item(BotaoData()) if not self.grupo.alteracoes_feitas["data"]:
self.add_item(BotaoData(self.grupo))
class RoleDropdown(Select): class RoleDropdown(Select):
def __init__(self, jogador, ctx_channel_id, role_msg_id): def __init__(self, jogador, ctx_channel_id, role_msg_id, grupo):
self.jogador = jogador self.jogador = jogador
self.ctx_channel_id = ctx_channel_id self.ctx_channel_id = ctx_channel_id
self.role_msg_id = role_msg_id self.role_msg_id = role_msg_id
self.grupo = grupo
options = [] options = []
for role in LIMITES: for role in LIMITES:
if len(inscritos[role]) < LIMITES[role]: if len(self.grupo.inscritos[role]) < LIMITES[role]:
options.append(discord.SelectOption(label=role, description="Escolher esta role")) options.append(discord.SelectOption(label=role, description="Escolher esta role"))
placeholder = "Escolhe a tua role" if options else "Todas as roles preenchidas" placeholder = "Escolhe a tua role" if options else "Todas as roles preenchidas"
super().__init__(placeholder=placeholder, options=options, disabled=(len(options) == 0)) super().__init__(placeholder=placeholder, options=options, disabled=(len(options) == 0))
async def callback(self, interaction: discord.Interaction): async def callback(self, interaction: discord.Interaction):
global jogador_em_progresso if self.grupo.jogador_em_progresso and self.grupo.jogador_em_progresso != interaction.user.display_name:
jogador = interaction.user.display_name
if jogador_em_progresso and jogador_em_progresso != jogador:
await interaction.response.send_message( await interaction.response.send_message(
f"⏳ Aguarda que {jogador_em_progresso} termine a escolha da classe.", f"⏳ Aguarda que {self.grupo.jogador_em_progresso} termine a escolha da classe.",
ephemeral=True ephemeral=True
) )
return return
jogador_em_progresso = jogador
self.grupo.jogador_em_progresso = interaction.user.display_name
role = self.values[0] role = self.values[0]
for r in inscritos:
if jogador in inscritos[r]: # Remover jogador de qualquer role anterior
inscritos[r].remove(jogador) for r in self.grupo.inscritos:
if jogador not in inscritos[role] and len(inscritos[role]) < LIMITES[role]: if interaction.user.display_name in self.grupo.inscritos[r]:
inscritos[role].append(jogador) self.grupo.inscritos[r].remove(interaction.user.display_name)
if interaction.user.display_name not in self.grupo.inscritos[role] and len(self.grupo.inscritos[role]) < LIMITES[role]:
self.grupo.inscritos[role].append(interaction.user.display_name)
canal = bot.get_channel(self.ctx_channel_id) canal = bot.get_channel(self.ctx_channel_id)
if isinstance(canal, discord.Thread): if isinstance(canal, discord.Thread):
await canal.join() await canal.join()
await interaction.message.delete() await interaction.message.delete()
mensagem = await canal.fetch_message(grupo_mensagem_id)
await mensagem.edit(embed=format_grupo_embed()) # Usar self.grupo.mensagem_id em vez da variável global
mensagem = await canal.fetch_message(self.grupo.mensagem_id)
await mensagem.edit(embed=self.grupo.format_grupo_embed())
await canal.send( await canal.send(
f"{jogador}, agora escolhe a tua classe para **{role}**:", f"{interaction.user.display_name}, agora escolhe a tua classe para **{role}**:",
view=ClasseView(role, jogador, self.ctx_channel_id) view=ClasseView(role, interaction.user.display_name, self.ctx_channel_id, self.grupo)
) )
await interaction.response.defer() await interaction.response.defer()
else: else:
jogador_em_progresso = None self.grupo.jogador_em_progresso = None
await interaction.response.send_message("❌ Esta role já está cheia ou ocorreu um erro.", ephemeral=True) await interaction.response.send_message("❌ Esta role já está cheia ou ocorreu um erro.", ephemeral=True)
class ClasseDropdown(Select): class ClasseDropdown(Select):
def __init__(self, role, jogador): def __init__(self, role, jogador, grupo):
self.jogador = jogador self.jogador = jogador
self.role = role
self.grupo = grupo
options = [discord.SelectOption(label=nome, value=nome) for nome, _ in CLASSES_POR_ROLE[role]] options = [discord.SelectOption(label=nome, value=nome) for nome, _ in CLASSES_POR_ROLE[role]]
super().__init__(placeholder=f"Escolhe a classe ({role})", options=options) super().__init__(placeholder=f"Escolhe a classe ({role})", options=options)
async def callback(self, interaction: discord.Interaction): async def callback(self, interaction: discord.Interaction):
global jogador_em_progresso self.grupo.classes_escolhidas[self.jogador] = self.values[0]
classes_escolhidas[self.jogador] = self.values[0]
canal = interaction.channel canal = interaction.channel
mensagem = await canal.fetch_message(grupo_mensagem_id)
await mensagem.edit(embed=format_grupo_embed()) # Usar self.grupo.mensagem_id em vez da variável global
mensagem = await canal.fetch_message(self.grupo.mensagem_id)
await mensagem.edit(embed=self.grupo.format_grupo_embed())
await interaction.message.delete() await interaction.message.delete()
jogador_em_progresso = None self.grupo.jogador_em_progresso = None
if any(len(inscritos[r]) < LIMITES[r] for r in LIMITES):
if any(len(self.grupo.inscritos[r]) < LIMITES[r] for r in LIMITES):
await canal.send( await canal.send(
"Escolher a tua **Role**:", "Escolher a tua **Role**:",
view=RoleView(interaction.user.display_name, canal.id, grupo_mensagem_id) view=RoleView(interaction.user.display_name, canal.id, self.grupo.mensagem_id, self.grupo)
) )
await interaction.response.defer() await interaction.response.defer()
class ClasseView(View): class ClasseView(View):
def __init__(self, role, jogador, ctx_channel_id): def __init__(self, role, jogador, ctx_channel_id, grupo):
super().__init__() super().__init__(timeout=None)
dropdown = ClasseDropdown(role, jogador) self.grupo = grupo
dropdown.ctx_channel_id = ctx_channel_id self.add_item(ClasseDropdown(role, jogador, grupo))
self.add_item(dropdown)
import asyncio import asyncio
async def agendar_remocao_thread(thread: discord.Thread, data_str: str, hora_str: str): async def agendar_remocao_thread(thread: discord.Thread, data_str: str, hora_str: str):
try: try:
alvo = datetime.strptime(f"{data_str} {hora_str}", "%d/%m/%Y %H:%M") alvo = datetime.strptime(f"{data_str} {hora_str}", "%d/%m/%Y %H:%M")
agora = datetime.now() agora = datetime.now()
segundos_ate_apagar = (alvo + timedelta(minutes=30) - agora).total_seconds() segundos_ate_apagar = (alvo + timedelta(minutes=30) - agora).total_seconds()
if segundos_ate_apagar > 0: if segundos_ate_apagar > 0:
await asyncio.sleep(segundos_ate_apagar) await asyncio.sleep(segundos_ate_apagar)
await thread.delete() await thread.delete()
@@ -336,31 +403,81 @@ async def agendar_remocao_thread(thread: discord.Thread, data_str: str, hora_str
print(f"[INFO] Tempo já passou, thread '{thread.name}' não foi agendada.") print(f"[INFO] Tempo já passou, thread '{thread.name}' não foi agendada.")
except Exception as e: except Exception as e:
print(f"[ERRO] ao agendar remoção: {e}") print(f"[ERRO] ao agendar remoção: {e}")
@bot.command(name="criargrupo") @bot.command(name="criargrupo")
async def criar_grupo(ctx): async def criar_grupo(ctx):
global grupo_mensagem_id, inscritos, dungeon_escolhida, dificuldade_escolhida, data_formatada, hora_escolhida, alteracoes_feitas # Verificar se o comando foi usado em um local válido
inscritos = {"Tank": [], "Healer": [], "DPS": []} if not (isinstance(ctx.channel, discord.ForumChannel) or
classes_escolhidas.clear() (isinstance(ctx.channel, discord.Thread) and
dungeon_escolhida = DUNGEONS[2] isinstance(ctx.channel.parent, discord.ForumChannel))):
dificuldade_escolhida = "10" await ctx.send("❌ Este comando só pode ser usado em um canal de fórum ou em posts de fórum!", ephemeral=True)
data_formatada = "06/08/2025" return
hora_escolhida = "22:00"
alteracoes_feitas = {"dungeon": False, "dificuldade": False, "data": False} # Determinar o canal de fórum principal
embed = format_grupo_embed() forum_channel = ctx.channel if isinstance(ctx.channel, discord.ForumChannel) else ctx.channel.parent
mensagem = await ctx.send(embed=embed, view=DungeonView())
grupo_mensagem_id = mensagem.id # Criar novo grupo
if isinstance(ctx.channel, discord.Thread): novo_grupo = GrupoDungeon()
asyncio.create_task(agendar_remocao_thread(ctx.channel, data_formatada, hora_escolhida))
role_msg = await ctx.send( try:
"Escolher a tua **Role**:", # Criar novo post no fórum com tags apropriadas
view=RoleView(ctx.author.display_name, ctx.channel.id, grupo_mensagem_id) tags = []
dungeon_tag = discord.utils.get(forum_channel.available_tags, name=novo_grupo.dungeon_escolhida)
if dungeon_tag:
tags.append(dungeon_tag)
# Criar o post no fórum
thread, message = await forum_channel.create_thread(
name=f"{novo_grupo.dungeon_escolhida} - Key {novo_grupo.dificuldade_escolhida}",
content=f"Dungeon group created by {ctx.author.mention}",
embed=novo_grupo.format_grupo_embed(),
view=DungeonView(novo_grupo),
applied_tags=tags
) )
# Configurar o grupo
novo_grupo.thread = thread
novo_grupo.canal_id = thread.id
novo_grupo.mensagem_id = message.id
grupos_ativos[message.id] = novo_grupo
# Enviar mensagem para escolher role
await thread.send(
f"{ctx.author.mention}, escolhe a tua **Role**:",
view=RoleView(ctx.author.display_name, thread.id, message.id, novo_grupo)
)
# Agendar remoção automática
asyncio.create_task(
agendar_remocao_thread(
thread,
novo_grupo.data_formatada,
novo_grupo.hora_escolhida
)
)
# Confirmar criação
if ctx.channel.id != thread.id: # Só responde se não estiver já na thread criada
await ctx.send(f"✅ Grupo criado com sucesso! {thread.mention}", ephemeral=True)
except discord.HTTPException as e:
await ctx.send("❌ Erro ao criar post no fórum. Verifique as permissões do bot.", ephemeral=True)
print(f"Erro HTTP ao criar post: {e}")
except Exception as e:
await ctx.send("❌ Ocorreu um erro inesperado ao criar o grupo.", ephemeral=True)
print(f"Erro ao criar grupo: {e}")
if 'thread' in locals() and thread: # Limpeza em caso de erro
await thread.delete()
class RoleView(View): class RoleView(View):
def __init__(self, jogador, ctx_channel_id, role_msg_id): def __init__(self, jogador, ctx_channel_id, role_msg_id, grupo):
super().__init__(timeout=None) super().__init__(timeout=None)
self.add_item(RoleDropdown(jogador, ctx_channel_id, role_msg_id)) self.grupo = grupo
self.add_item(RoleDropdown(jogador, ctx_channel_id, role_msg_id, grupo))
@bot.event @bot.event
async def on_ready(): async def on_ready():
print(f"Bot ligado como {bot.user}") print(f"Bot ligado como {bot.user}")
bot.run(os.getenv("DISCORD_TOKEN"))
bot.run(os.getenv("DISCORD_TOKEN"))