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
Related
import asyncio
import json
import os
import random
from pathlib import Path
import discord
import requests
import youtube_dl
from discord.ext import commands
from discord.utils import get
from dotenv import load_dotenv
from youtubesearchpython import SearchVideos
from pytube import YouTube
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
PREFIX = os.getenv('DISCORD_PREFIX')
YOUTUBE_KEY = os.getenv('YOUTUBE_API1')
OWNER_ID = os.getenv('OWNER_ID')
CACHE_SIZE = os.getenv('CACHE_SIZE')
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=PREFIX,intents=intents)
is_playing = True
is_skipping = False
is_recommended = False
is_bot_locked = False
is_repeat_mode = False
playlist = []
loop = asyncio.get_event_loop()
current_playing_song = ""
current_song_data = []
is_pinging = True
async def autoplay(ctx):
global is_skipping, current_playing_song, current_song_data
while is_playing:
if playlist:
voice = get(bot.voice_clients, guild=ctx.guild)
current_song_data = playlist.pop()
current_playing_song = current_song_data[0]
await ctx.channel.send('Now playing ' + current_song_data[1])
with youtube_dl.YoutubeDL({}) as ydl:
video = ydl.extract_info(current_song_data[1], download=False)
await bot.change_presence(activity=discord.Streaming(name=video['title'], url=current_song_data[1]))
voice.play(discord.FFmpegPCMAudio(f'audio_cache/{current_song_data[0]}.webm'))
while voice.is_playing() or voice.is_paused():
if is_skipping:
is_skipping = False
voice.stop()
break
else:
await asyncio.sleep(.5)
else:
if is_repeat_mode:
playlist.append(current_song_data)
elif is_recommended:
video_id = current_playing_song if current_playing_song else get_random_song()[-1]
await get_recommended_song(ctx, video_id)
else:
audio = get_random_song()
await download_file(ctx.channel, audio[0], audio[1])
#bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
#bot.command(pass_context=True, name='ping', help='Ping your bot')
async def ping(ctx):
global is_pinging
await ctx.send(f'Latency is {round(bot.latency * 100)}ms')
#bot.command(pass_context=True, name='summon', help='Connect the bot to voice channel')
async def summon(ctx):
global is_playing
if not await check_if_user_connected(ctx):
return
voice = get(bot.voice_clients, guild=ctx.guild)
if voice:
await ctx.channel.send('Bot is already connected to voice channel')
return
is_playing = True
channel = ctx.author.voice.channel
await channel.connect()
loop.create_task(autoplay(ctx))
await ctx.channel.send(
f"Connected to {channel}, Playing in {'Recommendation' if is_recommended else 'Auto Playlist'} mode.")
#bot.command(pass_context=True, aliases=['p', 'play'], help='play music')
async def play_music(ctx, *, arg):
voice = await get_bot_voice(ctx)
if not voice:
return
await search_video(ctx.channel, arg)
#bot.command(pass_context=True, aliases=['s', 'skip'], help='Skip music')
async def skip_music(ctx):
global is_skipping
voice = await get_bot_voice(ctx)
if not voice:
return
if is_playing:
await ctx.channel.send('Skipping the song')
is_skipping = True
else:
await ctx.channel.send('Nothing is playing')
#bot.command(pass_context=True, name='disconnect', help='Disconnect the bot')
async def disconnect(ctx):
global is_playing
voice = await get_bot_voice(ctx)
if not voice:
return
is_playing = False
await ctx.channel.send('Bye Bye')
await voice.disconnect()
#bot.command(pass_context=True, aliases=['sw', 'switch'], help='Switch play mode')
async def switch_mode(ctx):
global is_recommended
is_recommended = not is_recommended
await ctx.channel.send(f"Autoplay mode changed to {'Recommended' if is_recommended else 'Autoplaylist'}")
#bot.command(pass_context=True, name='lock', help='Lock the bot')
async def lock(ctx):
global is_bot_locked
if str(ctx.author.id) == str(OWNER_ID):
is_bot_locked = True
#bot.command(pass_context=True, name='unlock', help='Unlock the bot')
async def unlock(ctx):
global is_bot_locked
if str(ctx.author.id) == str(OWNER_ID):
is_bot_locked = False
#bot.command(pass_context=True, name='pause', help='Pause music')
async def pause(ctx):
voice = await get_bot_voice(ctx)
if not voice:
return
if voice.is_playing():
voice.pause()
await ctx.channel.send('Paused')
else:
await ctx.channel.send('Nothing is playing')
#bot.command(pass_context=True, name='resume', help='Resume music')
async def resume(ctx):
voice = await get_bot_voice(ctx)
if not voice:
return
if voice.is_paused():
voice.resume()
await ctx.channel.send('Resuming the song')
else:
await ctx.channel.send('Nothing is playing')
#bot.command(pass_context=True, name='save', help='Save music to Autoplaylist')
async def save(ctx):
voice = await get_bot_voice(ctx)
if not voice:
return
song = f"https://www.youtube.com/watch?v={current_playing_song}\n"
if song in list(open('autoplaylist.txt')):
await ctx.channel.send('This song is already in Autoplaylist')
else:
open('autoplaylist.txt', 'a').write(song)
await ctx.channel.send('Song is added to Autoplaylist')
#bot.event
async def on_voice_state_update(member, before, after):
if before.channel is None and after.channel is not None and str(member.id) == str('756835280714989620'):
await member.move_to(None)
#bot.command(pass_context=True, name='remove', help='Remove music from Autoplaylist')
async def remove(ctx):
voice = await get_bot_voice(ctx)
if not voice:
return
song = f"https://www.youtube.com/watch?v={current_playing_song}\n"
songs = list(open('autoplaylist.txt'))
if song in songs:
songs.remove(song)
open('autoplaylist.txt', 'w').write("".join(songs))
await ctx.channel.send('Song is removed from Autoplaylist')
else:
await ctx.channel.send('This Song is not in Autoplaylist')
#bot.command(pass_context=True, name='repeat', help='Toggle repeat mode')
async def repeat(ctx):
global is_repeat_mode
if is_repeat_mode:
is_repeat_mode = False
await ctx.channel.send('Repeat mode OFF')
else:
is_repeat_mode = True
await ctx.channel.send('Repeat mode ON')
async def check_if_user_connected(ctx):
connected = ctx.author.voice
if not connected:
await ctx.channel.send('You are not connected to any voice channel')
return False
return True
async def get_bot_voice(ctx):
if is_bot_locked and str(ctx.author.id) != str(OWNER_ID):
await ctx.channel.send('Bot is Locked, Ask an admin to unlock')
return None
connected = ctx.author.voice
if not connected:
await ctx.channel.send('You are not connected to any voice channel')
return None
voice = get(bot.voice_clients, guild=ctx.guild)
if not voice:
await ctx.channel.send('Bot is not connected to any voice channel, Please summon the bot first.')
return None
return voice
async def search_video(channel, search):
search = SearchVideos(search, offset=1, mode="list", max_results=1)
if len(search.result()) != 1:
await channel.send('Unable to find any Video')
else:
await channel.send('Added to stack ' + search.result()[0][3])
await download_file(channel, search.result()[0][2], search.result()[0][1])
async def download_file(channel, url, key):
file_path = f'audio_cache/{key}.webm'
if Path(file_path).is_file():
playlist.append([key, url])
return
try:
clear_cache()
yt = YouTube(url)
yt.streams.filter(only_audio=True).first().download(output_path='audio_cache', filename=f'{key}.webm')
playlist.append([key, url])
except Exception as e:
await channel.send(str(e))
def clear_cache():
try:
path, v, files = next(os.walk("audio_cache"))
if len(files) > int(CACHE_SIZE):
song = random.choice(files)
for music in playlist:
if song.strip('.webm') == music[0]:
return
os.remove(f"{path}/{song}")
except Exception as e:
print(e)
async def get_recommended_song(ctx, key):
global YOUTUBE_KEY
audio = get_random_song()
url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&relatedToVideoId=" \
f"{key}&type=video&key={YOUTUBE_KEY}"
response = requests.get(url)
if response.ok:
songs = json.loads(response.content)['items']
if len(songs) > 1:
songs.pop(0)
video_id = random.choice(songs)['id']['videoId']
audio = [f"https://www.youtube.com/watch?v={video_id}", video_id]
else:
if YOUTUBE_KEY is os.getenv('YOUTUBE_API1'):
YOUTUBE_KEY = os.getenv('YOUTUBE_API2')
else:
YOUTUBE_KEY = os.getenv('YOUTUBE_API1')
await download_file(ctx.channel, audio[0], audio[1])
def get_random_song():
song = random.choice(list(open('autoplaylist.txt'))).strip('\n')
return [song, song.split("=")[-1]]
bot.run(TOKEN)
Task was destroyed but it is pending!
task: <Task pending name='Task-21' coro=<autoplay() running at c:\Users\S1ncer3ly\Desktop\DiscordMusicBot-main\main.py:38>>
C:\Users\S1ncer3ly\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py:675: RuntimeWarning: coroutine 'autoplay' was never awaited
Im totally new into this thankyou
change the line loop.create_task(autoplay(ctx)) to await autoplay(ctx)
Im making a music bot but i get
AttributeError: 'Player' object has no attribute 'ctx'
when i do >>play some music when another music is playing (supposed to be for queue)
full error
Bot Online
Node <8d0e8f15e4723f72> is ready
Ignoring exception in on_wavelink_track_end
Traceback (most recent call last):
File "/home/catiganvien3/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/catiganvien3/scripts/WaveLinkBot/main.py", line 28, in on_wavelink_track_end
ctx = player.ctx
AttributeError: 'Player' object has no attribute 'ctx'
Full code is
import wavelink
import discord
from discord.ext import commands
import asyncio
import os
bot = commands.Bot(command_prefix='>>')
#bot.event
async def on_ready():
print('Bot Online')
bot.loop.create_task(node_connect())
#bot.event
async def on_wavelink_node_ready(node: wavelink.Node):
print(f'Node <{node.identifier}> is ready')
async def node_connect():
await bot.wait_until_ready()
await wavelink.NodePool.create_node(bot=bot, host='ash-01.thermalhosting.com', port=2008, password='ASH-01')
#bot.event
async def on_wavelink_track_end(player: wavelink.Player, track: wavelink.Track, reason):
ctx = player.ctx
vc: player = ctx.voice_client
if vc.loop:
return await vc.play(track)
try:
next_song = vc.queue.get()
await vc.play(next_song)
embed = discord.Embed(
title="Now playing", description=f'Song name: **{next_song.title}**\nSong author: **{next_song.author}**')
await ctx.send(embed=embed)
except:
# An exception when after the track end, the queue is now empty. If you dont do this, it will get error.
await vc.stop()
#bot.command()
async def play(ctx: commands.Context, *, search: wavelink.YouTubeTrack):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not getattr(ctx.author.voice, 'channel', None):
await ctx.send(f'Connect to a voice channel to use this command!')
else:
vc: wavelink.Player = ctx.voice_client
song_name = search.title
song_author = search.author
if song_author == None:
song_author = 'Unknown'
# embed = discord.Embed(title="Added to queue", description=f'Song name: **{song_name}**\nSong author: **{song_author}**')
# await vc.play(search)
# await ctx.send(embed=embed)
if vc.queue.is_empty and vc.is_playing:
await vc.play(search)
embed = discord.Embed(title="Playing", description=f'Song name: **{song_name}**\nSong author: **{song_author}**')
return await ctx.send(embed=embed)
else:
await vc.queue.put_wait(search)
embed = discord.Embed(title="Added to queue", description=f'Song name: **{song_name}**\nSong author: **{song_author}**')
return await ctx.send(embed=embed)
vc.ctx = ctx
setattr(vc, "loop", False)
#bot.command()
async def pause(ctx: commands.Context):
if not ctx.voice_client:
return await ctx.send('Im not playing any music!')
elif not getattr(ctx.author.voice, 'channel', None):
await ctx.send(f'Connect to a voice channel to use this command!')
else:
vc: wavelink.Player = ctx.voice_client
await vc.pause()
await ctx.send(f'Paused!')
#bot.command()
async def resume(ctx: commands.Context):
if not ctx.voice_client:
return await ctx.send('Im not playing any music!')
elif not getattr(ctx.author.voice, 'channel', None):
await ctx.send(f'Connect to a voice channel to use this command!')
else:
vc: wavelink.Player = ctx.voice_client
await vc.resume()
await ctx.send(f'Resumed!')
#bot.command()
async def stop(ctx: commands.Context):
if not ctx.voice_client:
return await ctx.send('Im not playing any music!')
elif not getattr(ctx.author.voice, 'channel', None):
await ctx.send(f'Connect to a voice channel to use this command!')
else:
vc: wavelink.Player = ctx.voice_client
await vc.stop()
await ctx.send(f'Stopped!')
#bot.command()
async def disconnect(ctx: commands.Context):
if not ctx.voice_client:
return await ctx.send('Im not playing any music!')
elif not getattr(ctx.author.voice, 'channel', None):
await ctx.send(f'Connect to a voice channel to use this command!')
else:
vc: wavelink.Player = ctx.voice_client
await vc.disconnect()
await ctx.send('Bye!')
#bot.command()
async def loop(ctx: commands.Context):
if not ctx.voice_client:
return await ctx.send('Im not playing any music!')
elif not getattr(ctx.author.voice, 'channel', None):
await ctx.send(f'Connect to a voice channel to use this command!')
else:
vc: wavelink.Player = ctx.voice_client
try:
vc.loop = True
except Exception:
setattr(vc, "loop", False)
if vc.loop:
return await ctx.send('Loop is now enabled!')
else:
vc.loop = False
return await ctx.send('Loop is now disabled')
#bot.command()
async def queue(ctx: commands.Context):
if not ctx.voice_client:
return await ctx.send('Im not playing any music!')
elif not getattr(ctx.author.voice, 'channel', None):
await ctx.send(f'Connect to a voice channel to use this command!')
else:
vc: wavelink.Player = ctx.voice_client
if vc.queue.is_empty:
return await ctx.send('Queue is empty!')
embed = discord.Embed(title="Queue")
queue = vc.queue.copy()
song_count = 0
for song in queue:
song_count += 1
embed.add_field(name=f"Song number {song_count}", value=f"{song.title}")
return await ctx.send(embed=embed)
bot.run('secret')
If I'm right, it should be a version issue. There is nothing wrong with your code.
I didn't have this troble until I re-installed wavelink, so I do prefer it's a version issue, I don't know which version has this ctx value, but if I find the correct version I'll answer you!
EDIT
The version has player.ctx is 1.2.5, I am not sure if 1.3.0 still has the player.ctx but I do prefere 1.2.5 because it's a more stable version (for me).
To install
python3 -m pip install wavelink==1.2.5, python -m pip install wavelink==1.2.5
or
py -m pip install wavelink==1.2.5, depends on your machine. You could also try version 1.2.3
IMPORTANT
It could be also that the bot stayed too long in the call and wavelink can't get the ctx out of it.
So basically I have this problem, any command that I type does not work. There are no errors, and everything else is working fine. It's just that for some reasons #bot.command() isn't working, and that is kind of annoying.
import discord
from discord.utils import get
from discord.ext import commands
import time
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix = '$', intents=intents)
TOKEN = 'hi'
ROLE = 'hi'
db1 = [hi, hi]
#bot.command()
async def test(ctx, arg):
await ctx.send(arg)
await bot.process_commands(arg)
#bot.event
async def on_member_join(member):
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
await member.send('hi')
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="hi", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="hi", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_member_remove(member):
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_invite_create(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been created, {}, by <#{}> on {}".format(str(invite.url), str(invite.inviter.id), str(invite.created_at)))
#bot.event
async def on_invite_delete(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been deleted by{}".format(str(invite.inviter.id)))
#bot.event
async def on_member_ban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Ban", description="Ban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_member_unban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Unban", description="Unban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_ready():
print(f'{bot.user} succesfully logged in')
return
#bot.event
async def on_message(message):
if message.content.startswith('purge requested by'):
time.sleep(1)
await message.delete()
if message.author == bot:
return
if message.content == 'hi':
await message.channel.send('hi')
if message.content.startswith('binvites'):
totalInvites = 0
for i in await message.guild.invites():
if i.inviter == message.author:
totalInvites += i.uses
await message.channel.send(f"You have invited {totalInvites} member{'' if totalInvites == 1 else 's'} to the Central Trade server")
if message.content == 'bpurge':
if message.author.id in db1:
await message.channel.purge(limit=10)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
else:
return
if message.content == 'block':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = False
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Lock", description="Channel lock request by <#{}>".format(str(message.author.id)), color= 0x00FFFF)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'bunlock':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = True
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Unlock", description="Channel unlock request by <#{}>".format(str(message.author.id)), color=0xC0C0C0)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'test':
embedVar = discord.Embed(title="test", description="test", color=0x00ff00)
embedVar.add_field(name="test", value="test", inline=False)
embedVar.add_field(name="test", value="test", inline=False)
await message.channel.send(embed=embedVar)
if message.content == 'bpurges':
if message.author.id in db1:
await message.channel.purge(limit=10000)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
embedVar = discord.Embed(title="Purge", description="Purge requested by<#{}>".format(str(message.author.id)))
await message.channel.send(embed=embedVar)
time.sleep(1)
await message.channel.delete()
bot.run(TOKEN)
Anyone has an idea why it's not working ? Also seems like i need to post more details, don't pay attention to this : Roméo et Juliette (Romeo and Juliet) est une tragédie de William Shakespeare.
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)
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