首页 > 解决方案 > 如何获取 DMChannel 对象?- 不和谐.py

问题描述

我希望机器人检查带有新表情符号的频道,然后根据新表情符号做不同的事情。它正常工作,直到表情符号在私人频道上,这使得bot.get_channel(payload.channel_id)返回无。

我对用户或会员 ID 有同样的问题。payload.member返回 None,但返回bot.get_user(payload.user_id)成员对象。那么,有没有这样的东西,但有渠道?用什么来获取 DMChannel 对象?

@bot.event
async def on_raw_reaction_add(payload):
print(bot.get_channel(payload.channel_id), payload.channel_id) # This line will be deleted, it is used for showing the problem.
if payload.user_id != None:
    channel = bot.get_channel(payload.channel_id)
    msg = await channel.fetch_message(payload.message_id)
    emoji = payload.emoji
    author = payload.member
    if emoji.is_custom_emoji():
        emoji_count = discord.utils.get(msg.reactions, emoji=emoji).count
    else:
        emoji_count = discord.utils.get(msg.reactions, emoji = emoji.name).count
    if payload.channel_id == channel_i:
        if emoji_count > 1:
           ...

输出如果反应在一个DM通道,错误是因为通道是NoneType,是上一行引起的。

None 782664385889959976
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
File "C:\Users\plays\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", 
line 312, in _run_event
await coro(*args, **kwargs)
File "C:\Users\plays\OneDrive\Рабочий стол\Python\bot2.py", line 122, in on_raw_reaction_add
msg = await channel.fetch_message(payload.message_id)
AttributeError: 'NoneType' object has no attribute 'fetch_message'

标签: pythondiscord.py

解决方案


是否有理由需要使用on_raw_reaction_add而不是on_reaction_add?在 99% 的情况下,后者的作用与前者相同。话虽如此,它的参数是reaction, user [documentation]更容易解析,因为它们是 discord.py 对象。

而不是bot.get_channel您可以检索频道,然后只需调用

channel = reaction.channel.message

完整示例:

@bot.event
async def on_reaction_add(reaction, user):
    channel = reaction.message.channel

推荐阅读