Reputation: 55
I am coding an anti-swear bot. But it doesn't seem to work. Here's the code -
@client.command()
async def addword(ctx,* ,word = None):
if word == None:
await ctx.send("You have one option :\n`a-addword <swear_word_here>`")
openfile = open(f"{ctx.guild.id}.txt", "r+")
contents = openfile.read()
for x in contents:
if x == "word":
await ctx.send('That word is already censored!')
else:
openfile.write(f"{word}")
await ctx.send("Added the word to server's censor list!")
This code is for adding words into the txt file. But it doesn't even add a word. I did find out that it doesn't respond to any commands either. Neither does it give any errors.
Here's the code where it checks if the message is the same as any word in the txt file,
@client.event
async def on_message(msg):
author = msg.author
channel = msg.channel
em = discord.Embed(title="Swear word warning", description = f"{author.mention} You're not allowed to say that <:angry_pepe:781377642410409994>.")
contentofmsg = msg.content.lower()
try:
f = open(f"{msg.guild.id}.txt", "r")
contents = f.read()
except FileNotFoundError:
f = open(f"{msg.guild.id}.txt", "a+")
contents = []
for x in contents:
if x == contentofmsg:
await msg.delete()
await channel.send(author.mention, embed=em)
else:
return
await client.process_commands(msg)
It still gives the same error, I have no idea why. If you know the answer to this, please do answer me. Thanks in advance.
Upvotes: 1
Views: 124
Reputation: 1513
The error says that the file to read is not found:
FileNotFoundError: [Errno 2] No such file or directory: '800964569055887360'"
This issue happens because python does not create the file when you open it in read ("r"
) mode.
You can avoid this error by:
1. Manually creating the file
or
2. Use try: ... except:
like that:
try: # the file exists
openfile = open(f"{ctx.guild.id}.txt", "r")
contents = openfile.read()
except FileNotFoundError: # the file does not exist
# create it and create "contents" (empty for the moment)
open(f"{ctx.guild.id}.txt", "a+")
contents = []
Upvotes: 1