Creating a Discord bot that appends user input to a URL

Hey everyone! I’m trying to make a Discord bot that can take user input and add it to the end of a URL. Here’s what I want to do:

When a user types something like +search coolstuff, I want the bot to take coolstuff and add it to the end of a Facebook URL.

For example, if the base URL is https://www.facebook.com/, the bot should create https://www.facebook.com/coolstuff.

I’m using discord.py and I’ve tried this code:

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

But it’s not working quite right. Can someone help me figure out what I’m doing wrong? Thanks in advance!

I’ve dealt with similar issues when building my Discord bots. Your code is close, but there’s room for improvement. One thing to consider is URL encoding the search term to handle spaces and special characters. Here’s a slightly modified version that should work better:

import urllib.parse

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

This approach uses the @bot.command() decorator, which is more suitable for command handling. It also encodes the query to ensure it’s properly formatted for a URL. Make sure you’ve set up your bot with the necessary intents and command prefix. If you’re still having trouble, double-check your bot’s permissions in the Discord server settings.

I’ve implemented something similar in one of my Discord bots. Your approach is on the right track, but there are a few tweaks you might want to consider. First, ensure you’re using the correct event. For command handling, it’s often better to use @bot.command() instead of @bot.event. This allows for more flexible command parsing.

Here’s a modified version that should work:

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

This way, users can type ‘!search coolstuff’ (assuming ‘!’ is your prefix), and it’ll work as expected. The ‘*’ before ‘query’ allows for multi-word searches. Remember to set up your bot with the necessary intents and command prefix. Let me know if you need any clarification!

yo, i think ur close but maybe try using @bot.command() instead? it’s easier to handle stuff that way. also, make sure ur bot has the right permissions n stuff. if ur still stuck, maybe check out the discord.py docs? they’ve got some good examples there