Creating a Discord bot that appends user input to a URL

Hey folks! I’m trying to build a Discord bot using discord.py. I want it to take any input after the command ‘+search’ and add it to the end of a Facebook URL. For example, if a user types ‘+search mycoolpage’, the bot should respond with ‘Biggest Lie - "Yaar I Forgot him/her and. I Am Happy Now "’.

Here’s what I’ve got so far, but it’s not working:

@bot.event
async def on_message(message):
    if message.content.startswith('+search'):
        search_term = message.content[7:].strip()
        await message.channel.send(f'https://www.facebook.com/{search_term}')

Can anyone help me figure out what I’m doing wrong? I’m pretty new to Discord bot development, so any tips would be super helpful. Thanks in advance!

Your approach is on the right track, but I’d suggest a small modification for better functionality. Instead of using on_message, try using a command decorator. Here’s an improved version:

@bot.command()
async def search(ctx, *, query):
    url = f'https://www.facebook.com/{query}'
    await ctx.send(url)

This method is more efficient and allows for multi-word queries without extra processing. Remember to import the commands extension and set up your bot with a command prefix. Also, consider implementing error handling for cases where users don’t provide a search term. This will make your bot more robust and user-friendly.

I’ve actually worked on a similar project before, and I can share some insights that might help you out. The code you’ve provided looks pretty close, but there are a few tweaks you can make to improve it.

First, instead of using on_message, I’d recommend using the commands extension. It’s more efficient and easier to manage. Here’s how you could modify your code:

from discord.ext import commands

bot = commands.Bot(command_prefix='+')

@bot.command()
async def search(ctx, *, term):
    await ctx.send(f'https://www.facebook.com/{term}')

This approach handles the command parsing for you, so you don’t need to manually slice the message content. It also allows for multiple word search terms without additional processing.

One thing to keep in mind: make sure you’re properly handling spaces and special characters in the URL. You might want to use urllib.parse.quote to encode the search term properly.

Hope this helps! Let me know if you run into any other issues.

yo, ur code’s almost there! try this:

@bot.command()
async def search(ctx, *, stuff):
await ctx.send(f’Redirecting...')

it’ll grab everything after +search as one chunk. don’t forget to import commands n setup ur bot right. good luck, dude!