我有这个代码,基本上它应该做的是当具有“ADMIN”或“semi-mod”角色的人说'!log user'时记录特定的用户消息。代码将消息放入.txt文件中,该文件的名称是被记录用户的ID。如果找不到包含用户唯一ID的txt文件,则会创建一个新文件。但是我的问题是,如果我记录多个人,则消息将进入其他用户文本文件等。
@commands.command(pass_context=True)
async def log(self, ctx, user: discord.Member):
if 'Administrator' or 'semi-mod' in [x.name for x in ctx.message.author.roles]:
users2log.append(user.id)
msg = """```
Member's Message Being Logged
{} messages are now being logged at the request of {}.
```""".format(ctx.message.mentions[0], ctx.message.author)
await self.bot.send_message(discord.Object(id='320289509281628165'), msg)
await self.bot.add_reaction(ctx.message, '\U00002611')
-----------------------
Part not working:
-----------------------
async def on_message(self, message):
if message.author.id in users2log:
for user in users2log:
try:
f = open(user, 'a')
msg = """
User: {}
Time: {}
Message: {}
\n""".format(message.author, time.localtime(), message.content)
f.write(msg)
f.close()
except FileNotFoundError:
os.system("touch " + user)
答案 0 :(得分:1)
消息被添加到其他用户的文件中,因为您循环遍历整个users2log
数组并附加到每个文件,即使您只想将消息记录到单个用户的文件中。如果您在on_message
中删除for循环,它应该有效,因此您只会附加到与用户ID相匹配的文件:
async def on_message(self, message):
if message.author.id in users2log:
user = message.author.id
try:
f = open(user, 'a')
msg = """
User: {}
Time: {}
Message: {}
\n""".format(message.author, time.localtime(), message.content)
f.write(msg)
f.close()
except FileNotFoundError:
os.system("touch " + user)