首页 > 解决方案 > Discord.py 知道用户是否存在于服务器中

问题描述

很抱歉打扰大家,我知道这是重复的,但我没有评论的等级,所以我不得不再问一次,我看过其他一些关于这个的帖子,他们都说你手动获取公会 ID 并定义它在 on_ready() 中,例如:

@bot.event
async def on_ready():
    guild = bot.get_guild(ID_OF_GUILD) # find ID by right clicking on server icon and choosing "copy id" at the bottom
    if guild.get_member(ID_OF_MEMBER) is not None: # find ID by right clicking on a user and choosing "copy id" at the bottom
        # the member is in the server, do something #
    else:
        # the member is not in the server, do something #

但是我如何在 on_message() 中自动获取公会的 ID,我希望我的机器人在各种服务器上运行,正如你所理解的那样,这实际上是行不通的。

如果您需要更多上下文,它是一个您拥有货币并且可以在用户之间转移它们的机器人,我想检查 message.author 想要转移资金的用户是否真的存在。

在此先感谢,诺埃尔。

标签: pythonpython-3.xdiscorddiscord.py

解决方案


on_message(message),您可以通过以下方式获得公会message.guild

@client.event #Maybe you use client or maybe bot, then you would have to change this to whatever of them you have
async def on_message(message):
    guild = message.guild
    if guild.get_member(ID_OF_MEMBER) is not None: # find ID by right clicking on a user and choosing "copy id" at the bottom
        # the member is in the server, do something #
    else:
        # the member is not in the server, do something #

为了能够使用,您必须在您的应用程序中的开发人员仪表板guild.get_member中启用成员意图,在 bot: 下 ,并在您定义的代码顶部,更改为:会员意向clientclient = ...

intents = discord.Intents.default()
intents.members = True
client = commands.Bot(... whatever you have here, intents=intents) #this line can be different for you!

参考:


推荐阅读