python-3.x - 找到在不和谐时使用react时保存图像的功能

标签 python-3.x discord discord.py

我是构建不和谐机器人的新手。

所以我创建了一个机器人,设法让他说话等等(我使用Python 3.6)

我现在正在尝试从 channel 复制图像以将其发送到其他地方。 我找不到检查我是否对图像使用react的函数,也找不到保存图像的函数。

我想做的是:如果有人对带有 :white_check_mark: 的图像使用react,机器人就会复制它。

如果有人已经做到了并且可以向我展示,那就太好了。

非常感谢。

最佳答案

图像在消息中的存在方式有两种。它可能是该消息的附件,您可以将图像从计算机上传到 Discord,也可以是嵌入的内容,这就是您在 Discord 中粘贴链接时发生的情况。

用户对消息使用react,而不是图像。每当用户对您的机器人知道的消息使用react时,它就会触发 on_reaction_add 事件。我们可以在该事件中添加代码来检查特定 react ,然后保存文件。

@bot.event
async def on_reaction_add(reaction, user):
    if reaction.emoji == '\N{WHITE HEAVY CHECK MARK}':
        for embed in reaction.message.embeds:
            if embed.url is not discord.Embed.Empty:
                url = embed.url
                name = url[url.rfind('/')+1:]
                async with aiohttp.ClientSession() as session:
                    async with session.get(url) as resp:
                        if resp.status == 200:
                            with open(f'imgs/{name}', 'wb+') as file:
                                file.write(await resp.read())
        for attachment in reaction.message.attachments:
            await attachment.save(f'imgs/{attachment.filename}')

我为最新的重写分支 1.0 版编写了此内容。如果您使用的是较旧的异步分支 0.16,那么您将需要更改附件保存的工作方式。我相信旧版本中的附件被存储为字典,而不是附件对象。

请记住 on_reaction_add is only run for messages that your bot has cached.对旧消息的 react 不会触发该事件。

关于python-3.x - 找到在不和谐时使用react时保存图像的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53805414/

相关文章:

python-3.x - 将 Excel 文档导入 Python

python - discord.py ffmpeg 歌曲一开始播放太快

discord - 尽管已授予 Bot 管理员权限,但仍要求踢成员(member)许可

python - 不和谐 py 中的 @client.command() 对我不起作用

python - 评论 : Built-In Functions

python-3.x - 有没有办法用 Python 读取 Linux 桌面通知?

discord - 用户离开公会后如何从客户端ID获取用户名

bots - 通过 ID : Discord. js 获取消息

javascript - 为什么我无法登录 Discord.js 客户端?

python - 使用切片交换索引?