下载用户发送的 .CSV 文件 [Discord.py]

Zac*_*com 0 python python-3.x discord.py

我正在制作一个不和谐的机器人,它从定期更新的 .CSV 文件中获取数据。为此,我希望我的机器人在 .CSV 文件发送到特定文本通道时下载该文件。我在discord.py中找到了.attachments对象:https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.attachments

如何将这些 .CSV 附件之一下载到我的项目中(我正在使用 Pycharm)

这可能吗?谢谢!

Zac*_*com 5

查看文档:使用 .save() https://discordpy.readthedocs.io/en/latest/api.html#discord.Attachment.save

我设法做到了这一点。

如果有人正在寻找如何自己做到这一点:

if str(message.attachments) == "[]": # Checks if there is an attachment on the message
    return
else: # If there is it gets the filename from message.attachments
    split_v1 = str(message.attachments).split("filename='")[1]
    filename = str(split_v1).split("' ")[0]
    if filename.endswith(".csv"): # Checks if it is a .csv file
        await message.attachments[0].save(fp="CsvFiles/{}".format(filename)) # saves the file
Run Code Online (Sandbox Code Playgroud)

.save() 中的 fp 是新文件的名称。这适用于任何文件类型,如果您只想下载 .txt 文件,请将第二个 if 语句更改为 .txt 而不是 .csv 如果您希望机器人下载所有文件,例如图像、文本文件、csv 文件、python 文件等等。只需去掉 if 语句即可。

希望这可以帮助其他遇到与我相同问题的人