I’m new to coding and trying to make a Discord bot using Python on Replit. I want the bot to repeat messages when I use a command. Here’s what I’m aiming for:
Me: !echo Hello world
Bot: Hello world
I’ve put together some code, but it’s not working as expected. Can someone help me fix it or point me in the right direction? Here’s a simplified version of what I’ve tried:
import discord
client = discord.Client(intents=discord.Intents.default())
@client.event
async def on_message(message):
if message.content.startswith('!echo'):
text = message.content[6:]
await message.channel.send(text)
client.run('YOUR_BOT_TOKEN')
Any tips or explanations would be really helpful. Thanks!
I’ve worked on a few Discord bots, and your approach is on the right track. One thing to consider is rate limiting - Discord has restrictions on how often bots can send messages. To avoid issues, you might want to add a cooldown:
from discord.ext import commands
import asyncio
bot = commands.Bot(command_prefix='!')
@bot.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def echo(ctx, *, message):
await ctx.send(message)
@echo.error
async def echo_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f'Please wait {error.retry_after:.2f}s before using this command again.')
bot.run('YOUR_BOT_TOKEN')
This setup uses the commands framework, which is generally easier to work with for beginners. It adds a 5-second cooldown per user and handles the error if someone tries to use the command too frequently. Remember to replace ‘YOUR_BOT_TOKEN’ with your actual token.
I’ve implemented a similar bot before, and your code is close! The main issue is that you’re not handling the message parsing correctly. Here’s a refined version that should work:
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!echo'):
echo_content = message.content[6:].strip()
if echo_content:
await message.channel.send(echo_content)
client.run('YOUR_BOT_TOKEN')
This version handles edge cases better and prevents the bot from responding to its own messages. Make sure to replace ‘YOUR_BOT_TOKEN’ with your actual bot token. Also, enable the message content intent in your Discord Developer Portal for the bot to read message content.
yo, ur code looks good but u might wanna add some error handling. heres a quick fix:
@client.event
async def on_message(message):
if message.content.startswith('!echo'):
try:
text = message.content[6:].strip()
if text:
await message.channel.send(text)
else:
await message.channel.send('say smthin after !echo bro')
except Exception as e:
await message.channel.send(f'oops, error: {e}')