Skip to content
Advertisement

issues with discord.py “if channel.id ==”

I’m trying to make a bot that takes images from channel A and posts them to channel B when someone reacts to it. I have everything down so far except that it’ll also post pictures in channel B if someone reacts to one in channel C. I’m trying to use “if channel.id ==” but so far when I introduce that line the bot will only save the file and will not post anything. any advice would be appreciated

@client.event
async def on_reaction_add(reaction, channel):
    if reaction.emoji:
        for attachment in reaction.message.attachments:
            filename = attachment.filename
            channel = client.get_channel(560327910179864576)
            await attachment.save(f'imgs/{filename}')
            print("File wrote.")
            if channel.id == 560327910179864576:
                await channel.send(file=discord.File(f'imgs/{filename}'))
                os.remove(f'imgs/{filename}')
       

Advertisement

Answer

  1. on_reaction_add doesn’t take the channel argument, it’s user
  2. if reaction.emoji doesn’t make sense, it always returns an discord.Emoji, discord.PartialEmoji or str, never None, True or False.
  3. You’re getting a channel by an id, checking if the channel id is the same as it is doesn’t make sense
  4. client.get_channel(id) doesn’t return a boolean so if client.get_channel also doesn’t make sense
  5. You’re saving, sending and then deleting a file, you can simply convert it to a discord.File object and send it without all that.

Here’s your fixed code:

@client.event
async def on_reaction_add(reaction, user):
    """Sends the message attachments to a channel if the
    message is in a specific channel"""

    reaction_channel = reaction.message.channel
    # Checking if the channel is the one want we want
    if reaction_channel.id != your_id:
        # If not, exit
        return

    message = reaction.message
    # Checking if there are any attachments in the message
    if len(message.attachments) == 0:
        # If not, exit
        return

    # Getting the channel
    channel = message.guild.get_channel(some_id) # I'm using `Guild.get_channel` as it is faster than `client.get_channel`
    
    # Iterating through every attachment and sending it to the channel
    for attachment in message.attachments:
        f = await attachment.to_file()
        await channel.send(file=f)

Note: You probably want to use on_raw_reaction_add instead. on_reaction_add it’s called if the message is in the internal cache. You also probably want to check if the channel is not a discord.DMChannel instance:

is isinstance(reaction_channel, discord.DMCHannel):
    return
Advertisement