I'm new to coding and I'm creating a Discord bot and I still get a Syntax error, here is the code:
import discord
import os
from discord.ext import commands
client = commands.Bot(command_prefix = "/")
@client.event
async def on_ready():
print("Bot is online!")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
try:
client.load_extension(f"cogs.{filename[:-3]}")
print(f"Loaded {filename}")
except Exception as e:
print(f"Failed to load {filename}")
print(f"[ERROR] {e}")
client.run("token")
And this is the error
File "main.py", line 15
except: Exception as e:
^
SyntaxError: invalid syntax
try:
client.load_extension(f"cogs.{filename[:-3]}")
print(f"Loaded {filename}")
except Exception as e:
print(f"Failed to load {filename}")
print(f"[ERROR] {e}")
The except is supposeod to be outside the try chunk. The except cannot find any try in the scope similarly the try doesnt find any except in its scope
The indentation can differ from ide to ide
This might happen because Python indentation is not done right. Your try
and except
is has a different indentation, make sure the except
statement is at the same level as the try
one.
Corrected code:
import discord
import os
from discord.ext import commands
client = commands.Bot(command_prefix = "/")
@client.event
async def on_ready():
print("Bot is online!")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
try:
client.load_extension(f"cogs.{filename[:-3]}")
print(f"Loaded {filename}")
except Exception as e:
print(f"Failed to load {filename}")
print(f"[ERROR] {e}")
client.run("token")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.