python - 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}')
解决方案
on_reaction_add
不接受channel
争论,它是user
if reaction.emoji
没有意义,它总是返回一个discord.Emoji
,discord.PartialEmoji
orstr
, neverNone
,True
orFalse
。- 您通过 id 获取频道,检查频道 id 是否与其相同是没有意义的
client.get_channel(id)
不返回布尔值,所以if client.get_channel
也没有意义- 您正在保存、发送然后删除一个文件,您可以简单地将其转换为一个
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
推荐阅读
- excel - 如何为格式错误的地址添加分隔符?
- parsing - 使用 awk 在 $4 和 $5 之间添加一列
- java - 从 Java 应用程序(服务器-客户端)接收数据并将它们显示为 Android 应用程序中的通知
- port - listening port not allowing the connection
- node.js - Cant assign values from a json response in angular 6
- c# - 无法打开本地主机(ERR_CONNECTION_ABORTED)
- reactjs - 解决与 Expo 和 React Native 的依赖冲突
- machine-learning - which class is positive and how to determine real alarm in preparing data for ML
- mongodb - 如何提高MongoDB的搜索性能?
- python - Is there a cleaner Python version of my code for Euler Practice