我在斜杠中创建了一个不和谐机器人,但对于每个命令,我都必须指定服务器ID,这对于服务器间兼容性的所有内容都非常烦人(如果我不指定对象 guild=discord.Object(id=" Guild id 在这里”)该命令在服务器中不被识别为斜杠),这是代码:
main.py:
import os;os.system("cls||clear")
import discord, json
from utils import Invite, EmbedCreator, OPEN_TICKET
from discord import app_commands, Object
with open("config.json", "+r") as file: config = json.load(file)
intents = discord.Intents.all();client = discord.Client(intents=intents);tree = app_commands.CommandTree(client);TOKEN = config["TOKEN"];SERVER_ID = config["SERVER_ID"]
def is_admin(interaction): member = interaction.guild.get_member(interaction.user.id);return member.guild_permissions.administrator if member else False
@client.event
async def on_ready(): await tree.sync(guild=discord.Object(id=SERVER_ID))
@tree.command(name="invite", description=f"Avoir le lien pour inviter le bot !", guild=Object(id=SERVER_ID))
async def _(interaction):
try: await interaction.response.send_message(view=Invite(f"[En cliquant ici](https://discord.com/oauth2/authorize?client_id={client.user.id}&scope=applications.commands)"))
except Exception as e: await interaction.response.send_message(embed=discord.Embed(title="ERREUR INTERNE",description=str(e),color=discord.Color.red()))
@tree.command(name="ping",description="Voir le Ping du bot !", guild=Object(id=SERVER_ID))
async def _(interaction):embed = discord.Embed(title="Ping", description=f"╰┈➤ `{round(client.latency*1000)}`ms 🛰️", color=discord.Color.green());embed.set_footer(text="Made by ItsPyDevs");await interaction.response.send_message(embed=embed)
@tree.command(name="embed", description="Crée un Embed selont votre input !", guild=discord.Object(id=SERVER_ID))
async def _(interaction):await interaction.response.send_modal(EmbedCreator())
@tree.command(name='clear', description='Clear a specified number of messages in the channel.', guild=discord.Object(id=SERVER_ID))
async def _(interaction, amount: int):
if not is_admin(interaction): interaction.response.send_message("You do not have permission to use this command.");return;await interaction.channel.purge(limit=amount + 1)
@tree.command(name="ticket", description="Crée un Ticket selont votre input !", guild=Object(id=SERVER_ID))
async def _(interaction):
if is_admin: await interaction.response.send_message(embed=discord.Embed(title="Ouvrir un ticket", description="Click sur le bouton ci dessous pour ouvrir un ticket !", color=discord.Color.dark_blue()), view=OPEN_TICKET())
else: interaction.response.send_message(embed=discord.Embed(title="ERREUR INTERNE",description="Vous n'avez pas les permissions suffisantes pour crée cette interaction !",color=discord.Color))
client.run(TOKEN)
utils.py:
import discord
class Invite(discord.ui.View):
def __init__(self, inv=str):super().__init__();self.inv = inv
@discord.ui.button(label="Invite moi !", style=discord.ButtonStyle.danger,emoji="<:1_pepefuckyou:1223613141057929246>")
async def invitebutton(self, interaction: discord.Interaction, button: discord.ui.Button): await interaction.response.send_message(self.inv, ephemeral=True)
class EmbedCreator(discord.ui.Modal, title='Créateur d\'embed !'):
titre = discord.ui.TextInput(label='Titre de l\'embed', required=True)
description = discord.ui.TextInput(label='Description de l\'embed', style=discord.TextStyle.paragraph, required=True)
color = discord.ui.TextInput(label='couleur de l\'embed en RGB (0 0 0)', required=False)
field1 = discord.ui.TextInput(label='Nom du champ 1', required=False, style=discord.TextStyle.paragraph)
field1_value = discord.ui.TextInput(label='Valeur du champ 1', required=False, style=discord.TextStyle.paragraph)
async def on_submit(self, interaction: discord.Interaction):
embed = discord.Embed(title=self.titre.value, description=self.description.value)
if self.field1.value and self.field1_value.value: embed.add_field(name=self.field1, value=self.field1_value, inline=False)
if self.color and self.color.value:
color_values = self.color.value.split()
if len(color_values) == 3:
try:r, g, b = map(int, color_values);embed.color = discord.Color.from_rgb(r, g, b)
except ValueError:pass
await interaction.response.send_message(embed=embed)
class TICKET(discord.ui.Modal, title='Créateur de Ticket'):
titre = discord.ui.TextInput(label='Titre du problème', required=True)
description = discord.ui.TextInput(label='Description du Problème', style=discord.TextStyle.paragraph, required=True)
async def on_submit(self, interaction: discord.Interaction):
embed = discord.Embed(title=self.titre.value, description=self.description.value, color=discord.Color.from_rgb(0,0,255))
existing_ticket = discord.utils.get(interaction.guild.text_channels, name=f'ticket-{interaction.user.name}')
if existing_ticket:
await interaction.response.send_message("Vous ne pouvez créer qu'un seul ticket.", ephemeral=True)
return
ticket_channel = await interaction.guild.create_text_channel(name=f'ticket-{interaction.user.name}')
deleted_ping = await ticket_channel.send(f"<@{interaction.user.id}>")
await ticket_channel.send(embed=embed)
await deleted_ping.delete()
await interaction.response.send_message(f'Ticket créé avec succès dans {ticket_channel.mention}', ephemeral=True)
class OPEN_TICKET(discord.ui.View):
def __init__(self):
super().__init__()
@discord.ui.button(label="Ouvrir un ticket !", style=discord.ButtonStyle.primary,emoji="📩")
async def open_ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_modal(TICKET())
我尝试过类似的方法,但失败了:
for id in client.guild:
@tree.command(name="test", guild=discord.Object(id=id))
# rest of exemple command
感谢您对这篇文章的帮助/回复!
问题出在命令树同步上。让我简化问题。
@client.event
async def on_ready():
await tree.sync(guild=discord.Object(id=SERVER_ID))
@tree.command(guild=discord.Object(id=SERVER_ID))
async def guild_specific_command(interaction: discord.Interaction):
...
@tree.command()
async def global_command(interaction: discord.Interaction):
...
在这种情况下,只会同步
guild_specific_command
,因为您指定仅与 guild=discord.Object(id=SERVER_ID)
同步命令。
要解决此问题,请进行全局同步:
@client.event
async def on_ready():
await tree.sync()
这不仅应将服务器特定命令同步到服务器,还应将非服务器特定(全局)命令同步到所有服务器。