I have just started learning how to make bots using python in discord, and I have been following the tutorial of freecodecamp for it. But just around 26 minutes in, I already have a problem. I have done the part of adding the command ‘$inspire’ which should give a random quote every time anyone uses it. However, whenever I use the command, nothing comes up in discord, instead, I get an error in the console saying,
Traceback (most recent call last):
File "C:\Users\kabir\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\app_commands\tree.py", line 1089, in wrapper
await self._call(interaction)
File "C:\Users\kabir\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\app_commands\tree.py", line 1221, in _call
command, options = self._get_app_command_options(data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kabir\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\app_commands\tree.py", line 1125, in _get_app_command_options
raise CommandNotFound(name, parents)
discord.app_commands.errors.CommandNotFound: Application command 'list' not found
here is the code below
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
import asyncio
TOKEN = ''
GUILD_ID = '' # Replace with your guild ID
CHANNEL_NAME = 'website-status'
DEFAULT_WEBSITE_URL = '' # 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
@client.event
async def on_ready():
print(f"We have logged in as {client.user}")
await register_global_commands()
# 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 find_bot_owner():
app_info = await client.application_info()
return app_info.owner.id
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.'}
]
await client.http.bulk_upsert_global_commands(
client.user.id,
[
dict(name=command['name'], description=command['description'])
for command in commands_to_register
]
)
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()
# Sync commands
await asyncio.sleep(10) # Add a delay, adjust the duration as needed
await client.application_command_count()
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.")
await asyncio.sleep(10) # Add a delay, adjust the duration as needed
await client.application_command_count()
@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.")
await channel.send("The website request timed out. please try again later.")
except Exception as e:
logging.error(f"An error occurred in check_website: {e}")
await channel.send(f"An error occurred while checking the 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 Exception as e:
return f"An error occurred in quick_check: {e}"
client.run(TOKEN)