获取Python Discord Bot to DM硬编码接收者加入的人的名字



我做了一些研究,我知道使用on_member_join()来知道用户何时加入服务器。但是我很难找到如何获得该用户的用户名,并用该用户名向我的个人帐户发送消息。这样做的原因是因为我的不和服务器相当小,我每天都有新用户,只有我想得到通知,这样我就可以在他们加入时亲自与他们交谈。

您可以通过在函数定义中引用Member对象来轻松获取它。链接到on_member_join事件的Discord.py引用。之后,您可以使用fetch_user("您的个人ID")方法并将member.user发送给您的dm。

示例代码:

import discord
# Starting the client with all Intents so you can use the on_member_join() event.
Client = discord.Client(intents=discord.Intents.all())
@Client.event
def on_member_join(member):
your_user = Client.fetch_user("your id")
your_dm = await your_user.dm_channel
# Verify if there is already a DM, otherwise create the channel
if not your_dm:
your_dm = await your_user.create_dm()
await your_dm.send(member.user)

您可能需要将以下代码作为您的bot定义来启用members意图:

intents = discord.Intents.default()
intents.members = True
# If you're using discord.Client():
client = discord.Client(intents=intents)
# If you're using commands.Bot():
client = commands.Bot(options_here,intents=intents)

在此之后,您可以将DM发送到用户对象(如通道),并使用member.user获取新成员的名称:

def on_member_join(member):
dmUser = await client.fetch_user(579450993167564811)
await dmUser.send(member.user) # Sends member's name to dmUser via DM

最新更新