Discord.py Bot Not Playing music - python

Hi guys, for some reason my bot can actually join, but is not able to play audio.
Actually I am totally new to that and I was trying to get it to work like 2 hours and managed just to set up join but not play (or leave) command.
import os
import random
from dotenv import load_dotenv
import youtube_dl
import discord
from discord.ext import commands
from discord.ext import commands
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
players={}
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
#bot.command(name="Ja_som_to_nebol.")
async def sranda(ctx):
sranda_quotes = ["Not gonna lie, kinda sus",
("Not gonna lie, kinda sus"), ]
response = random.choice(sranda_quotes)
await ctx.send(response)
##bot.event
#async def on_command_error(ctx, error):
# if isinstance(error, commands.errors.CheckFailure):
# await ctx.send('You do not have the correct role for this command.')
#bot.command(name="join")
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
#bot.command(name="leave")
async def leave(ctx):
channel = ctx.author.voice.channel
await channel.disconnect()
#bot.command(name="play")
async def play(ctx, url):
guild = ctx.author.voice.channel
voice_client = discord.utils.find(lambda c: c.guild.id == server.id, client.voice_client)
player = await voice_client.create_ytdl_player(url)
players=[server.id] = player
player.start()
bot.run(TOKEN)

instead of playing like this use my code which I uses you must have FFmpeg installed.
#commands.command(name='play', aliases=['p'])
async def _play(self, ctx: commands.Context, *, search: str):
if not ctx.voice_state.voice:
await ctx.invoke(self._join)
async with ctx.typing():
try:
source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop)
except YTDLError as e:
await ctx.send('An error occurred while processing this request: {}'.format(str(e)))
else:
song = Song(source)
await ctx.voice_state.songs.put(song)
await ctx.send('Enqueued {}'.format(str(source)))
I am using some Cogs here you can edit to normal code by yourself.

Related

(discord.py) Why am I getting the error "command is not found"?

