使用message.author很难识别谁使用Discord API使用Python发送了消息

2024-09-24 02:26:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了一些代码,可以将它从特定用户的dm获得的每一条新消息附加到一个文件中(使用discord)。我已经写了大部分内容,但我不确定如何从特定的用户部分进行测试

它不工作的原因可能是我的代码中的其他一些缺陷,但我很想修复这个问题

@client.event
async def on_message(message):
    if message.channel.type == "dm":
        if message.author == "MYUSERNAME#MYDISCRIMINATOR":
            print("New message")
            with open('outputmeta.txt', 'a+') as the_file:
                async for log in client.logs_from(message.channel, limit=1000):
                      stringTime = log.timestamp.strftime("%Y-%m-%d %H:%M")
                      try:
                          author = log.author
                      except:
                          author = 'invalid'
                      message = str(log.content.encode("utf-8"))[2:-1]

                      template = '[{stringTime}] <{author}> {message}\n'
                      try:
                          the_file.write(template.format(stringTime=stringTime, author=author, message=message))
                      except:
                          author = log.author.discriminator
                          the_file.write(template.format(stringTime=stringTime, author=author, message=message))
                      print(template.format(stringTime=stringTime, author=author, message=message)[:-1])
client.run('token')

Tags: the代码用户clientlogformatmessageasync
1条回答
网友
1楼 · 发布于 2024-09-24 02:26:38

您应该使用^{}属性来标识特定用户。名称/鉴别器对不能保证唯一

if message.author.id == 12345:
    ...

您可以将print(message.author.id)添加到事件顶部,然后发送消息以获取您自己的id,或者如果您是bot的所有者,则可以使用^{}协同程序获取您自己的信息:

app_info = await client.application_info()
if message.author.id == app_info.owner.id:
    ...

相关问题 更多 >