首页 > 解决方案 > 我的反脏话代码不起作用,是什么原因?

问题描述

我正在编写一个反发誓机器人。但这似乎不起作用。这是代码 -

@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!")

此代码用于将单词添加到 txt 文件中。但它甚至没有添加一个词。我确实发现它也不响应任何命令。它也没有给出任何错误。

这是它检查消息是否与 txt 文件中的任何单词相同的代码,

@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)

它仍然给出同样的错误,我不知道为什么。如果你知道这个问题的答案,请回答我。提前致谢。

标签: pythonpython-3.xdiscord.py

解决方案


该错误表示未找到要读取的文件:

FileNotFoundError:[Errno 2] 没有这样的文件或目录:'800964569055887360'"

"r"发生此问题是因为当您以读取 ( ) 模式打开文件时,python 不会创建文件。

您可以通过以下方式避免此错误:

1.手动创建文件

2.try: ... except:这样使用:

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 = []

推荐阅读