【问题标题】:Can you determine if a user can be direct messaged using discord.py?您能否确定是否可以使用 discord.py 直接向用户发送消息?
【发布时间】:2022-01-24 06:40:09
【问题描述】:

我想知道是否允许我的机器人在不先向用户发送消息的情况下向用户发送消息。我写了一些工作代码,但它需要先向用户发送消息。

user=bot.get_user(member.id)
try:
    await user.send("")
except discord.errors.Forbidden:
    canmessage=False
except:
    canmessage=True

代码向用户发送一条空白消息,如果无法向用户发送消息,则返回 False,如果消息发送失败(因为它是空白),则返回 True。 在某些情况下使用时,这可以将机器人标记为垃圾邮件,即使没有收到任何消息。 如果有通过 Discord API 执行此操作的正确方法,我不知道。 我已经搜索了互联网,但我没有找到这方面的信息,也没有找到其他人问过类似的问题。 我想知道这在 Discord API 中是否可行,最好使用 discord.py

【问题讨论】:

    标签: python python-3.x discord discord.py


    【解决方案1】:

    您可以在用户/成员对象上使用 create_dm 方法

    user=bot.get_user(member.id)
    try:
       await user.create_dm()
       can_message_user = True
    except discord.errors.Forbidden:
       can_message_user = False
    #do other stuff
    

    【讨论】:

    • user.create_dmuser.send中被称为internally,所以本质上是一样的。
    • 如果用户之前收到过消息,这似乎不起作用,因为它仍然会返回 true。如果向用户发送消息的能力发生了变化,这仍然会返回 True。
    猜你喜欢
    • 2018-12-16
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2014-07-14
    • 1970-01-01
    • 2013-01-18
    • 2016-08-07
    相关资源
    最近更新 更多