Getting discord.py to talk using tts - python

How would I get a my bot to use /tts in a vc?
Here is the code that I have so far. It is a loop of one word and I want to use tts in the voice channel I am in.
#client.command()
async def start(ctx):
global start_channel
start_channel = ctx.channel.id
reminder.start()
await ctx.send('Bot has Started')
#tasks.loop(minutes=10)
async def reminder():
channel = client.get_channel(int(start_channel))
await channel.send('/tts Honk!')
#client.command()
async def stop(ctx):
reminder.cancel()
await ctx.send('Bot has stopped')
#client.command()
async def join(ctx):
if ctx.author.voice is None:
await ctx.send("You're not in a voice channel")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_channel.move_to(voice_channel)

add tts as = True to allow it use tts commands through discord
#tasks.loop(minutes=10)
async def reminder():
channel = client.get_channel(int(start_channel))
await channel.send('Honk!', tts=True)

Related

Discord.py channel.connect() does not work

This is the command:
#commands.command(name="join", pass_context=True)
async def join(self, ctx):
print("1")
channel = ctx.message.author.voice.channel
print("2")
if not channel:
print("3")
await ctx.send("You're not connected to any voice channel !")
print("4")
else:
print("5")
voice = discord.utils.get(self.bot.voice_clients, guild=ctx.guild)
print("6")
if voice and voice.is_connected():
await voice.move_to(channel)
else:
print("7")
voice = await channel.connect()
print("8")
This is the main.py file:
import discord, os, asyncio
from discord.ext import commands
TOKEN = TOKEN
intents = discord.Intents.all()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents, help_command=None)
async def load():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
async def main():
await load()
await bot.start(TOKEN)
asyncio.run(main())
My bot is not connecting to any voice channel, Intents are all enabled, he got administrator and the voice channel is not private.
the output is this:
1
2
5
6
7
try just:
channel = ctx.author.voice.channel
instead of
channel = ctx.message.author.voice.channel

discord.ext.commands.errors.CommandNotFound: Command "play" is not found

