无法使discord.py中的应用程序命令出现在discord中

问题描述 投票:0回答:1

一直在混乱地制作这个不和谐的机器人,我希望组织命令,因为我计划添加许多命令,我正在努力使 cogs py 文件加载不和谐中的应用程序命令,观看了一堆教程一步一步,但无法弄清楚。当机器人运行时,命令ratio、castle_cost和ta_cost应该在discord中显示为斜线命令,而在cog/calculations.py中是目标

main.py

import discord
from discord.ext import commands

import os
from dotenv import load_dotenv

import locale
from datetime import datetime, timedelta
import pytz

# Load environment variables from the .env file
load_dotenv()

# Set up Discord intents
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)


# Event handler for when the bot is ready
@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')
    await bot.tree.sync()  # Sync application commands globally
    print("Application commands synced globally.")
    await bot.load_extension('cogs.calculations')



# Set the timezone for CST
cst = pytz.timezone('America/Chicago')

# Define the reset intervals
colonies_reset_interval = timedelta(days=10)
hell_mode_reset_interval = timedelta(days=7)
guild_reset_interval = timedelta(days=5)

# Set the last reset times in CST
colonies_last_reset_time = cst.localize(datetime(2024, 4, 20, 9, 55))  # Initial reset time
hell_mode_last_reset_time = cst.localize(datetime(2024, 4, 21, 9, 50))  # Initial reset time
guild_last_reset_time = cst.localize(datetime(2024, 4, 25, 9, 55))  # Initial reset time

# Command to show the time until the next reset for various events
@bot.tree.command(name="reset", description="Shows the time until the next reset for various events")
async def reset(interaction: discord.Interaction):
    now = datetime.now(cst)  # Get the current time in CST
    embed = discord.Embed(title="Time Until Next Reset", color=discord.Color.red())

    # Calculate the time until the next reset
    colonies_next_reset = calculate_next_reset(now, colonies_last_reset_time, colonies_reset_interval)
    hell_mode_next_reset = calculate_next_reset(now, hell_mode_last_reset_time, hell_mode_reset_interval)
    guild_next_reset = calculate_next_reset(now, guild_last_reset_time, guild_reset_interval)

    # Format the time until the next reset
    colonies_formatted = format_time_remaining(colonies_next_reset - now)
    hell_mode_formatted = format_time_remaining(hell_mode_next_reset - now)
    guild_formatted = format_time_remaining(guild_next_reset - now)

    # Add fields to the embed with Discord timestamps
    embed.add_field(name="Colonies Reset", value=f"<t:{int(colonies_last_reset_time.timestamp())}:F> {colonies_formatted}", inline=False)
    embed.add_field(name="Hell Mode Reset", value=f"<t:{int(hell_mode_last_reset_time.timestamp())}:F> {hell_mode_formatted}", inline=False)
    embed.add_field(name="Guild Reset", value=f"<t:{int(guild_last_reset_time.timestamp())}:F> {guild_formatted}", inline=False)

    await interaction.response.send_message(embed=embed)

# Helper function to calculate the time elapsed since the last reset
def calculate_time_elapsed(now, last_reset_time, reset_interval):
    time_since_last_reset = now - last_reset_time
    resets_since_last = time_since_last_reset // reset_interval
    time_elapsed = time_since_last_reset - (resets_since_last * reset_interval)
    return time_elapsed

