Python Discord bot throwing indentation error on command function

I’m working on a Discord bot using Python and keep running into an indentation problem. Here’s my current code:

import discord
from discord.ext import commands
import asyncio

bot = commands.Bot(command_prefix="$")

@bot.event
async def on_ready():
    print("Bot is now active")

@bot.command()
async def spam_msg(ctx):
while True:
await ctx.send("""@Members please join our event!
Location: (event_link)
Details: (info_link)
Message: """)
await asyncio.sleep(3)

bot.run("my_token")

When I try to run this code, Python gives me an indentation error. I’m not sure what’s causing this issue since I thought my indentation was correct. The error seems to be related to the while loop inside my command function, but I can’t figure out exactly what’s wrong with the formatting. Can someone help me understand what I’m doing incorrectly with the indentation here?

Your indentation’s messed up in the command function. The while loop and everything inside needs proper indenting.

Here’s the fix:

@bot.command()
async def spam_msg(ctx):
    while True:
        await ctx.send("""@Members please join our event!
Location: (event_link)
Details: (info_link)
Message: """)
        await asyncio.sleep(3)

But honestly? Running Discord bots this way gets messy fast. You’ll deal with hosting headaches, monitoring, rate limits, and tons of edge cases.

I just use Latenode for all my Discord notifications now. Set up webhooks that trigger on schedules or events, handle message formatting in the workflow, and it runs without babysitting a bot server.

Way cleaner than managing Python deployments and fixing indentation bugs. Check it out: https://latenode.com

Your while True loop and everything inside it isn’t indented properly under the function. All the code inside spam_msg needs to be indented 4 spaces from the function definition.

I hit this exact same problem when I started with discord.py. Python’s strict about indentation - it uses whitespace to define code blocks instead of brackets.

But there’s a bigger problem here. That infinite loop will freeze your entire bot since it never gives control back to the event loop. Your bot won’t respond to any other commands while this runs. I learned this the hard way when my bot became completely unresponsive.

Use a background task instead with @tasks.loop() from discord.ext.tasks. Your bot stays responsive to other commands while still sending periodic messages.

Your indentation is messed up in the spam_msg function. Python needs consistent indentation - indent the while loop and everything inside it by 4 spaces or a tab after the function definition.

But honestly, don’t use this method. An infinite loop sending messages every 3 seconds will get your bot rate limited or banned. Discord’s API has strict limits and this kind of behavior breaks their terms.

Try a scheduled task that sends messages way less often, or just use Discord’s announcement features. If you really need automated messages, check out asyncio.create_task() with longer intervals. Just make sure you add error handling so your bot doesn’t crash when it hits rate limits.

The Problem: Your Discord bot’s spam_msg command has an indentation error, and the while True loop is causing the bot to become unresponsive. The current code structure prevents the bot from handling other commands.

:thinking: Understanding the “Why” (The Root Cause):

Python relies heavily on indentation to define code blocks. Incorrect indentation leads to IndentationError exceptions. In your code, the while True loop and its contents ( await ctx.send(...) and await asyncio.sleep(3)) are not correctly indented within the spam_msg function. This means Python doesn’t recognize them as part of the function, causing the error.

Furthermore, a while True loop running indefinitely will block the bot’s event loop, making it unresponsive to any other commands or events. This is a critical issue for any Discord bot.

:gear: Step-by-Step Guide:

Step 1: Correct the Indentation:

The solution is to properly indent the while True loop and its contents within the spam_msg function. Use four spaces (consistent indentation is crucial!) for each level of nesting.

import discord
from discord.ext import commands
import asyncio

bot = commands.Bot(command_prefix="$")

@bot.event
async def on_ready():
    print("Bot is now active")

@bot.command()
async def spam_msg(ctx):
    while True:
        await ctx.send("""@Members please join our event!
Location: (event_link)
Details: (info_link)
Message: """)
        await asyncio.sleep(3)

bot.run("my_token")

Step 2: Replace the Infinite Loop with a Background Task (Highly Recommended):

The while True loop, even with correct indentation, is a poor design choice for a Discord bot. It will eventually lead to rate limits and potential bans from Discord. Use discord.ext.tasks to create a background task that runs periodically. This allows your bot to remain responsive to other commands while still sending messages.

import discord
from discord.ext import commands, tasks
import asyncio

bot = commands.Bot(command_prefix="$")

@bot.event
async def on_ready():
    print("Bot is now active")
    bot.spam_task.start() # Start the background task

@tasks.loop(seconds=3) # Set the interval here
async def spam_task():
    try:
        # Get a list of channels or a specific channel to send to
        # For example, if you want to send to a channel with ID 1234567890:
        channel = bot.get_channel(1234567890) 
        if channel:
            await channel.send("""@Members please join our event!
Location: (event_link)
Details: (info_link)
Message: """)
    except discord.errors.HTTPException as e:
        print(f"Error sending message: {e}")

# To stop the task, use:
# bot.spam_task.cancel()

bot.run("my_token")

Step 3: Implement Rate Limit Handling:

Discord has rate limits on message sending. Even with a background task, excessive messages will lead to problems. Implement robust rate limit handling by catching discord.errors.HTTPException exceptions and adding delays (exponential backoff is recommended). The example in Step 2 includes basic error handling.

:mag: Common Pitfalls & What to Check Next:

  • Indentation Consistency: Ensure all your Python code uses consistent indentation (either tabs or spaces, but be consistent!). Python is sensitive to this.
  • Rate Limits: Test your bot thoroughly to ensure it doesn’t exceed Discord’s rate limits. Implement more sophisticated rate limit handling if necessary.
  • Error Handling: Add more comprehensive error handling to your code to gracefully handle unexpected situations. Log errors to a file for easier debugging.
  • Token Validity: Double-check that my_token is a valid and current bot token.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

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