-1

When I type / in my Discord server chat, the commands don't show up. I tried everything and don't know why it won't work. Here is the code of the bot:

import discord
import asyncio
from discord.ext import commands, tasks
import os
import random
from discord.ext import commands
from discord.utils import get
from discord import FFmpegPCMAudio
from discord import TextChannel
from youtube_dl import YoutubeDL
import sys
import spotipy
import spotipy.util as util
import youtube_dl

intents = discord.Intents.all()

bot = commands.Bot(command_prefix=".", intents=intents)

# Set the intents for the bot
intents.members = True
intents.presences = True
intents.typing = True
intents.message_content = True

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

audio_data = None

CLIENT_ID = "YOUR_ID"
CLIENT_SECRET = "SECRET"
REDIRECT_URI = "http://localhost:8888/callback"
USERNAME = "your-username"
scope = "user-read-private user-read-playback-state user-modify-playback-state"
token = util.prompt_for_user_token(USERNAME, scope, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI)
spotify_api = spotipy.Spotify(auth=token)

players = {}

@client.event  # check if bot is ready
async def on_ready():
    print('Bot online')


@client.command()
async def entra(ctx):
    channel = ctx.message.author.voice.channel
    voice = get(client.voice_clients, guild=ctx.guild)
    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()

@client.command(name='leave', aliases=['esci', 'quit'], pass_context=True)
async def leave(ctx):
    voice_client = ctx.voice_client

    if voice_client is not None:
        await voice_client.disconnect()
        await ctx.send('')
    else:
        await ctx.send('')

@client.command(name='avvia', aliases=['ascolta', 'play'], description="riproduce link youtube")
async def play(ctx, url):
    channel = ctx.message.author.voice.channel
    voice = get(client.voice_clients, guild=ctx.guild)
    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()
    YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
    FFMPEG_OPTIONS = {
        'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
    voice = get(client.voice_clients, guild=ctx.guild)

    # Check if the given url is a Spotify track or playlist
    if "open.spotify.com/track/" in url:
        # Extract the track id from the url
        track_id = url.split("/")[-1]
        # Get the track data from Spotify
        track_data = spotify_api.track(track_id)
        # Set the audio data to the track's preview url
        audio_data = track_data["preview_url"]
        await ctx.send("è possibile solo sentire i 30 secondi di preview di una canzone tramite link di spotify perche spotify è stronzo ")
    elif "open.spotify.com/playlist/" in url:
        # Extract the playlist id from the url
        playlist_id = url.split("/")[-1]
        # Get the playlist data from Spotify
        playlist_data = spotify_api.playlist(playlist_id)
        # Get the playlist's track data
        track_data = spotify_api.playlist_tracks(playlist_id)
        # Set the audio data to the first track's preview url
        audio_data = track_data[0]["preview_url"]
        await ctx.send(
            "è possibile solo sentire i 30 secondi di preview di una canzone tramite link di spotify perche spotify è stronzo ")
    elif "youtube.com" in url:
        # The url is not a Spotify track or playlist, so use YoutubeDL to extract the audio data
        with YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
        audio_data = info['url']
    else:
        await ctx.send('')
    if not voice.is_playing():
        # Play the audio data
        voice.play(FFmpegPCMAudio(audio_data, **FFMPEG_OPTIONS))
        voice.is_playing()
        if ctx.message.author == "Aq3ila":
            await ctx.send("musica di merda incoming ")
        else:
            await ctx.send("")
        return
    else:
        await ctx.send("impara ad'aspettare")

# command to resume voice if it is paused
@client.command()
async def riavvia(ctx):
    voice = get(client.voice_clients, guild=ctx.guild)

    if not voice.is_playing():
        voice.resume()
        await ctx.send('riavviando')

# command to pause voice if it is playing
@client.command()
async def pausa(ctx):
    voice = get(client.voice_clients, guild=ctx.guild)

    if voice.is_playing():
        voice.pause()
        await ctx.send('messo in pausa')

# command to stop voice
@client.command(name='ferma', aliases=['stop', 'annulla'], description="ferma la canzone in riproduzione")
async def stop(ctx):
    voice = get(client.voice_clients, guild=ctx.guild)

    if voice.is_playing():
        voice.stop()
        await ctx.send('')

client.run("YOUR_TOKEN")

I don't know why it won't work.

loopassembly
  • 2,653
  • 1
  • 15
  • 22
End3r
  • 1
  • 1
  • You have included the CLIENT_**SECRET** in your posted code. I recommend you to reset it at the Dashboard of your app, and copy the new one into your code. – Ximzend Jan 01 '23 at 10:25
  • You're not seeing any slash commands because you didn't make any... – stijndcl Jan 01 '23 at 18:57

1 Answers1

-1

First of all, you've included your Bot Token in the bot.run(). Delete that and reset your token right now.

Next: All of your commands are text commands, i.e. They're triggered when a message has the bot prefix in it.

Slash commands are integrated into the Discord client itself. They don't need a message to trigger them but can be run directly from the client.

I'll show you the method I use to make slash commands, but there are other ways to do this.

To make a slash command, first have this in your on_ready:

@bot.event
async def on_ready():
    #sync your commands and saves information about them in a var
    synced = await bot.tree.sync()
    #print how many commands were synced.
    print(f"Synced {len(synced)} command(s)")

Afterwards, create commands with the @bot.tree.command decorator.

For example:

@bot.tree.command(name="command_nam", description="command_description")
async def unique_command_name(interaction: discord.Interaction):
    #code here

Here, instead of Context or ctx, you're using the Interaction class. You can check out how Interactions work in the docs.

Edit: as stated in a comment down below, don't do this with bot's that have a lot of command that you restart often. It's just an alternative method for bot's that aren't general-purpose.

  • **Do not have this in your on_ready**! Auto-syncing is **terrible**, and especially in `on_ready`. The ratelimits for this are very harsh, and you don't want to get ratelimited to eternity after restarting your bot too often. Also, you should never make any API calls in `on_ready` because Discord can just disconnect your bot. **Syncing should be done in an owner-only message command!** You only have to sync after you make a change to your command tree, not every single time you start your bot... – stijndcl Jan 01 '23 at 18:54
  • Oh yes, should've made note of that. I rarely restart my bots, so never occurred. – Zaid Hussain Jan 02 '23 at 02:46
  • Your note is also just misleading. Don't do this, period. This isn't "an alternative method", it's bad practice that you should never be doing. – stijndcl Jan 02 '23 at 12:00