I am having troubles gettimg my commands to work, it keeps telling me that they do not exist when they clearly do. I've been stumped on this for hours and can't figure out why its not working. I've tried doing commands.command() instead of #commands.command(), but no luck, i tried explicitly defining the name of the command #commands.command(name="play") but still no luck
import youtube_dl
import pafy
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
#bot.event
async def on_ready():
print(f"{bot.user.name} is ready.")
bot.run("....")
class Player(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.song_queue = {}
self.setup()
def setup(self):
for guild in self.bot.guilds:
self.song_queue[guild.id] = []
async def check_queue(self, ctx):
if len(self.song_queue[ctx.guild.id]) > 0:
await self.play_song(ctx, self.song_queue[ctx.guild.id][0])
self.song_queue[ctx.guild.id].pop(0)
async def search_song(self, amount, song, get_url=False):
info = await self.bot.loop.run_in_executor(None, lambda: youtube_dl.YoutubeDL({"format" : "bestaudio", "quiet" : True}).extract_info(f"ytsearch{amount}:{song}", download=False, ie_key="YoutubeSearch"))
if len(info["entries"]) == 0: return None
return [entry["webpage_url"] for entry in info["entries"]] if get_url else info
async def play_song(self, ctx, song):
url = pafy.new(song).getbestaudio().url
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url)), after=lambda error: self.bot.loop.create_task(self.check_queue(ctx)))
ctx.voice_client.source.volume = 0.5
#commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
return await ctx.send("You are not connected to a voice channel, please connect to the channel you want the bot to join.")
if ctx.voice_client is not None:
await ctx.voice_client.disconnect()
await ctx.author.voice.channel.connect()
#commands.command()
async def leave(self, ctx):
if ctx.voice_client is not None:
return await ctx.voice_client.disconnect()
await ctx.send("I am not connected to a voice channel.")
#commands.command(name="play")
async def play(self, ctx, *, song=None):
if song is None:
return await ctx.send("You must include a song to play.")
if ctx.voice_client is None:
return await ctx.send("I must be in a voice channel to play a song.")
# handle song where song isn't url
if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
await ctx.send("Searching for song, this may take a few seconds.")
result = await self.search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Sorry, I could not find the given song, try using my search command.")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(self.song_queue[ctx.guild.id])
if queue_len < 10:
self.song_queue[ctx.guild.id].append(song)
return await ctx.send(f"I am currently playing a song, this song has been added to the queue at position: {queue_len+1}.")
else:
return await ctx.send("Sorry, I can only queue up to 10 songs, please wait for the current song to finish.")
await self.play_song(ctx, song)
await ctx.send(f"Now playing: {song}")
#commands.command()
async def search(self, ctx, *, song=None):
if song is None: return await ctx.send("You forgot to include a song to search for.")
await ctx.send("Searching for song, this may take a few seconds.")
info = await self.search_song(5, song)
embed = discord.Embed(title=f"Results for '{song}':", description="*You can use these URL's to play an exact song if the one you want isn't the first result.*\n", colour=discord.Colour.red())
amount = 0
for entry in info["entries"]:
embed.description += f"[{entry['title']}]({entry['webpage_url']})\n"
amount += 1
embed.set_footer(text=f"Displaying the first {amount} results.")
await ctx.send(embed=embed)
#commands.command()
async def queue(self, ctx): # display the current guilds queue
if len(self.song_queue[ctx.guild.id]) == 0:
return await ctx.send("There are currently no songs in the queue.")
embed = discord.Embed(title="Song Queue", description="", colour=discord.Colour.dark_gold())
i = 1
for url in self.song_queue[ctx.guild.id]:
embed.description += f"{i}) {url}\n"
i += 1
embed.set_footer(text="Thanks for using me!")
await ctx.send(embed=embed)
#commands.command()
async def skip(self, ctx):
if ctx.voice_client is None:
return await ctx.send("I am not playing any song.")
if ctx.author.voice is None:
return await ctx.send("You are not connected to any voice channel.")
if ctx.author.voice.channel.id != ctx.voice_client.channel.id:
return await ctx.send("I am not currently playing any songs for you.")
poll = discord.Embed(title=f"Vote to Skip Song by - {ctx.author.name}#{ctx.author.discriminator}", description="**80% of the voice channel must vote to skip for it to pass.**", colour=discord.Colour.blue())
poll.add_field(name="Skip", value=":white_check_mark:")
poll.add_field(name="Stay", value=":no_entry_sign:")
poll.set_footer(text="Voting ends in 15 seconds.")
poll_msg = await ctx.send(embed=poll) # only returns temporary message, we need to get the cached message to get the reactions
poll_id = poll_msg.id
await poll_msg.add_reaction(u"\u2705") # yes
await poll_msg.add_reaction(u"\U0001F6AB") # no
await asyncio.sleep(15) # 15 seconds to vote
poll_msg = await ctx.channel.fetch_message(poll_id)
votes = {u"\u2705": 0, u"\U0001F6AB": 0}
reacted = []
for reaction in poll_msg.reactions:
if reaction.emoji in [u"\u2705", u"\U0001F6AB"]:
async for user in reaction.users():
if user.voice.channel.id == ctx.voice_client.channel.id and user.id not in reacted and not user.bot:
votes[reaction.emoji] += 1
reacted.append(user.id)
skip = False
if votes[u"\u2705"] > 0:
if votes[u"\U0001F6AB"] == 0 or votes[u"\u2705"] / (votes[u"\u2705"] + votes[u"\U0001F6AB"]) > 0.79: # 80% or higher
skip = True
embed = discord.Embed(title="Skip Successful", description="***Voting to skip the current song was succesful, skipping now.***", colour=discord.Colour.green())
if not skip:
embed = discord.Embed(title="Skip Failed", description="*Voting to skip the current song has failed.*\n\n**Voting failed, the vote requires at least 80% of the members to skip.**", colour=discord.Colour.red())
embed.set_footer(text="Voting has ended.")
await poll_msg.clear_reactions()
await poll_msg.edit(embed=embed)
if skip:
ctx.voice_client.stop()
#commands.command()
async def pause(self, ctx):
if ctx.voice_client.is_paused():
return await ctx.send("I am already paused.")
ctx.voice_client.pause()
await ctx.send("The current song has been paused.")
#commands.command()
async def resume(self, ctx):
if ctx.voice_client is None:
return await ctx.send("I am not connected to a voice channel.")
if not ctx.voice_client.is_paused():
return await ctx.send("I am already playing a song.")
ctx.voice_client.resume()
await ctx.send("The current song has been resumed.")
async def setup():
await bot.wait_until_ready()
bot.add_cog(Player(bot))
bot.loop.create_task(setup())
You can try replacing :
async def setup():
await bot.wait_until_ready()
bot.add_cog(Player(bot))
bot.loop.create_task(setup())
With just :
bot.add_cog(Player(bot))
Moreover, put you run statement after all setup operations, so you have :
# Cog declaration
bot.add_cog(Player(bot))
bot.run('....')
run() should be executed as last function because it starts bot and it runs until you stop bot.
And all code which you have after run() is executed after you stop bot.
bot.loop.create_task(setup())
bot.run(TOKEN)
#commands.command()
Write this down where you wrote it down.
#bot.command()
Because:
bot = commands.Bot(command_prefix="!", intents=intents)
Since you have assigned a "bot" variable here, the name of the variable is added first, and then the "command" is added.

