find the function that save an image when react to on discord

让人想犯罪 __ 提交于 2019-12-24 05:22:09

问题


I am new to building discord bots.

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.

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.

Thank you very much.


回答1:


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.

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}')

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.

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.



来源:https://stackoverflow.com/questions/53805414/find-the-function-that-save-an-image-when-react-to-on-discord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!