有没有办法在 Discord.py 上直接给某人发消息?

时间:2021-06-04 08:00:48

标签: python discord discord.py

我做了一些研究,发现了一种(可能)旧的直接向某人发送消息的方法。

async def dm(ctx, recipient=None, message=None):
    if message == None or recipient == None:
        await ctx.channel.send("***Error: Incorrect Usage***\nUsage: `/test [recipient] [message]`")
    else:
        pass

    if message is not None:
        if recipient is not None:
        
            message = str(message)
            await client.send_message(recipient, message)

此代码应该做的是获取 dm 和消息的接收者,并直接向此人发送消息(if message == None or recipient == None 是检查缺少的参数,并发送错误消息。) 直接向某人发送消息的正确/最近方式是什么?

2 个答案:

答案 0 :(得分:2)

需要注意的一些事项,如果您正在与 None 进行比较,而不是比较运算符 (==),则更喜欢使用恒等运算符(is 或 {{1} })

其次,除非您进行类型转换,否则 discord.py 默认将函数中的所有参数都作为字符串。您不能向字符串对象“发送”消息。你需要is nottypecast/typehint

最后,您的代码中前两行之后还有一些不必要的 discord.Member 语句

我会重新写的,有什么不懂的可以问

if/else

答案 1 :(得分:0)

您可以使用 target = ctx.guild.get_member(int(recipient)) 然后使用 await target.send(content=message)

获取 Member 对象

您向其发送消息的用户必须位于发送命令的服务器中,我的回答才能通过。