THIS QUESTION HAS BEEN SOLVED BY FURAS IN THE COMMENTS.
So I was following this tutorial on how to create a discord music bot like Rythm using discord.py. I had troubleshooted my code and fixed a few errors to do with coroutine.
EDIT: I have called the r function and now get this error upon running the code:
main.py:15: RuntimeWarning: coroutine 'r' was never awaited
r()
When I run the code everything boots up successfully until I try to use a command. If I put '#join' in the chat it should have joined the voice chat or said "You're not in a voice channel!". Instead I get this error:
2022-09-02 20:07:08 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "join" is not found
I have tried swapping out #commands.command for #client.command (whilst also defining client in music.py) but more of the same. Any help would be much appreciated.
I have two files, main.py and music.py.
MAIN.PY
import discord
from discord.ext import commands
import music
cogs = [music]
client = commands.Bot(command_prefix='#', intents=discord.Intents.all())
async def r():
for i in range(len(cogs)):
await cogs[i].setup(client)
r()
client.run(
"my token")
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("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_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("Paused")
#commands.command()
async def resume(self, ctx):
await ctx.voice_client.resume()
await ctx.send("Resumed")
async def setup(client):
await client.add_cog(music(client))
When you define async function like async def r() then you would have to run it await r(). Problem is that you can't run await outside functions. You would have to run it in some async function - but it make the same problem with running this async function.
You may try to run it in event on_ready() which is async function.
#client.event
async def on_ready():
for item in cogs:
await item.setup(client)

No error but it is not running HELP Discord.py

i want to make a discord bot but i cant run it.
idk what to do
it just runs
and no log
idk REALLY what to do
import discord
from discord.ext import commands
import os
import keep_alive
client = commands.Bot(command_prefix="!")
token = os.environ.get('Token')
GUILD = os.environ.get('Guild')
async def on_ready():
print(f'{client.user} is connected')
#client.command()
async def dm(ctx, member: discord.Member):
await ctx.send('what do u want to say bitch!')
def check(m):
return m.author.id == ctx.author.id
massage = await client.wait_for('massage', check=check)
await ctx.send(f'send massage to {member} ')
await member.send(f'{ctx.member.mention} has a massage for you: \n {massage}')
#client.event
async def on_member_join(member):
channel = discord.util.get(member.Guild, name='general')
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
keep_alive.keep_alive()
client.run(token)
client.close()
i dont know what to do anymore
I tried everything i could i ran it in pycharm
vscode
nothing works
There's a lot of errors on your code. so I fixed it
First thing is your client events, keep_alive, client.run, also why did you put client.close()
import os, discord
import keep_alive
from discord.ext import commands
client = commands.Bot(command_prefix="!")
token = os.environ.get('Token')
GUILD = os.environ.get('Guild')
#client.event # You need this event
async def on_ready():
print(f'{client.user} is connected')
"""
client.wait_for('massage') is invalid. Changed it into 'message'. Guess it is a typo.
You can replace this command with the new one below.
"""
#client.command()
async def dm(ctx, member: discord.Member):
await ctx.send('what do u want to say bitch!')
def check(m):
return m.author.id == ctx.author.id
massage = await client.wait_for('message', check=check)
await ctx.send(f'send massage to {member} ')
await member.send(f'{ctx.member.mention} has a massage for you: \n {massage}')
"""
I also moved this on_member_join event outside because it blocks it.
"""
#client.event
async def on_member_join(member):
channel = discord.util.get(member.Guild, name='general')
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
"""
I put the keep_alive call outside because the function blocks it in your code.
And also removed client.close() to prevent your bot from closing
"""
keep_alive.keep_alive()
client.run(token)
For the dm command. Here it is:
#client.command()
async def dm(ctx, member:discord.Member=None):
if member is None:
return
await ctx.send('Input your message:')
def check(m):
return m.author.id == ctx.author.id and m.content
msg = await client.wait_for('message', check=check) # waits for message
if msg:
await member.create_dm().send(str(msg.content)) # sends message to user
await ctx.send(f'Message has been sent to {member}\nContent: `{msg.content}`')
Sorry, I'm kinda bad at explaining things, also for the delay. I'm also beginner so really I'm sorry

Discord.py bot won't leave a voice chat

i'm currently using these commands to make my bot leave/join a vc. Joining works fine, but leaving won't work.
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("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)
#commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect()
Any help in understanding why would be really appreciated!
try with:
#commands.command()
async def disconnect(self,arg):
await arg.voice_client.disconnect(force=True)
and also replace channel name from ctx to arg cause it takes ctx as current channel (its not possible to type in voice channel afaik)

Need help discord bot command

I just started learning python recently and never coded a discord bot before. I've been trying to get the bot to connect to the voice or respond to ">hello", but it doesn't respond to my command and I don't know how to fix it. I'm using replit as hosting.
import discord
import os
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = '>', intents=intents)
#client.event
async def on_ready():
print('Log in as {0.user}'.format(client))
print('-------------------')
#client.command()
async def hello(ctx):
await ctx.send("Hello Im Deemo Bot")
#client.command(pass_context = True)
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
await channel.connect()
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('Deemo left voice')
else:
await ctx.send('Deemo is not in voice')
keep_alive()
client.run(os.environ['TOKEN'])

Discord bot commands not working (Python)

I am currently using python to code my first discord bot. While trying to write a command, I saw that I was unable to do this. This code:
import os
import random
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = 'NzQxMjA2OTQzMDc4ODA5NjEy.Xy0Mwg.Shkr9hHvkn-y4l5ye1yTHYM3rQo'
client = discord.Client()
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
pp = commands.Bot(command_prefix='!')
messages = ["hello", "hi", "how are you?"]
#pp.command(name = "swear")
async def swear(ctx):
await ctx.send(rand.choice(messages))
client.run(TOKEN)
is not outputting anything in the discord application when I type !swear. The bot is online, and working normally for other codes such as:
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
Here is the full code:
import discord
import os
import random
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = (##my token spelled out)
client = discord.Client()
#client.event
async def on_ready():
print('im in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hi there!')
elif message.content.startswith("Is Ethan's mum gay?"):
await message.channel.send("Yep, 100%!")
elif message.content.startswith("What are you doing?"):
await message.channel.send(f"Step {message.author}")
elif 'happy birthday' in message.content.lower():
await message.channel.send('Happy Birthday! 🎈🎉')
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
pp = commands.Bot(command_prefix='!')
messages = ["hello", "hi", "how are you?"]
#pp.command(name = "swear")
async def swear(ctx):
await ctx.send(rand.choice(messages))
client.run(TOKEN)
Does anyone know how I can fix my problem?
Client() and Bot() are two methods to create bot and using both at the same time is wrong.
Using Client() and Bot() you create two bots but they would need client.run(TOKEN) and pp.run(TOKEN) to run together - but it makes problem to start them at the same time and it can make conflict which one should get user message.
Bot() is extended version of Client() so you need only Bot() and use
#pp.event instead of #client.event
pp.run(TOKEN) instead of client.run(TOKEN)
pp.user instead of client.user
EDIT:
And you have to define pp before all functions. Like this
import random
from discord.ext import commands
TOKEN = 'TOKEN'
pp = commands.Bot(command_prefix='!')
#pp.event
async def on_ready():
print('im in as {}'.format(pp.user))
#pp.event
async def on_message(message):
if message.author == pp.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hi there!')
elif message.content.startswith("Is Ethan's mum gay?"):
await message.channel.send("Yep, 100%!")
elif message.content.startswith("What are you doing?"):
await message.channel.send(f"Step {message.author}")
elif 'happy birthday' in message.content.lower():
await message.channel.send('Happy Birthday! 🎈🎉')
#pp.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
messages = ["hello", "hi", "how are you?"]
#pp.command(name = "swear")
async def swear(ctx):
await ctx.send(rand.choice(messages))
pp.run(TOKEN)

Categories