How would I make it so that an individual person is the only one who can run a command with a discord bot?

I have a debug command for my bot that prints all of the current stacks that are running. Problem is it also prints my bot token. Rather than making it so it doesnt print my token, i'd rather make it so the debug command can only be ran by me.
my program:
import discord
from discord.ext import commands
from discord.ext.commands.core import command
import youtube_dl
import traceback
from tabulate import tabulate
table = [['Song', 'Queued by', 'Duration']]
class music(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def join(self, ctx):
await ctx.send("Hello!", ctx.author)
if ctx.author.voice is None:
await ctx.send("Join a voice channel please.")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
#commands.command()
async def disconnect(self, ctx):
await ctx.voice_client.disconnect()
#commands.command()
async def play(self, ctx, url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format':"bestaudio"}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
#commands.command()
async def pause(self, ctx):
await ctx.voice_client.pause()
await ctx.send("Music is paused.")
#commands.command()
async def online(self, ctx):
await ctx.send("The bot is online.")
#commands.command()
async def debug(self,ctx):
await ctx.send("You are: ")
await ctx.send(ctx.author)
await ctx.send("You are in the channel:")
if ctx.author.voice:
await ctx.send(ctx.author.voice.channel)
else:
await ctx.send("None")
await ctx.send("Stack: ")
for line in traceback.format_stack():
await ctx.send(line.strip())
#commands.command()
async def resume(self, ctx):
await ctx.voice_client.resume()
await ctx.send("Music has been resumed.")
#commands.command()
async def queue(self, ctx):
await ctx.send(tabulate(table, headers='firstrow'))
def setup(client):
client.add_cog(music(client))
You can for example return when the user's id that used the command is not yours:
#commands.command()
async def debug(self, ctx):
if ctx.author.id != "your id":
return
# The rest of your debug command

discord bot music with youtube dl not stuck at webpage downloading

So I'm trying to make a music bot which just joins,plays,stops and resume music. However my bot can join and leave a voice channel fine, however when i do my /play command it get stuck on [youtube] oCveByMXd_0: Downloading webpage (this is output in vscode) and then does nothing after. I put some print statement (which you can see in the code below and it prints 1 and 2 but NOT 3). Anyone had this issue?
MUSIC BOT FILE
import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def join(self, ctx):
if(ctx.author.voice is None):
await ctx.reply("*You're not in a voice channel.*")
voiceChannel = ctx.author.voice.channel
if(ctx.voice_client is None): # if bot is not in voice channel
await voiceChannel.connect()
else: # bot is in voice channel move it to new one
await ctx.voice_client.move_to(voiceChannel)
#commands.command()
async def leave(self, ctx):
await ctx.voice_client.disconnect()
#commands.command()
async def play(self,ctx, url:str = None):
if(url == None):
await ctx.reply("*Check your arguments!*\n```/play VIDEO_URL```")
else:
ctx.voice_client.stop() # stop current song
# FFMPEG handle streaming in discord, and has some standard options we need to include
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YTDL_OPTIONS = {"format":"bestaudio"}
vc = ctx.voice_client
# Create stream to play audio and then stream directly into vc
with youtube_dl.YoutubeDL(YTDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
print("1")
url2 = info["formats"][0]["url"]
print("2")
source = await discord.FFmpegOpusAudio.from_probe(url2,FFMPEG_OPTIONS)
print("3")
vc.play(source) # play the audio
await ctx.send(f"*Playing {info['title']} -* 🎵")
#commands.command()
async def pause(self, ctx):
await ctx.voice_client.pause()
await ctx.reply("*Paused -* ⏸️")
#commands.command()
async def resume(self, ctx):
await ctx.voice_client.resume()
await ctx.reply("*Resuming -* ▶️")
def setup(bot):
bot.add_cog(music(bot))
MAIN FILE
from discord.ext import commands
from dotenv import load_dotenv
from lxml import html
import youtube_dl
import requests
import random
import discord
import requests
import os
import music
# Load .env file
load_dotenv()
COGS = [music]
PREFIX = "/"
bot = commands.Bot(command_prefix=PREFIX, intents=discord.Intents.all())
for x in range(len(COGS)):
COGS[x].setup(bot)
# EVENTS #
#bot.event
async def on_ready():
await bot.get_channel(888736019590053898).send(f"We back online! All thanks to *sploosh* :D")
#bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
replies = ["Err is that even a command?", "Can you type bro?", "Yeah... thats not a command buddy.", "Sorry forgot you can't spell"]
await ctx.send(random.choice(replies))
#bot.event
async def on_message(message):
if str(message.channel) == "images-videos" and message.content != "":
await message.delete()
await bot.process_commands(message)
# COMMANDS #
#bot.command()
async def hello(ctx):
# Get a random fact
url = 'http://randomfactgenerator.net/'
page = requests.get(url)
tree = html.fromstring(page.content)
hr = str(tree.xpath('/html/body/div/div[4]/div[2]/text()'))
await ctx.reply("**Hello Bozo!**\n" + "*Random Fact : *" + hr[:-9]+"]")
#bot.command()
async def randomNum(ctx, start:int = None, end:int = None):
if(start == None or end == None):
await ctx.reply("*Check your arguments!*\n```/randomNum START_NUMBER END_NUMBER```")
else:
randNum = random.randint(start, end)
await ctx.reply(f"*{randNum}*")
#bot.command()
#commands.is_owner()
async def kick(ctx, member:discord.Member = None, *, reason="You smell bozo."):
if(member == None):
await ctx.reply("*Check your arguments!*\n```/kick #MEMBER REASON(optional)```")
elif ctx.author.id in (member.id, bot.user.id):
await ctx.reply("*You cant kick yourself/me you silly.*")
else:
await member.kick(reason=reason)
#bot.command()
#commands.is_owner()
async def ban(ctx, member:discord.Member = None, *, reason="Bye Bye! :D."):
if(member == None):
await ctx.reply("*Check your arguments!*\n```/kick #MEMBER REASON(optional)```")
elif ctx.author.id in (member.id, bot.user.id):
await ctx.reply("*You cant ban yourself/me you silly.*")
else:
await member.ban(reason=reason)
#bot.command()
#commands.is_owner()
async def close_bot(ctx):
replies = ["Well bye!", "Guess I go now?", "Please let me stay..."]
await ctx.send(random.choice(replies))
await bot.close()
if __name__ == "__main__":
bot.run(os.getenv("BOT_TOKEN"))
This is how my play music command is setup, and i know for sure it works and it seems like it should work for you too.
#commands.command()
async def play(self, ctx, *, song=None):
commandd = "play"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if song is None:
return await ctx.send("You must include a song to play.")
if ctx.voice_client is None:
return await ctx.send("I must be in a voice channel to play a song.")
# handle song where song isn't url
if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
await ctx.send("Searching for song, this may take a few seconds.")
result = await self.search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Sorry, I could not find the given song, try using my search command.")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(self.song_queue[ctx.guild.id])
if queue_len < 10:
self.song_queue[ctx.guild.id].append(song)
return await ctx.send(f"I am currently playing a song, this song has been added to the queue at position: {queue_len+1}.")
else:
return await ctx.send("Sorry, I can only queue up to 10 songs, please wait for the current song to finish.")
await self.play_song(ctx, song)
await ctx.send(f"Now playing: {song}")
this is some other things that you might need
import discord
from discord.ext import commands
from random import choice
import string
from discord.ext.commands.cooldowns import BucketType
import asyncio
import youtube_dl
import pafy
import datetime
from discord_slash import cog_ext, SlashContext
x = datetime.datetime.now()
from ult import *
class music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.song_queue = {}
self.setup()
def setup(self):
for guild in self.bot.guilds:
self.song_queue[guild.id] = []
async def check_queue(self, ctx):
if len(self.song_queue[ctx.guild.id]) > 0:
ctx.voice_client.stop()
await self.play_song(ctx, self.song_queue[ctx.guild.id][0])
self.song_queue[ctx.guild.id].pop(0)
async def search_song(self, amount, song, get_url=False):
info = await self.bot.loop.run_in_executor(None, lambda: youtube_dl.YoutubeDL({"format" : "bestaudio", "quiet" : True}).extract_info(f"ytsearch{amount}:{song}", download=False, ie_key="YoutubeSearch"))
if len(info["entries"]) == 0: return None
return [entry["webpage_url"] for entry in info["entries"]] if get_url else info
async def play_song(self, ctx, song):
url = pafy.new(song).getbestaudio().url
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url)), after=lambda error: self.bot.loop.create_task(self.check_queue(ctx)))
ctx.voice_client.source.volume = 0.5

