import discord import youtube_dl from discord.ext import commands from youtube_search import YoutubeSearch from typing import Union
intents = discord.Intents.all()
#(commands) bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command() async def join(ctx): # Check if the user is in a voice channel if ctx.author.voice is None: await ctx.send("You need to be in a voice channel to use this command.") return
# Get the voice channel of the user
channel = ctx.author.voice.channel
# Connect to the voice channel
voice_client = await channel.connect()
await ctx.send(f"Joined {channel}")
@bot.command() async def search(ctx, *, query): # check if the user is in a voice channel if ctx.author.voice is None: await ctx.send("You need to be in a voice channel to use this command.") return
# no results
results = YoutubeSearch(query, max_results=5).to_dict()
if not results:
await ctx.send("No results found.")
return
for i, video in enumerate(results, 1):
await ctx.send(f"{i}. {video['title']}")
@bot.command() async def play(ctx, index_or_url: Union[int, str]):
if isinstance(index_or_url, int):
index = index_or_url
else:
# Handles the case where the argument is a URL so it wont give error
url = index_or_url
# more code for playing from URLs goes here
return
try:
index = int(index)
except ValueError:
await ctx.send("Invalid selection. Please provide a valid number.")
return
results = YoutubeSearch(ctx.message.content[7:], max_results=5).to_dict()
if not results or index < 1 or index > len(results):
await ctx.send("Invalid selection. Please choose a number within the provided range.")
return
selected_video = results[index - 1]
url = f"https://www.youtube.com/watch?v={selected_video['id']}"
# Join the voice channel if not already in
if ctx.voice_client is None:
if ctx.author.voice:
await ctx.author.voice.channel.connect()
else:
await ctx.send("You are not in a voice channel.")
return
# Plays audio
voice_client = ctx.voice_client
voice_client.play(discord.FFmpegPCMAudio(url), after=lambda e: print('done', e))
await ctx.send(f"Now playing: {selected_video['title']}")
@bot.command() async def pause(ctx): await ctx.send("Paused the playback.")
@bot.command() async def resume(ctx): await ctx.send("Resumed the playback.")
@bot.command() async def skip(ctx): await ctx.send("Skipped the current song.")
bot.run(