字符串未进入正确的 txt 文件 [discord.py]
Strings not going into the right txt file [discord.py]
我有这段代码,基本上它应该做的是在具有 '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)
消息被添加到其他用户的文件中,因为您遍历了整个 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)
我有这段代码,基本上它应该做的是在具有 '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)
消息被添加到其他用户的文件中,因为您遍历了整个 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)