首页 > 解决方案 > discord.py 的问题“如果 channel.id ==”

问题描述

我正在尝试制作一个机器人,它从通道 A 获取图像,并在有人对其做出反应时将它们发布到通道 B。到目前为止,我已经掌握了所有内容,除了如果有人对频道 C 中的图片做出反应,它还会在频道 B 中发布图片。我正在尝试使用“if channel.id ==”,但到目前为止,当我介绍该行时,机器人只会保存文件,不会发布任何内容。任何意见,将不胜感激

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

标签: pythondiscorddiscord.py

解决方案


  1. on_reaction_add不接受channel争论,它是user
  2. if reaction.emoji没有意义,它总是返回一个discord.Emoji, discord.PartialEmojior str, never None, Trueor False
  3. 您通过 id 获取频道,检查频道 id 是否与其相同是没有意义的
  4. client.get_channel(id)不返回布尔值,所以if client.get_channel也没有意义
  5. 您正在保存发送然后删除一个文件,您可以简单地将其转换为一个discord.File对象并发送它而无需所有这些。

这是您的固定代码:

@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)

注意:您可能想on_raw_reaction_add改用。on_reaction_add如果消息在内部缓存中,则调用它。您可能还想检查通道是否不是discord.DMChannel实例:

is isinstance(reaction_channel, discord.DMCHannel):
    return

推荐阅读