python - 我的反脏话代码不起作用,是什么原因?
问题描述
我正在编写一个反发誓机器人。但这似乎不起作用。这是代码 -
@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)
它仍然给出同样的错误,我不知道为什么。如果你知道这个问题的答案,请回答我。提前致谢。
解决方案
该错误表示未找到要读取的文件:
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 = []
推荐阅读
- php - 使用 Symfony 升级 2.8-> 3.4 进行 Doctrine Migration 时出错
- oracle - impdp ora-00904 标识符无效
- rust - 我可以有条件地提供特征函数的默认实现吗?
- angular - 对动态内容的 Angular 应用程序进行单元测试
- react-native - 使用 https url 获取请求不适用于 Android<5.0
- c# - c# -DirectShow 中的网络摄像头模拟器/虚拟摄像头
- amazon-web-services - Amazon DynamoDB 是否支持查询结果的流式传输
- python - 形状为 (2,) 的不可广播输出操作数与广播形状 (1,2) 不匹配
- node.js - Handlebars:根据 url 禁用一些内容
- angular - 用户登录时无法从本地存储中正确获取项目