Мой бот Discord не будет работать или взаимодействовать, если у участника нет прав администратораPython

Программы на Python
Ответить
Anonymous
 Мой бот Discord не будет работать или взаимодействовать, если у участника нет прав администратора

Сообщение Anonymous »

Я новичок в программировании и сейчас учусь. Недавно я завершил код бота Discord, предназначенного для команд создания профессий, связанных с World of Warcraft. Бот работает идеально, как задумано, за исключением одной проблемы: он отвечает только пользователям с правами администратора и не работает ни с кем другим.
Я дважды проверил права участника Discord, Я переделал токен своего бота, дважды проверил идентификатор своего сервера, полностью переработал свой код, чтобы предоставить все разрешения любому лицу, использующему его, и т. д.... ничего не сработало, и это по-прежнему работает только для офицеров, GM и Администраторы. Я приложил сюда свой код, чтобы вы могли просмотреть/ссылаться. Пожалуйста, помогите!
import os
import random
import dotenv
import discord
from discord.ext import commands
from discord import app_commands

dotenv.load_dotenv()

token = os.getenv("DISCORD_TOKEN")
guild_id = os.getenv("GUILD_ID")

if not token:
raise ValueError("DISCORD_TOKEN is not set in the .env file.")
if not guild_id:
raise ValueError("GUILD_ID is not set in the .env file.")

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

professions = {}
requests_data = {}

character_names = [
"Thrall", "Jaina Proudmoore", "Sylvanas Windrunner", "Illidan Stormrage", "Arthas Menethil",
"Tyrande Whisperwind", "Anduin Wrynn", "Vol'jin", "Bolvar Fordragon", "Kael'thas Sunstrider",
"Malfurion Stormrage", "Gul'dan", "Medivh", "Rexxar", "Kel'Thuzad", "Varian Wrynn",
"Grommash Hellscream", "Saurfang", "Baine Bloodhoof", "Lor'themar Theron", "Velen",
"Alexstrasza", "Ysera", "Nozdormu", "Deathwing", "Chromie", "Khadgar", "Turalyon",
"Alleria Windrunner", "Teron'khan", "Garrosh Hellscream", "Magni Bronzebeard",
"Gelbin Mekkatorque", "Moira Thaurissan", "Anub'arak", "Lady Vashj", "Archimonde",
"Kil'jaeden", "Cairne Bloodhoof", "Uther the Lightbringer", "Bolvar Fordragon",
"Darion Mograine", "Liadrin", "Kael'thas Sunstrider", "Valeera Sanguinar",
"Chen Stormstout", "Murozond", "Algalon the Observer", "Freya", "Thorim", "Hodir",
"Mimiron", "Loken", "Yogg-Saron", "C'Thun", "N'Zoth", "Argus the Unmaker",
"Mannoroth", "Ner'zhul", "Zul'jin", "Cho'gall", "Varok Saurfang", "Thassarian",
"Draka", "Durotan", "Nazgrim", "Aggra", "Eitrigg", "Fenris Wolfbrother",
"Halduron Brightwing", "Lady Liadrin", "Loramus Thalipedes", "Thal'kiel",
"Anveena Teague", "Tichondrius", "Xal'atath", "Zul", "Bwonsamdi", "Zul'jin",
"Arugal", "Dar'khan Drathir", "Halford Wyrmbane", "Lilian Voss", "Rhonin",
"Modgud", "Thoras Trollbane", "Aegwynn", "Med'an", "Drustvar", "Ashvane",
"Jastor Gallywix", "Gallywix", "Lord Godfrey", "Queen Azshara", "Helya",
"Ner'zhul", "Cho'gall", "Balnazzar", "Onyxia", "Ragnaros", "Shandris Feathermoon",
"Maraad", "Ner'zhul", "Archmage Vargoth", "Yrel", "Farseer Nobundo",
"Prince Erazmin", "Sky Admiral Rogers", "Benedictus", "Elisande",
"Blackhand", "Kilrogg Deadeye", "Frostwolf", "Vanessa VanCleef",
"Edwin VanCleef", "Valeera Sanguinar", "Hogger", "Loken", "Mimiron",
"Thorim", "Vol'jin", "Zul the Prophet", "Bwonsamdi", "Rokhan", "Akama",
"Nefarian", "Sinestra", "Deathbringer Saurfang", "Razorgore",
"Broxigar", "Talanji", "Draka", "Durotan", "Gazlowe"
]

def generate_request_id():
return random.choice(character_names)

@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
try:
await bot.tree.sync()
print("Global slash commands synced.")
except Exception as e:
print(f"Error syncing commands: {e}")

