为了账号安全,请及时绑定邮箱和手机立即绑定

只向discord.py中特定服务器的用户发送欢迎DM

只向discord.py中特定服务器的用户发送欢迎DM

陪伴而非守候 2023-08-22 17:11:51
我有一个驻留在多个服务器中的不和谐机器人,但是我想为每个服务器提供加入消息,或者确保我的机器人仅向加入其中一台服务器的人发送欢迎消息。@client.event #Send new members of the server a messageasync def on_member_join(member): #Run when a member joins    await member.create_dm() #Create a DM chat with the new user    await member.dm_channel.send(f"Heya, {member.name}! [ETC OF WELCOME MESSAGE]")    print(f'User DM sent:\n----------\nUser: {member.name}\n----------')根据文档, 的唯一参数on_member_join是member,所以这不可能吗?我一直在尝试根据服务器 ID 发送 DM。经过一番研究,我看到了ctx.author.send,但这不起作用:  File "REDACTED", line 312, in _run_event    await coro(*args, **kwargs)  File "REDACTED", line 34, in on_member_join    await ctx.author.send(f"Heya, {member.name}! REDACTED")AttributeError: 'Member' object has no attribute 'author'这是当前形式的完整代码。@client.eventasync def on_member_join(ctx):    current_server = ctx.guild.id    if current_server == server_id:        await ctx.author.send(f"Heya, {member.name}! REDACTED")        print(f'User DM sent:\n----------\nUser: {member.name}\n----------')
查看完整描述

1 回答

?
偶然的你

TA贡献1841条经验 获得超3个赞

您可以使用事件提供的成员对象来获取加入的服务器的 id,并将其与存储的公会 id 进行比较。

对于单个服务器:


# stored_guild_id must be defined before this code appears


@client.event

async def on_member_join(member: discord.Member):

    if member.guild.id == stored_guild_id:

        await member.send(f"Welcome to the server!")

如果您有很多服务器,您可以使用服务器列表:


# stored_guild_ids must be defined above this code. For example:

# stored_guild_ids = [id1, id2]

# where id1 and id2 are guild ids


@client.event

async def on_member_join(member: discord.Member):

    if member.guild.id in stored_guild_ids:

        await member.send(f"Welcome to the server!")

您还可以将其存储为字典,并为每个服务器设置单独的问候语。


# welcome_messages must be defined. For example:

# welcome_messages = {

#    guild_id: "Welcome there!", 

#    guild_id2: 'Hello there!'

#  }

# Again guild_id and guild_id2 are actual guild ids


@client.event

async def on_member_join(member: discord.Member):

    if member.guild.id in welcome_messages.keys():

        await member.send(welcome_messages[member.guild.id])

根据用例,这也可以扩展为将欢迎消息存储在文件中,并具有使用命令编辑来自不和谐的欢迎消息的命令。您还可以将消息设置为包含一个字段,例如: welcome_messages = {my_guild_id: "Hello {0}! Welcome to server") 并使用 await member.send(welcome_messages[guild_id].format(member.mention)) 它将替换0为新用户的提及。


查看完整回答
反对 回复 2023-08-22
  • 1 回答
  • 0 关注
  • 160 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信