Python Discord Bot isn't joinig voice channel - python

import discord
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print("I'm logged in as {0.user}.".format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("!test"):
await message.channel.send("Test passed successfully!")
#commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("You are not in a voice channel")
voice_channel = client.get_channel(ctx.author.voice.channel.id)
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
await ctx.send("idk")
#commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect()
The bot doesn't join I don't know what I did wrong. It should only join my voice channel nothing else. I watched this Tutorial but as I said it didn't worked.

You're mixing metaphors a little: your on_message is a plain function:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("!test"):
await message.channel.send("Test passed successfully!")
Whereas your join and disconnect functions look as if they belong in a class (note the self argument):
#commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("You are not in a voice channel")
voice_channel = client.get_channel(ctx.author.voice.channel.id)
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
await ctx.send("idk")
#commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect()
If you remove the self argument from those functions, you should be able to get it working:
async def join(ctx):
if ctx.author.voice is None:
await ctx.send("You are not in a voice channel")
voice_channel = client.get_channel(ctx.author.voice.channel.id)
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
await ctx.send("idk")
#commands.command()
async def disconnect(ctx):
await ctx.voice_client.disconnect()

Related

Empty message by discord bot

i'm trying to make embed and my bot is sending empty message
I have token, i just deleted him from this message.
And with deleted 'help' don't working too.
bot = commands.Bot (command_prefix=config['prefix'], intents=intents, help_command=None)
bot.remove_command('help')
#bot.event
async def on_ready():
print('Bot connected')
#bot.command()
async def info(ctx):
embed = discord.Embed(
title='title',
description='description',
colour=discord.Colour.dark_gold()
)
await ctx.send(embed=embed)
#bot.event
async def on_message(ctx):
if ctx.author != bot.user:
if filter_mata(ctx.content) == True:
await ctx.delete()
print(f'message {ctx.id} by {ctx.author} deleted')
await bot.process_commands(ctx)
bot.run (config['token'])

Why doesn't my bot doesn't accept my commands?

I'm having issues building my music bot. It's accepting any of my commands.
I tried to making the Bot join the voice chat, and subsequently play music, but it doesn't work for some reason.
Here's my code:
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
bot = commands.Bot(command_prefix='.', description="L's very own Jukebox", intents=discord.Intents.all())
#bot.event
async def on_ready():
print(f"Logged in as {bot.user} ({bot.user.id})")
print("-----")
async def on_load():
print(f"Starting to load cogs...")
for cog in os.listdir("cog"):
if cog.endswith(".py"):
try:
await bot.load_extension(f"cog.{cog.strip('py')}")
print("{cog} cog has been loaded")
except Exception as e:
print(e)
print("{cog} cog can't be loaded.")
load_dotenv('development.env')
on_ready()
on_load()
TOKEN = os.getenv('TOKEN')
bot.run(TOKEN)
Here's also the code for the cog I'm using. It's under the 'cog' folder:
import youtube_dl
from discord.ext import commands
import YTDLSource
youtube_dl.utils.bug_reports_message = lambda: ''
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def ping(self, ctx):
await ctx.send('Ping!')
#commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("You're currently 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):
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop)
ctx.voice_client.play(player, after=lambda e: ctx.send(f'Player error: {e}') if e else None)
await ctx.send(f'Now playing {player.title}')
#commands.command()
async def stream(self, ctx, *, url):
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)
await ctx.send(f'Now playing: {player.title}')
#commands.command()
async def volume(self, ctx, volume: int):
if ctx.voice_client is None:
return await ctx.send("Not connected to a voice channel.")
ctx.voice_client.source.volume = volume / 100
await ctx.send(f"Changed volume to {volume}%")
#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("Resuming ▶")
#commands.command()
async def stop(self, ctx):
await ctx.voice_client.disconnect()
#play.before_invoke
#stream.before_invoke
async def ensure_voice(self, ctx):
if ctx.voice_client is None:
if ctx.author.voice:
await ctx.author.voice.channel.connect()
else:
await ctx.send("You aren't connected to a voice channel!")
raise commands.CommandError("Author is not connected to a voice channel.")
elif ctx.voice_client.is_playing():
ctx.voice_client.stop()
def setup(client):
client.add_cog(Music(client))
Anything that can help me fix my bot would help.
Thanks in advance.
Thanks to you guys, you helped me find the issue. As it turns out, I don't need await in on_ready() method. I also fixed the on_ready() method overall.
There was also a typo in the code. I wrote py, instead of .py for the bot.load_extension(f"cog.{cog.strip('.py')}").
So the code for the method looks like this:
#bot.event
async def on_ready():
print(f"Logged in as {bot.user} ({bot.user.id})")
print("-----")
print(f"Starting to load cogs...")
for cog in os.listdir("cog"):
if cog.endswith(".py"):
try:
bot.load_extension(f"cog.{cog.strip('.py')}")
print("{cog} cog has been loaded")
except Exception as e:
print(e)
print("{cog} cog can't be loaded.")

