AttributeError: 'FFmpegPCMAudio' object has no attribute 'start' - python

I'm trying to program a discord bot with discord.py, the main goal right now is to have my bot join a voice channel and play an audio file that's on my laptop.
#client.command()
async def sing(ctx):
user = ctx.author.voice
if user != None:
channel_chat = ctx.author.voice.channel
await channel_chat.connect()
player = discord.FFmpegPCMAudio(executable="C:/Path_Program/ffmpeg.exe", source=r"C:\Users\ialwa\Desktop\Misc\Music\Zelda's Lullaby Ancient Tune Hyrule Warriors Age of Calamity Soundtrack.mp3")
player.start()
else:
await ctx.send("Beep beep! (Be in a voice channel please!)")
This is the block of code that's suppose to play a file, the bot joins the channel just fine but fails to play audio. I do have ffmpeg-python installed and already tried installing ffmpeg but both or one at a time brings the same error.
The error itself in full is here
Ignoring exception in command sing:
Traceback (most recent call last):
File "C:\Users\ialwa\PycharmProjects\TY\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\ialwa\PycharmProjects\TY\main.py", line 29, in sing
player.start()
AttributeError: 'FFmpegPCMAudio' object has no attribute 'start'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ialwa\PycharmProjects\TY\venv\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ialwa\PycharmProjects\TY\venv\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ialwa\PycharmProjects\TY\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'FFmpegPCMAudio' object has no attribute 'start'
If anyone can help me understand what to do to fix this problem it would be appreciated!

discord.FFmpegPCMAudio isn't a player, it's just an audio source.
In order to play audio files, you need discord.VoiceClient.play:
#client.command()
async def sing(ctx):
user = ctx.author.voice
if user is not None:
channel = ctx.author.voice.channel
voice = await channel.connect()
voice.play(discord.FFmpegPCMAudio(executable="C:/Path_Program/ffmpeg.exe", source=r"C:\Users\ialwa\Desktop\Misc\Music\Zelda's Lullaby Ancient Tune Hyrule Warriors Age of Calamity Soundtrack.mp3"))
else:
await ctx.send("Beep beep! (Be in a voice channel please!)")

Related

My Discord bot won't send embeds from within a cog. (AttributeError: 'int' object has no attribute 'send')

So basically I'm trying to put the commands of my Discord bot into cogs. It loads the cog just fine. But when I run the command and the bot tries to send an embed to my logging channel it doesn't work.
Here is the code:
from discord.ext import commands
import datetime
from ruamel.yaml import YAML
yaml = YAML()
with open(r"C:\Users\Jea\Desktop\Yuna-Discord-Bot\config.yml", "r", encoding="utf-8") as file:
config = yaml.load(file)
bot = commands.Bot(command_prefix=config['Prefix'])
bot.debugchannel = config['Debug Channel ID']
bot.embed_color = discord.Color.from_rgb(
config['Embed Settings']['Color']['r'],
config['Embed Settings']['Color']['g'],
config['Embed Settings']['Color']['b'])
bot.footer = config['Embed Settings']['Footer']['Text']
bot.footerimg = config['Embed Settings']['Footer']['Icon URL']
class Testing(commands.Cog):
def __init__(self, bot):
self.bot = bot
#bot.command(name="ping",
aliases=["p"],
help="Check if the bot is online with a simple command")
async def ping(self, ctx):
embed = discord.Embed(title=f"Pinged {bot.user}", color=bot.embed_color, timestamp=datetime.datetime.now(datetime.timezone.utc))
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
embed.set_footer(text=bot.footer, icon_url=bot.footerimg)
await bot.debugchannel.send(embed=embed)
print("Sent and embed")
await ctx.message.add_reaction('✅')
print("Added a reaction to a message")
await ctx.send("Pong!")
print("Sent a message")
def setup(bot):
bot.add_cog(Testing(bot))
print("Loaded testing cog")
This is the error it gives:
Traceback (most recent call last):
File "C:\Users\Jea\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Jea\Desktop\Yuna-Discord-Bot\cogs\testing.py", line 34, in ping
await bot.debugchannel.send(embed=embed)
AttributeError: 'int' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Jea\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Jea\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Jea\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'send'
and I know it is the line await bot.debugchannel.send(embed=embed). Because when I removed it, the command worked just fine. however, I don't know what is causing it. any help would be appreciated!
bot.debugchannel just stores the id of the channel, not a discord.TextChannel object, and it therefore cannot be used to send messages. First, you need to get the channel itself from the id, which can be done using ctx.guild.get_channel(<id>)
So replace line 4 of the ping method with the following two lines:
debugchannel = ctx.guild.get_channel(bot.debugchannel)
await debugchannel.send(embed=embed)
You might also want to consider changing the variable name of bot.debugchannel to bot.debugchannel_id or the like, to make it clearer what is going on here.

Dictionary "Command' Object is not subscriptable

