亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

只向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 關注
  • 195 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號