Discord bot / commands not showing up - python

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.

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.

Related

why is the FFmpegPCMAudio not playing?

in the following code of a discod bot (wrote in python) the FFmpegPCMAudio is not playing, the code and the mp3 audio are in the same folder, also, yesterday the bot worked well, but today when i write the command the bot enters the voice chat, but it doesn't play the mp3 audio, why?
import discord as ds
from discord.ext import commands
from discord import FFmpegPCMAudio
intents = ds.Intents.all()
bot = commands.Bot(command_prefix='$', intents = intents)
#bot.event
async def on_ready():
print('bot online.')
#bot.command(pass_context = True)
async def outro(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
voce = await channel.connect()
source = FFmpegPCMAudio('outro.mp3')
player = voce.play(source)
else:
await ctx.send('not in a voice chat')
#bot.command(pass_context = True)
async def esci(ctx):
if (ctx.voice_client):
await ctx.guild.voice_client.disconnect()
await ctx.send('adios #everyone')
else:
ctx.send('not in a voice chat')
bot.get_command('outro')
bot.get_command('esci')
bot.run('MTAwNDA0MjQ1MjcxMTI0NzkwNQ.GjUNFS.LecuRh7QuWxrdpK-lqyH3npMUzCiIyzehCQfjU')
If you're running this on Replit, it's because Replit no longer supports ffmpeg. If not, then you don't have it installed properly on your system.

Discord.py bot doesn't play wav/mp3 file

import discord
from discord.ext import commands
from discord import FFmpegPCMAudio
import requests
import json
from apikeys import *
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = '!', intents=intents)
#client.event
async def on_ready():
print("The bot is now ready for use!")
print("-----------------------------")
#client.command(pass_context = True)
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
voice = await channel.connect()
source = FFmpegPCMAudio("song.wav")
player = voice.play(source)
else:
await ctx.send("You are not in a voice channel")
#client.command(pass_context = True)
async def leave(ctx):
if (ctx.voice_client):
await ctx.guild.voice_client.disconnect()
await ctx.send("I left the voice channel")
else:
await ctx.send("I am not in a voice channel")
client.run(BOTTOKEN)
Hey! I have recently started watching a tutorial series.
It works for the tutorial maker, but doesn't for me.
The bot is able to join the voice channel the user is in, but never starts playing "song.wav".
Sadly Visual Studio Code also doesn't output any Error messages.
Does anyone know a solution?

Adding a queue command to discord.py music bot