I am trying to make a bot that does a very simple task, it adds points to a member in the channel for the time the bot is live, in a temporary context. Trying to accomplish this without databases, because I don't need a permanent record of these points. I seem to have come very close to a solution combining a lot of references I've found over the internet. In essence, I create a dictionary based on the member ID and add 1 that key value pair whenever I use the give command, however, I keep getting the error listed below, I appreciate your time and please if someone can explain to me WHY this sub scriptable error happens with my code, Thank you and have a great day.
Adding my code below:
import discord
from discord.ext.commands import Bot
from collections import defaultdict
TOKEN = '#code would go here.'
bot = Bot('!')
points = defaultdict(int)
#bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
#bot.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.content == "hello":
# SENDS A MESSAGE TO THE CHANNEL.
await message.channel.send("FIX CONTEXT")
# INCLUDES THE COMMANDS FOR THE BOT. WITHOUT THIS LINE, YOU CANNOT TRIGGER YOUR COMMANDS.
await bot.process_commands(message)
#bot.command(pass_context=True)
async def give(ctx, member: discord.Member):
points[member.id] += 1
ctx.send("{} now has {} radiation".format(member.mention, points[member.id]))
#bot.command(pass_context=True)
async def points(ctx, member: discord.Member):
ctx.send("{} has {} radiation".format(member.mention, points[member.id]))
bot.run(TOKEN)
The main thing I don't understand about my code is the line Command raised an exception: TypeError: 'Command' object is not subscriptable
We have logged in as RadiationTracker#7562
AdamKostandy: !!give AdamKostandy#9900 (ffg-game-chat)
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "!give" is not found
AdamKostandy: !give AdamKostandy#9900 (ffg-game-chat)
Ignoring exception in command give:
Traceback (most recent call last):
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:/Users/Adam/Documents/GitHub/Discord-Bot/main.py", line 34, in give
points[member.id] += 1
TypeError: 'Command' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Command' object is not subscriptable
AdamKostandy: !points AdamKostandy#9900 (ffg-game-chat)
Ignoring exception in command points:
Traceback (most recent call last):
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:/Users/Adam/Documents/GitHub/Discord-Bot/main.py", line 39, in points
ctx.send("{} has {} radiation".format(member.mention, points[member.id]))
TypeError: 'Command' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Adam\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Command' object is not subscriptable

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Events' object has no attribute 'get_channel

I want to make it so that when my bot starts, it sends messages to certain chats. With normal power-up, everything is fine, and when I already use a special restart command, this error is issued. Here is the code:
#client.event
async def on_ready():
changeStatus.start()
kvuqqs = client.get_channel(906998823187017728)
librar = client.get_channel(906168716197232660)
await kvuqqs.send('Айоу! Бот был включен. \nК сожалению, на данный момент обновлений нет. \n`l.хелп`')
await librar.send(embed=discord.Embed(title='Бот был включен!', description='Версия бота на данный момент: 2.0.1.', color=random.choice(colors)))
And also a full error:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Events' object has no attribute 'get_channel'
bruh
to get a channel from id you need a guild
example :-
guild = client.get_guild(ID)
channel = guild.get_channel(ID)
and
Getting a channel or guild by id is privileged intent
Add this code in your bot (if you haven't)
intents = discord.Intents().all()
client = commands.Bot(command_prefix='prefix', intents=intents)
You have to turn these intents on in Discord Dev Portal
You can read more about intents here :- https://discordpy.readthedocs.io/en/stable/intents.html

AttributeError: 'NoneType' object has no attribute 'channel' discord.py

My code:
#bot.command(aliases=['p', 'pla'])
async def play(ctx, url: str = 'http://stream.radioparadise.com/rock-128'):
channel = ctx.message.author.voice.channel
global player
try:
player = await channel.connect()
except:
pass
player.play(FFmpegPCMAudio('http://stream.radioparadise.com/rock-128'))
The error:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'`
I try to make that the bot play a radio in the voice channel, but don't recognize the attribute channel. I'm using Zorin OS based on ubuntu.
Here ctx.message.author.voice is returning None, meaning the author is not connected to any voice channel. To solve this you need to check if voice returned None or not
#bot.command(aliases=['p', 'pla'])
async def play(ctx, url: str = 'http://stream.radioparadise.com/rock-128'):
voice = ctx.message.author.voice
if not voice:
return await ctx.send("Author is not connected to any voice channel")
channel = voice.channel
global player
try:
player = await channel.connect()
except:
pass
player.play(FFmpegPCMAudio('http://stream.radioparadise.com/rock-128'))

I can't connect my Discord Python BOT to a voice channel, why?

I've tried to connect my BOT to a voice channel to do a music BOT, but I don't know why, it doesn't work. Can you help me please ? I've already install PyNaCl, and it still doesn't working...
This is the code of the command :
#bot.command()
async def join(ctx):
channel = get(ctx.guild.voice_channels, id=722012728176410694)
await channel.connect()
And here is the error that is printed :
Ignoring exception in command join:
Traceback (most recent call last):
File "C:\Users\Maxence\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Maxence\Documents\Programmation\Python\Discord\Music BOT\main.py", line 44, in join
await channel.connect()
File "C:\Users\Maxence\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\abc.py", line 1076, in connect
voice = VoiceClient(state=state, timeout=timeout, channel=self)
File "C:\Users\Maxence\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\voice_client.py", line 91, in __init__
raise RuntimeError("PyNaCl library needed in order to use voice")
RuntimeError: PyNaCl library needed in order to use voice
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Maxence\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Maxence\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Maxence\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice
I really need help I found no answers...
If you are using an IDE like Pycharm you should try to add PyNaCl mannualy to the project interpreter
Why dont you use the ctx.author.voice.channel.connect() to connect the bot to the user's current voice channel?
#commands.command()
async def entrar(ctx):
canal = ctx.author.voice.channel
#I suggest make it global so other commands can acess it
global voice_client
voice_client = await canal.connect()
My full music cog https://github.com/Voz-bonita/Discord-Bot/blob/master/Music%20extension.py
OK I found how to do. I need to open the cmd, then type py -3 -m pip install pynacl and that's all.
Before, I saw many other commands that's seems to this, but this one is the correct one.

Categories