忽略命令树和 discord.app_commands.errors.CommandNotFound 中的异常;Python Discord 机器人

Ignoring exception in command tree and discord.app_commands.errors.CommandNotFound; python discord bot

提问人:Sk Kabir 提问时间:11/17/2023 更新时间:11/17/2023 访问量:18

问:

我目前正在努力注册或调用 discord 斜杠命令。我已经成功登录了 discord 服务器,但这只是命令问题。我想不通。可以帮忙,不胜感激。这是下面的代码



import discord

from discord.ext import commands

import requests

import schedule

import time

import logging

from datetime import datetime, timedelta

from requests.exceptions import ReadTimeout

TOKEN = ''

GUILD_ID = ''

CHANNEL_NAME = 'website-status'

DEFAULT_WEBSITE_URL = 'http://novelfreak.com'  # Replace with your default website URL

# Set up logging with DEBUG level

logging.basicConfig(level=logging.DEBUG)

# Create an Intents object and enable necessary intents

intents = discord.Intents.default()

intents.messages = True  # Enables the message intent

intents.guilds = True    # Enables the guilds intent

intents.message_content = True  # Enables the message content intent

client = commands.Bot(command_prefix='/', intents=intents)

WEBSITE_URL = DEFAULT_WEBSITE_URL

# Dictionary to store command descriptions

command_descriptions = {

    'start': 'Start monitoring the website hourly.',

    'quick_check': 'Perform a quick check of the website status.',

    'list': 'Show all commands with their descriptions.',

    'website_url_change': 'Change the website URL.'

}

async def register_global_commands():

    """Register all global slash commands."""

    commands_to_register = [

        {'name': 'start', 'description': 'Start monitoring the website hourly.'},

        {'name': 'quick_check', 'description': 'Perform a quick check of the website status.'},

        {'name': 'list', 'description': 'Show all commands with their descriptions.'},

        {'name': 'website_url_change', 'description': 'Change the website URL.'}

    ]

    url = f"https://discord.com/api/v10/applications/{client.user.id}/commands"

    headers = {

        "Authorization": f"Bot {TOKEN}"

    }

    try:

        response = requests.put(url, headers=headers, json=commands_to_register)

        response.raise_for_status()

        logging.info("Global commands registered successfully.")

    except requests.HTTPError as e:

        logging.error(f"Failed to register global commands. Status code: {e.response.status_code}")

        logging.error(e.response.text)  # Log the response content for debugging

    except Exception as e:

        logging.error(f"An error occurred during global command registration: {e}")

@client.event

async def on_ready():

    logging.info(f'We have logged in as {client.user.name}')

    guild = discord.utils.get(client.guilds, id=int(GUILD_ID))

    # Find the "website-status" channel

    channel = discord.utils.get(guild.channels, name=CHANNEL_NAME)

    if channel is not None:

        # Schedule the website check every hour

        schedule.every().hour.at(':00').do(check_website, channel)

        # Register all commands globally

        await register_global_commands()

    else:

        # If "website-status" channel not found, find the user who added the bot and send a message

        owner_id = await find_bot_owner()

        owner = await client.fetch_user(owner_id)

        if owner:

            await owner.send("The 'website-status' channel is not available in the server. Please create the channel for website status updates.")

async def find_bot_owner():

    app_info = await client.application_info()

    return app_info.owner.id

@client.command(name='start', help='Start monitoring the website hourly.')

async def start(ctx):

    await ctx.send('Website status checks started.')

    while not client.is_closed():

        schedule.run_pending()

        time.sleep(1)

@client.command(name='quick_check', help='Perform a quick check of the website status.')

async def quick_check_command(ctx):

    result = await quick_check()

    await ctx.send(result)

@client.command(name='list', help='Show all commands with their descriptions.')

async def list_commands(ctx):

    commands_list = "\n".join([f'/{command} => {description}' for command, description in command_descriptions.items()])

    await ctx.send(f'Available commands:\n{commands_list}')

@client.command(name='website_url_change', help='Change the website URL.')

async def website_url_change(ctx, new_url):

    global WEBSITE_URL

    WEBSITE_URL = new_url

    await ctx.send(f"Website URL changed to: {new_url}")

async def check_website(channel):

    try:

        result = await quick_check()

        await channel.send(result)

    except ReadTimeout:

        logging.error("The website request timed out. Please try again later.")

    except Exception as e:

        logging.error(f"An error occurred in check_website: {e}")

async def quick_check():

    current_time = datetime.utcnow()

    try:

        response = requests.head(WEBSITE_URL, timeout=10)

        if response.status_code != 200:

            return f'Site is down. Time: {current_time.strftime("%I:%M %p")} GMT'

        else:

            return f'Site is up. Time: {current_time.strftime("%I:%M %p")} GMT'

    except ReadTimeout:

        return "The website request timed out. Please try again later."

    except requests.ConnectionError as e:

        return f'Site is down. Time: {current_time.strftime("%I:%M %p")} GMT. Error: {e}'

client.run(TOKE
N)

这是一个用于监控某个网站的 discord 机器人。无论是在线还是离线。

Python discord.py

评论


答: 暂无答案