I'm looking for a way to add the following to my music bot:
A queue function, allowing songs to be inputted while another plays. This would then go through the play function after the first song ends
Being able to display this queue
Removing songs from/changing positions of the songs in the queue
How would I go about doing this? Below is my code.
from discord.ext import commands
from dotenv import load_dotenv
from keep_alive import keep_alive
from youtube_dl import YoutubeDL
from discord.utils import get
load_dotenv()
TOKEN = os.getenv('TOKEN')
bot = commands.Bot(command_prefix='!', case_insensitive=True)
#bot.event
async def on_ready():
print(f'{bot.user} has successfully connected to Discord!')
#bot.command(aliases=['p'])
async def play(ctx, url: str = None):
YDL_OPTIONS = {'format': 'bestaudio/best', 'noplaylist':'True'}
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
voice = get(bot.voice_clients, guild=ctx.guild)
try:
channel = ctx.message.author.voice.channel
except AttributeError:
await ctx.send('Bruh, join a voice channel')
return None
if not voice:
await channel.connect()
await ctx.send("Music/Audio will begin shortly, unless no URL provided.")
voice = get(bot.voice_clients, guild=ctx.guild)
with YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
I_URL = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(I_URL, **FFMPEG_OPTIONS)
voice.play(source)
voice.is_playing()
await ctx.send("Playing audio.")
#bot.command()
async def pause(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.pause()
await ctx.send("Audio is paused.")
if voice.is_not_playing():
await ctx.send("Currently no audio is playing.")
#bot.command()
async def resume(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if voice.is_paused():
voice.resume()
await ctx.send("Resumed audio.")
if voice.is_not_paused():
await ctx.send("The audio is not paused.")
#bot.command()
async def stop(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
voice.stop()
await ctx.send("Stopped playback.")
#bot.command(aliases=['l'])
async def leave(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
await voice.disconnect()
await ctx.send("Left voice channel.")
keep_alive()
bot.run(TOKEN
first you need to create an empty queue outside your command
queues = {}
and a function to check if there's a song in queues it will play that song
#check queue
queues = {}
def check_queue(ctx, id):
if queues[id] !={}:
voice = ctx.guild.voice_client
source = queues[id].pop(0)
voice.play(source, after=lambda x=0: check_queue(ctx, ctx.message.guild.id))
and inside the play command create a function to add the next song to queue if a song is already being played and add the check queue function
if voice.is_playing():
guild_id = ctx.message.guild.id
if guild_id in queues:
queues[guild_id].append(source)
else:
queues[guild_id] = [source]
else:
voice.play(source, after=lambda x=0: check_queue(ctx, ctx.message.guild.id))
This way is to create a queue and play the next only and still cant display or change the queue
Need help Discord bot queue

How to I make a my discord bot join a voice channel *in a category*?

I'd like to write a bot with the ability to join; This is my code
import json
import discord
from discord.ext import commands
JSON_FILE = r"C:\JSON PATH"
bot = commands.Bot(command_prefix = "~")
with open(JSON_FILE, "r") as json_file:
TOKEN = json.load(json_file)["token"]
GUILD = json.load(json_file)["guild"]
bot = commands.Bot(command_prefix = "~")
#bot.event
async def on_ready():
print(f"{bot.user.name} launched and has arrived for further use")
#bot.command(name = "join")
async def join(ctx, voice_channel: commands.VoiceChannelConverter):
await voice_channel.connect()
await ctx.send(f"I have joined: {voice_channel}")
#bot.command(name = "leave")
async def leave(ctx):
server = ctx.message.server
voice_client = bot.voice_client_int(server)
await voice_client.disconnect()
bot.run(TOKEN)
It can join usual channels but it cannot join channels in categories. Any advice on how to do that?
Thank you in advance
The problem is probably, that you are using an outdated version of discord.py since you are using server, which is deprecated since v1.0, and not guild. If you update it, it will probably work, because it worked for me too when I tried it.
To code it to automatically join the voice channel of the user executing the command, just use ctx.author.voice.channel:
#bot.command(name = "join")
async def join(ctx, voice_channel: commands.VoiceChannelConverter):
if not ctx.author.voice is None:
await ctx.author.voice.channel.connect()
await ctx.send(f"I have joined your voice channel.")
else:
await ctx.send("You are not in a voice channel!")
References:
discord.Member.voice
Server is deprecated

Get the user voice channel id

I have this following function:
async def play_youtube_url(youtube_url):
channel = client.get_channel('VOICE_CHANNEL_ID')
if youtube_url.startswith('https://www.youtube.com/watch?v='):
voice = await client.join_voice_channel(channel)
player = await voice.create_ytdl_player(youtube_url)
player.start()
else:
return 'URL_ERROR'
My question is, how can I get the voice channel id of the user that typed the command. I know how to get the server id, but i can't find how to get the voice channel id in the documentation. Thanks!
Use command extension and context:
import discord
from discord.ext import commands
...
client = commands.Bot(command_prefix="!")
#client.command(pass_context=True)
async def play_youtube_url(self, ctx, youtube_url):
channel = ctx.message.author.voice.voice_channel
# http://discordpy.readthedocs.io/en/latest/api.html#discord.Member.voice
# http://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState.voice_channel
if youtube_url.startswith('https://www.youtube.com/watch?v='):
voice = await client.join_voice_channel(channel)
player = await voice.create_ytdl_player(youtube_url)
player.start()
else:
return 'URL_ERROR'
...
client.run("token")

Categories