Home > Net >  Discord bot commands randomly stop working with python?
Discord bot commands randomly stop working with python?

Time:09-22

I was just adding some extra code to my discord bot to play youtube music, but then i go to run the bot and it starts as normal and works, but then when i go to test the new commands nothing works, no errors or anything, then i try the basic commands like /hello that was working fine before and that also is not doing anything. The bot as Administration role. Ive double checked Iam not spelling commands wrong, but even if I was the on_command_error function should call. Also i did a print debug statement at the start of the /play command and not even that gets called, and I havent changed anything major. Anyone have any ideas?

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 shutil,os

# Load .env file
load_dotenv()

PREFIX = "/"
bot = commands.Bot(command_prefix=PREFIX)


# 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.channel.purge(limit=1)
    

# 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()


# YOUTUBE AUDIO PLAYER
@bot.command()
async def play(ctx, url : str):
    print("WORKING")
    if(url == None):
        await ctx.reply("*Check your arguments!*\n```/play VIDEO_URL```")
    else:
        song = os.path.isfile("songs/song.mp3")
        
        try: # Check if song exists if so remove it
            if(song):
                os.remove("songs/song.mp3")
        except PermissionError:
            await ctx.reply("*Wait for current song to end, or use 'stop' command*")
            return
            
        voiceChannel = discord.utils.get(ctx.guild.voice_channels, name="Lounge")
        await voiceChannel.connect()
        voice = discord.utils.get(bot.voice_clients, guild = ctx.guild)
        
        ytdl_opts = { # Some options you need to pass in
            'format': 'bestaudio/best',
            'postprocessors':[{
               'key':'FFmpegExtractAudio',
               'preferredcodec': 'mp3',
               'preferredquality': '192' 
            }],
        }
        
        with youtube_dl.YoutubeDL(ytdl_opts) as ydl:
            ydl.download(url) # Download the vid
            
        for file in os.listdir("./"): # Change the name and move to songs folder
            if file.endswith(".mp3"):
                os.rename(file, "song.mp3")
                shutil.move("song.mp3", "songs")
        
        voice.play(discord.FFmpegPCMAudio(source="songs/song.mp3")) # Play the song
        
        
        
@bot.command()
async def leave(ctx):
    voice = discord.utils.get(bot.voice_clients, guild = ctx.guild)
    
    if(voice.is_connected()):
        voice.disconnect()
    else:
        await ctx.reply("*How can I leave a voice channel if I'am not connected?*")

@bot.command()
async def pause(ctx):
    voice = discord.utils.get(bot.voice_clients, guild = ctx.guild)

    if(voice.is_playing()):
        voice.pause()
    else:
        await ctx.reply("*Can't pause buddy, nothings playing...*")

@bot.command()
async def resume(ctx):
    voice = discord.utils.get(bot.voice_clients, guild = ctx.guild)

    if(voice.is_paused()):
       voice.resume()
    else:
        await ctx.reply("*Can't resume buddy, audio is already playing*")
        
@bot.command()
async def stop(ctx):
    voice = discord.utils.get(bot.voice_clients, guild = ctx.guild)
    voice.stop()
        
   
if __name__ == "__main__":
    bot.run(os.getenv("BOT_TOKEN"))

CodePudding user response:

You need to have bot.process_commands(message) inside your custom on_message events,

@bot.event
async def on_message(message):
    if str(message.channel) == "images-videos" and message.content != "":
        await message.delete()
    await bot.process_commands(message)

I've also changed message.channel.purge(limit=1) to message.delete() because it's the proper way of deleting a message

For more info as to why this is required, see the faq

  • Related