我有一个不和谐的bot驻留在多个服务器中,但是我希望每个服务器都具有加入消息,或者确保我的bot只向加入其中一个的那些人发送欢迎消息。
@client.event #Send new members of the server a message
async 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.event
async 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----------')
答案 0 :(得分:0)
文档here提供on_member_join事件的签名。因此,您可以使用事件提供的成员对象获取加入的服务器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])
根据用例的不同,它也可以扩展为将欢迎消息存储在文件中,并具有使用命令从不和谐中编辑欢迎消息的命令。您还可以将message设置为具有以下字段:
welcome_messages = {my_guild_id: "Hello {0}! Welcome to server")
和使用
await member.send(welcome_messages[guild_id].format(member.mention))
它将用提及新用户代替0
。