Hey everyone! I’m working on a Discord bot that can play audio. It’s going well but I’m stuck on one thing. I want the bot to post the YouTube URL in the chat. Here’s what I’ve tried:
@bot.command()
async def playtrack(ctx, *, search: str):
if not search.startswith('-u'):
# Regular search logic here
pass
else:
try:
index = int(search[3])
await ctx.send(track_list[index][0])
except Exception as e:
await ctx.send(str(e))
I’m trying to make it work with a shorter command like .playtrack -u 1
instead of the longer url
version. But I can’t get it to work right. Any ideas on how to fix this?
Also, I’m using a separate function to search YouTube that returns a list of video details. How can I ensure the bot shows the correct URL when a user selects a track? Thanks for any help!
I’ve been working on a similar project, and I can share what worked for me. Instead of using a separate function for YouTube searches, I integrated it directly into the command. This approach simplified the code and made it easier to handle URLs:
@bot.command()
async def playtrack(ctx, *, query):
if query.startswith(‘-u’):
try:
index = int(query.split()[1]) - 1
results = await YTDLSource.search_youtube(query)
if 0 <= index < len(results):
await ctx.send(results[index][‘webpage_url’])
else:
await ctx.send(‘Invalid track number.’)
except ValueError:
await ctx.send(‘Please use a valid number after -u.’)
else:
# Regular search logic here
This way, the bot fetches fresh results each time, ensuring the correct URL is always displayed. It also handles potential errors more gracefully. Hope this helps!
hey mandy! i think ur on the right track. maybe try using regex to match the ‘-u’ pattern? like re.match(r’^-u\s*(\d+)$', search). that way u can handle spaces between -u and the number. also, make sure track_list is accessible in that function. good luck with ur bot!
I’d suggest refactoring your code to separate the URL handling logic. Create a function that processes the ‘-u’ command and returns the URL. This way, you can reuse it for both short and long commands. Also, consider error handling for out-of-range indices. For example:
import re
def get_url(search, track_list):
match = re.match(r'^-u\s*(\d+)$', search)
if match:
index = int(match.group(1)) - 1
if 0 <= index < len(track_list):
return track_list[index][0]
return None
@bot.command()
async def playtrack(ctx, *, search: str):
url = get_url(search, track_list)
if url:
await ctx.send(url)
else:
# Regular search logic here
pass
This approach should work for both .playtrack -u 1
and longer URL versions.