Python Discord bot throwing indentation error on async function

I’m working on a Discord bot using Python and keep running into an indentation problem. Every time I try to run my script, it gives me an error about expecting an indented block.

Here’s my code:

import discord
from discord.ext import commands
import asyncio

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

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

@bot.command()
async def spam(ctx):
for i in range(10):
await ctx.send(message="Hello everyone! Join our server event!")
await asyncio.sleep(3)

bot.run("my_bot_token")

The error shows up when I try to execute this. I think it has something to do with the way I wrote the loop inside the command function, but I’m not sure how to fix the indentation properly. Can someone help me understand what’s wrong with the structure?

The issue you’re encountering is indeed related to indentation in your spam function. Python requires correct indentation for defining blocks of code, and it appears your for loop and the await statements are not correctly aligned. I’ve had a similar experience when I first started working with Discord bots.

To fix this, you should indent the for loop by four spaces from the function declaration, and then indent the await statements another four spaces further in. Here’s what your code should look like:

@bot.command()
async def spam(ctx):
    for i in range(10):
        await ctx.send("Hello everyone! Join our server event!")
        await asyncio.sleep(3)

Also, remember to position the message parameter correctly in ctx.send() or use content=. Just a heads up—be cautious with spamming, as many servers may kick bots that send too many messages in a short period.

yep, the problem is with indents on the for loop and await lines. python is super picky about how you indent. just make sure everything inside the func is tabbed correctly and it should work.

Indeed, indentation is crucial in Python, particularly with async functions. Ensure that your for loop and await statements are correctly aligned under the function declaration. I faced similar issues when I began using discord.py. You should indent your for loop by four spaces from the function declaration and indent the await statements an additional four spaces inward. Additionally, verify that the message formatting in ctx.send is correct. Be cautious, as sending messages too quickly may exceed Discord’s rate limits; consider increasing the sleep duration.

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