找到对不和谐做出反应时保存图像的功能 [英] find the function that save an image when react to on discord

查看:13
本文介绍了找到对不和谐做出反应时保存图像的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to building discord bots.

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

So I created a bot, manage to make him talk etc. (I use Python 3.6)

我现在正在尝试从频道复制图像以将其发送到其他地方.我找不到检查我是否对图像做出反应的功能,也找不到保存图像的功能.

I am now trying to copy an image from a channel to send it somewhere else. I can't find the function that checks if I reacted to the image neither the one to save an image.

我想要做的是:如果有人对带有 :white_check_mark: 的图像做出反应,机器人会复制它.

What i want to do is : If an someone reacts to an image with the :white_check_mark: , the bot copies it.

如果有人已经做过并且可以展示给我看,那就太棒了.

If someone already did it and can show it to me would be awesome.

非常感谢.

推荐答案

图片在消息中的显示方式有两种.它可能是该消息的附件,您可以在其中将图像从计算机上传到 Discord,或者它可能是嵌入的,当您在 Discord 中粘贴链接时会发生这种情况.

There are two ways an image could be in a message. It could be an attachment to that message, where you upload an image from your computer to Discord, or it could be in an embed, which is what happens when you paste a link in Discord.

用户对消息做出反应,而不是图像.每当用户对您的机器人知道的消息做出反应时,它都会触发 on_reaction_add 事件.我们可以在该事件中放入代码来检查某个反应,然后保存文件.

Users react to messages, not images. Whenever a user reacts to a message your bot is aware of, it triggers the on_reaction_add event. We can put code in that event to check for a certain reaction and then save the files.

@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,那么您将需要更改附件保存的工作方式.我相信旧版本中的附件被存储为字典,而不是附件对象.

I wrote this for the more recent rewrite branch, version 1.0. If you're using the older async branch, 0.16, then you will need to change how attachment saving works. I believe that attachments in the older versions were stored as dictionaries, rather than as attachment objects.

请记住,on_reaction_add 是仅针对您的机器人缓存的消息运行. 对旧消息的反应不会触发事件.

Keep in mind that on_reaction_add is only run for messages that your bot has cached. Reactions on older messages won't trigger the event.

这篇关于找到对不和谐做出反应时保存图像的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