Cogs double commands discord.py

Unknown Message Already playing audio. When I added to my code cogs it a bit broken him. Before I don't have any error, but now when I calling some command it calls twice. Also I'm getting error like Unknown Message, Already playing audio. etc. (twice) Also I pinned some tracebacks in the image. I'm new in discord.py so hope someone will help me, thank you !
main.py
import discord
import os
from discord.ext import commands
from cogs import embed_command, music
cogs = [embed_command, music]
client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
client.remove_command("help")
# for i in range(len(cogs)):
# cogs[i].setup(client)
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
else:
print(f'Unable to load {filename[:-3]}')
#client.event
async def on_ready():
print("\n\tOnline")
client.run('token')
in folder cogs: embed_command.py
import discord
import asyncio
from discord.ext import commands
class Embed(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_message(self, message):
if message.author == self.client.user:
return
await self.client.process_commands(message)
#commands.command()
async def embed(self, ctx):
embed_question = discord.Embed(
title="Enter a title of embed message: ",
description="||This request will be canceled in 10 seconds!||"
)
embed1 = await ctx.send(embed=embed_question)
try:
msg = await self.client.wait_for("message", check=lambda message: message.author == ctx.author, timeout=10)
msg_color = await self.client.wait_for("message", check=lambda message: message.author == ctx.author,
timeout=10)
r = msg_color.content.split(",", 3)[0]
g = msg_color.content.split(",", 3)[1]
b = msg_color.content.split(",", 3)[2]
embed_question_answer = discord.Embed(
title=msg.content.split("/", 3)[0],
description=msg.content.split("/", 3)[1],
color=discord.Color.from_rgb(int(r), int(g), int(b))
)
# embed_question_answer.add_field(name=msg.content.split("/", 3)[2], value=msg.content.split("/", 3)[3],
# inline=False)
await ctx.send(embed=embed_question_answer)
await msg.delete()
await ctx.message.delete()
await msg_color.delete()
await embed1.delete()
except asyncio.TimeoutError:
timeout_embed = discord.Embed(
title="",
description="***Отмена операции из-за долгого ожидания.***",
color=0x2f3136
)
await ctx.send(embed=timeout_embed, delete_after=5)
await embed1.delete()
await ctx.message.delete()
#commands.command()
async def clear(self, ctx, amount=5):
await ctx.message.delete()
await ctx.channel.purge(limit=amount)
embed_answer = discord.Embed(
title="",
description=f"***{amount} сообщений(-я, -е) было удалено.***",
color=0x2f3136
)
await ctx.send(embed=embed_answer, delete_after=5)
def setup(client):
client.add_cog(Embed(client))
in folder cogs: music.py:
import discord
from discord.ext import commands
import youtube_dl
class Music(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("Вы не находитесь в голосовом канале !")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
#commands.command()
async def disconnect(self, ctx):
await ctx.voice_client.disconnect()
#commands.command()
async def play(self, ctx, url):
if ctx.author.voice is None:
await ctx.send("Вы не находитесь в голосовом канале !")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
ctx.voice_client.stop()
FFMPEG_OPTIONS = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
'options': '-vn'
}
YDL_OPTIONS = {'format': 'bestaudio'}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
#commands.command()
async def pause(self, ctx):
ctx.voice_client.pause()
await ctx.send("Приастоновлено.")
#commands.command()
async def resume(self, ctx):
ctx.voice_client.resume()
await ctx.send("Возабновлено.")
def setup(client):
client.add_cog(Music(client))
add an exception so if someone tries command twice it will send them error.
try this:
#commands.command()
async def play(self, ctx, url):
try:
if ctx.author.voice is None:
await ctx.send("Вы не находитесь в голосовом канале !")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
ctx.voice_client.stop()
FFMPEG_OPTIONS = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
'options': '-vn'
}
YDL_OPTIONS = {'format': 'bestaudio'}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
except discord.ClientException:
await ctx.send("Already Playing Song")

Categories

Resources