I am trying to make a bot that plays an mp3 file by a command but it doesn't work with no error

I made so it connects to the voice channel by the command .join and it supposed to play a sound that i saved. This is made for a voice channel with chill music so that they don't have to copy and paste a YouTube link. I am using python 3.9
import discord
from discord.ext import commands
bot = discord.Client()
bot = commands.Bot(command_prefix=".")
#bot.command()
async def join(ctx):
if ctx.author.voice is None:
await ctx.send("You are not in a voice channel")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)
audio_source = discord.FFmpegPCMAudio('music.mp3')
if not voice_client.is_playing():
voice_client.play(audio_source, after=None)
else:
await ctx.voice_client.move_to(voice_channel)
bot.run("token")
Try this instead:
import discord
from discord.ext import commands
from youtube_dl import YoutubeDL
bot = discord.Client()
bot = commands.Bot(command_prefix=".")
#bot.command()
async def join(ctx):
if ctx.author.voice is None:
await ctx.send("You are not in a voice channel")
return
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)
audio_source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio('music.mp3'))
if not ctx.voice_client.is_playing():
ctx.voice_client.play(audio_source, after=lambda e: print('Player error: %s' % e) if e else None)
bot.run("token")

Make discord bot connect to vc with deafen

I use voice = await message.author.voice.channel.connect() to connect my bot to voice channel and i want the bot connect and deafen himself
All my code:
client = discord.Client()
#client.event
async def on_ready():
print("Bot is ready!")
#client.event
async def on_message(message):
arg = message.content.split(' ')
if message.content.startswith('>play'):
voice = await message.author.voice.channel.connect()
voice.play(discord.FFmpegPCMAudio(YouTube(arg[1]).streams.first().download()))
await message.guild.change_voice_state(channel=voice, self_mute=True, self_deaf=False)
client.run('my token')
Use await message.guild.change_voice_state(channel=voice, self_mute=False, self_deaf=True)
Copy-paste this code that I wrote after looking at your comments:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='>')
#bot.event
async def on_ready():
print("Bot is ready!")
#bot.event
async def on_message(message):
if message.author == bot.user:
return
await bot.process_commands(message)
#bot.command()
async def join(ctx):
if ctx.author.voice is None or ctx.author.voice.channel is None:
return await ctx.send('You need to be in a voice channel to use this command!')
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
vc = await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
vc = ctx.voice_client
vc.play(discord.FFmpegPCMAudio(YouTube(arg[1]).streams.first().download()))
await ctx.guild.change_voice_state(channel=vc, self_mute=False, self_deaf=True)
bot.run('my token')

discord.py mute everyone in voice channel

this is my code rn:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="-")
#client.event
async def on_ready():
print('BOT ACTIVATED')
#client.command()
async def hello(ctx):
await ctx.send("hei this is a test just dont mind me")
#client.command()
async def join(ctx):
channel = ctx.message.author.voice.channel
await channel.connect()
client.run('mytoken')
how do i mute everyone in that voice channel?
Iterate through all members of the voice channel and pass mute=True to the edit function.
#client.command()
async def vcmute(ctx):
vc = ctx.author.voice.channel
for member in vc.members:
await member.edit(mute=True)

Categories