# Helper function to format the time elapsed
def format_time_elapsed(time_elapsed):
    hours, remainder = divmod(time_elapsed.seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    return f"{hours:02d}:{minutes:02d} PM" if hours < 12 else f"{hours-12:02d}:{minutes:02d} AM"

# Helper function to calculate the time until the next reset
def calculate_next_reset(now, last_reset_time, reset_interval):
    time_since_last_reset = now - last_reset_time
    resets_since_last = time_since_last_reset // reset_interval
    next_reset_time = last_reset_time + (resets_since_last + 1) * reset_interval
    return next_reset_time

# Helper function to format the time remaining until the next reset
def format_time_remaining(time_remaining):
    days = time_remaining.days
    hours, remainder = divmod(time_remaining.seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    return f"{days} Days, {hours} Hours, {minutes} Minutes"
    


@bot.tree.command(name="sync", description="Sync the application commands")
async def sync(interaction: discord.Interaction):
    print(f'Syncing for {interaction.guild.name}')
    await interaction.response.send_message(f"Syncing application commands...", ephemeral=True)
    synced = await bot.tree.sync(guild=interaction.guild)
    await interaction.edit_original_response(content=f"Synced {len(synced)} commands.")


bot.run(os.getenv('Discord_Token'))

cogs/calculations.py

import discord
from discord.ext import commands
from discord import app_commands
from typing import Optional
import locale

class calculationsCog(commands.Cog, name="calculations"):
    """A collection of utility commands."""

    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name="ratio", description="finds a hero to wave ratio")
    async def ratio(self, interaction: discord.Interaction, hero: int, wave: int):
        if hero <= 0 or wave <= 0:
            await interaction.response.send_message("Hero and wave values must be positive integers.", ephemeral=True)
            return

        hero_ratio = hero / wave
        embed = discord.Embed(title="Hero to Wave Ratio", color=discord.Color.red())
        embed.add_field(name="Ratio", value=f"{hero_ratio:.2f}")
        await interaction.response.send_message(embed=embed)

    @app_commands.command(name="castle_cost", description="finds the gold cost of one castle level to another")
    @app_commands.describe(
        castle_level="The current castle level",
        castle_target_level="The desired castle level"
    )
    async def castle_cost(self, interaction: discord.Interaction, castle_level: int, castle_target_level: int):
        if castle_level <= 0 or castle_target_level <= 0 or castle_level > castle_target_level:
            await interaction.response.send_message("Castle levels must be positive integers, and the target level must be higher than the current level.", ephemeral=True)
            return

        castle_gold_cost = (castle_level + castle_target_level) * (castle_target_level - castle_level + 1) * 2500 // 2
        formatted_cost = format_number(castle_gold_cost)
        embed = discord.Embed(title="Castle Upgrade Cost", color=discord.Color.red())
        embed.add_field(name="Cost", value=formatted_cost)
        await interaction.response.send_message(embed=embed)

    @app_commands.command(name="ta_cost", description="finds the gold cost of one ta level to another")
    @app_commands.describe(
        ta_level="The current TA level",
        ta_target_level="The desired TA level"
    )
    async def ta_cost(self, interaction: discord.Interaction, ta_level: int, ta_target_level: int):
        if ta_level <= 0 or ta_target_level <= 0 or ta_level > ta_target_level:
            await interaction.response.send_message("TA levels must be positive integers, and the target level must be higher than the current level.", ephemeral=True)
            return

        ta_level_cost = (0.5 * ((ta_level * 1000) * ta_level)) - (44500 * ta_level)
        ta_target_cost = (0.5 * ((ta_target_level * 1000) * ta_target_level)) - (44500 * ta_target_level)
        ta_gold_cost = ta_target_cost - ta_level_cost
        formatted_cost = format_number(ta_gold_cost)
        embed = discord.Embed(title="TA Upgrade Cost", color=discord.Color.red())
        embed.add_field(name="Cost", value=formatted_cost)
        await interaction.response.send_message(embed=embed)

def format_number(number):
    # Set the locale for formatting numbers with commas
    locale.setlocale(locale.LC_ALL, '')
    formatted_number = locale.format_string('%d', number, grouping=True)
    if number >= 1000000000000:
        # Format numbers with 'T' suffix for trillions
        suffix = f" ({locale.format_string('%0.2fT', number / 1000000000000, grouping=True)} gold)"
    elif number >= 1000000000:
        # Format numbers with 'B' suffix for billions
        suffix = f" ({locale.format_string('%0.2fB', number / 1000000000, grouping=True)} gold)"
    elif number >= 1000000:
        # Format numbers with 'M' suffix for millions
        suffix = f" ({locale.format_string('%0.2fM', number / 1000000, grouping=True)} gold)"
    else:
        # No suffix for smaller numbers
        suffix = ""
    return formatted_number + suffix

async def setup(bot):
    await bot.add_cog(calculationsCog(bot))
discord discord.py
1个回答
0
投票

我注意到这个函数有一个不一致的地方。您在加载 Cog 之前同步命令,这意味着 Cog 中的现有命令永远不会同步。加载 cog 后测试同步命令。

# Event handler for when the bot is ready
@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')
    await bot.tree.sync()  # Sync application commands globally
    print("Application commands synced globally.")
    await bot.load_extension('cogs.calculations')

async def on_ready():
    await bot.load_extension('cogs.calculations')
    print(f'We have logged in as {bot.user}')
    await bot.tree.sync()  # Sync application commands globally
    print("Application commands synced globally.")

© www.soinside.com 2019 - 2024. All rights reserved.