Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

python - How to get a DMChannel object? - discord.py

I want the bot to check what is the channel with the new emoji and then do different things, depends on what the new emoji is. It works properly until the emoji is on a private channel, which makes the bot.get_channel(payload.channel_id) return None.

I had the same problem with a user or member id. The payload.member returns None, but bot.get_user(payload.user_id) returns the member object. So, is there something like this but with channels? What is used to get the DMChannel object?

@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:
           ...

The output if the reaction is in a DM channel, the error occurs because the channel is NoneType, which is caused by the previous line.

None 782664385889959976
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
File "C:UsersplaysAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordclient.py", 
line 312, in _run_event
await coro(*args, **kwargs)
File "C:UsersplaysOneDriveРабочий столPythonot2.py", line 122, in on_raw_reaction_add
msg = await channel.fetch_message(payload.message_id)
AttributeError: 'NoneType' object has no attribute 'fetch_message'
question from:https://stackoverflow.com/questions/65642072/how-to-get-a-dmchannel-object-discord-py

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is there a reason you need to use on_raw_reaction_add rather than on_reaction_add? In 99% of cases the latter does the same as the former. That being said its parameters are reaction, user [documentation] which are much more easily parseable, because they are discord.py objects.

Rather than retrieving the channel by bot.get_channel you can then just can just call

channel = reaction.channel.message

Full example:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...