How to display YouTube link in Discord chat using Python bot

I created a Discord music bot in Python that can stream audio from YouTube videos. Everything works fine for playing music, but I’m struggling with one feature. I want the bot to post the YouTube URL in the chat when requested.

@client.command()
async def music(ctx, *, search_term: str):
    options = {'default_search': 'auto', 'quiet': True}
    
    if voice_client == None:
        await ctx.send('Connect me to a voice channel first using !join')
    
    elif search_term[:3] == 'url':
        try:
            index = int(search_term[4])
            await ctx.send(song_list[index][0])
        except Exception as error:
            await ctx.send(error)
    
    elif len(search_term) != 1:
        song_list = youtube_search.find_videos(search_term, 4)
        for x in range(4):
            embed = discord.Embed(title=song_list[x][1], color=0x00ff00)
            embed.set_image(url=f'https://i.ytimg.com/vi/{song_list[x][0][32:]}/maxresdefault.jpg')
            await ctx.send(embed=embed)
        await ctx.send('Pick a song (type !music 1/2/3/4)')
    
    else:
        try:
            if audio_player != None:
                audio_player.stop()
            choice = int(search_term)
            audio_player = await voice_client.create_ytdl_player(song_list[choice-1][0], ytdl_options=options)
            audio_player.volume = 0.3
            audio_player.start()
        except Exception as error:
            await ctx.send(error)

My issue is with the URL command part. Right now I use ‘url’ but I want to make it shorter like ‘-u’ or something similar. When I try to change elif search_term[:3] == 'url' to use a different prefix, it doesn’t work properly. How can I modify this to accept shorter commands for displaying URLs?

This happens because you need to update both the slice length and character position for different prefixes. For -u, change search_term[:3] == 'url' to search_term[:2] == '-u' and update int(search_term[4]) to int(search_term[2]) since the number comes right after -u. I ran into the same thing with my Discord bot. Adding validation really helps - wrap the index extraction in try-except and check if search_term is long enough before slicing. Saves you from crashes when users type incomplete commands.

just adjust the slice length when you change the prefix. for -u, use search_term[:2] == '-u' and int(search_term[3]) to get the index. don’t forget to update the index position or parsing will break.

Your parsing logic is hardcoded for that specific ‘url’ prefix length - that’s the problem. I’ve dealt with similar command parsing issues and found it’s way better to use a flexible approach. Don’t hardcode slice positions. Use string methods like startswith() and split() instead. Try if search_term.startswith('-u ') then grab the index with search_term.split()[1]. You’ll avoid that brittle slice indexing that breaks every time you change prefix lengths. You could also use regex to extract the number regardless of prefix length - makes your code way more maintainable when you want multiple URL command formats later.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.