@bot.tree.command(name="myprofessions", description="See all registered professions.")
async def my_professions(interaction: discord.Interaction):
user_id = interaction.user.id
if user_id in professions and professions[user_id]:
profession_list = [prof.capitalize() for prof in professions[user_id]]
response = "**Your Registered Professions:** " + ", ".join(profession_list)
else:
response = "You have not registered any professions yet. Use `/registerprofession` to register one."
await interaction.response.send_message(response, ephemeral=True)

@bot.tree.command(name="registerprofession", description="Register your WoW profession (e.g., Alchemy, Blacksmithing).")
async def register_profession(interaction: discord.Interaction, profession: str):
user_id = interaction.user.id
profession = profession.lower()
if user_id not in professions:
professions[user_id] = []
if profession in professions[user_id]:
await interaction.response.send_message(
f"You are already registered for the profession **{profession.capitalize()}**.", ephemeral=True
)
return
professions[user_id].append(profession)
await interaction.response.send_message(
f"The profession **{profession.capitalize()}** has been registered for you.", ephemeral=True
)

@bot.tree.command(name="createrequest", description="Create a new WoW profession request.")
async def create_request(interaction: discord.Interaction, profession: str, details: str):
user_id = interaction.user.id
if user_id not in professions or not professions[user_id]:
await interaction.response.send_message(
"You need to register at least one profession before creating a request. Use `/registerprofession`.",
ephemeral=True
)
return
request_id = generate_request_id()
requests_data[request_id] = {
"creator": user_id,
"profession": profession.lower(),
"details": details,
"status": "OPEN",
"accepted_by": None,
}
target_channel_id = 1332989603358969897 # Replace with your channel ID
target_channel = bot.get_channel(target_channel_id)
if not target_channel:
await interaction.response.send_message("Target channel not found.", ephemeral=True)
return
await target_channel.send(
f"**New Crafting Request Created!**\n"
f"Request ID: **{request_id}**\n"
f"Creator: \n"
f"Profession: **{profession.capitalize()}**\n"
f"Details: {details}\n"
f"Status: **OPEN**"
)
await interaction.response.send_message(
f"Your request has been created and posted in the channel.", ephemeral=True
)

@bot.tree.command(name="acceptrequest", description="Accept a profession request by ID.")
async def accept_request(interaction: discord.Interaction, request_id: str):
if request_id not in requests_data:
await interaction.response.send_message("Request not found.", ephemeral=True)
return
request_info = requests_data[request_id]
user_id = interaction.user.id
if user_id not in professions or request_info["profession"] not in professions[user_id]:
await interaction.response.send_message(
f"You do not have the required profession **{request_info['profession'].capitalize()}** to accept this request.",
ephemeral=True
)
return
if request_info["status"] != "OPEN":
await interaction.response.send_message(f"Request **{request_id}** is not open.", ephemeral=True)
return
request_info["status"] = "ACCEPTED"
request_info["accepted_by"] = user_id
await interaction.response.send_message(
f"You have accepted request **{request_id}**. Please coordinate with !"
)

@bot.tree.command(name="closerequest", description="Close a profession request by ID.")
async def close_request(interaction: discord.Interaction, request_id: str):
if request_id not in requests_data:
await interaction.response.send_message("Request not found.", ephemeral=True)
return
request_info = requests_data[request_id]
user_id = interaction.user.id
if user_id not in [request_info["creator"], request_info["accepted_by"]]:
await interaction.response.send_message(
"You are not authorized to close this request.", ephemeral=True
)
return
request_info["status"] = "CLOSED"
target_channel_id = 1332989603358969897 # Replace with your channel ID
target_channel = bot.get_channel(target_channel_id)
if target_channel:
await target_channel.send(
f"**Crafting Request Closed!**\n"
f"Request ID: **{request_id}**\n"
f"Creator: \n"
f"Profession: **{request_info['profession'].capitalize()}**\n"
f"Details: {request_info['details']}\n"
f"Status: **CLOSED**"
)
await interaction.response.send_message(
f"Request **{request_id}** has been closed and updated in the channel.", ephemeral=True
)

@bot.tree.command(
name="registerprofessionfor",
description="Register a WoW profession for another user (Admin Only)."
)
@app_commands.describe(
user="The user to register the profession for.",
profession="The profession to register for the user."
)
async def register_profession_for(interaction: discord.Interaction, user: discord.User, profession: str):
if not interaction.user.guild_permissions.administrator:
await interaction.response.send_message(
"You must be an Administrator to register professions for others.", ephemeral=True
)
return
if user.id not in professions:
professions[user.id] = []
if profession.lower() in professions[user.id]:
await interaction.response.send_message(
f"{user.mention} is already registered for the profession **{profession.capitalize()}**.",
ephemeral=True
)
return
professions[user.id].append(profession.lower())
await interaction.response.send_message(
f"The profession **{profession.capitalize()}** has been registered for {user.mention}.", ephemeral=False
)

bot.run(token)



Подробнее здесь: https://stackoverflow.com/questions/793 ... ermissions
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»