【问题标题】:Discord.py sending messages to members on join and giving them rolesDiscord.py 在加入时向成员发送消息并赋予他们角色
【发布时间】:2021-03-26 03:37:18
【问题描述】:

我想让我的机器人向加入我的服务器的人发送直接消息,并在 30 秒后赋予他们角色。 我没有收到任何错误,我的机器人没有崩溃,但它什么也没做。

我的代码:

@bot.event
async def on_member_join(member):
    await member.send('Hi! Welcome to our server, in 30 seconds you will get "Verified" role, please read rules in that time.')
    time.sleep(30)
    await member.add_roles('Verified')

我已经导入了discordtime,并且我的机器人有权限,成员没有被屏蔽的 DM。

【问题讨论】:

  • 您的机器人是否按预期在 30 秒后添加角色?是否可以在测试时添加print 语句以确保调用该函数?
  • 不,它没有给出,我可以发出print 声明,但我认为它在发送消息时崩溃。我试着检查一下
  • 好的,没有检测到新成员。

标签: python discord discord.py


【解决方案1】:

如果您使用的是最新版本的discord.py,这应该可以:

@bot.event   #Event to detect when a user joins the server
async def on_member_join(member):
    await member.send('Hi! Welcome to our server, in 30 seconds you will get "Verified" role, please read rules in that time.')
    time.sleep(30)   #The parameter is in seconds, so it'll wait for 30 seconds
    verifiedRole = discord.utils.get(member.guild.roles, id = THE_ROLE_ID)
    await member.add_roles(verifiedRole)

注意:请记住,机器人将在这 30 秒内停止工作。所以使用time.sleep() 可怕的想法。请改用asyncio.sleep()

@bot.event   #Event to detect when a user joins the server
async def on_member_join(member):
    await member.send('Hi! Welcome to our server, in 30 seconds you will get "Verified" role, please read rules in that time.')
    await asyncio.sleep(30)   #The parameter is in seconds, so it'll wait for 30 seconds
    verifiedRole = discord.utils.get(member.guild.roles, id = THE_ROLE_ID)
    await member.add_roles(verifiedRole)

通过使用这个,机器人在这 30 秒内仍然可以正常工作。记得导入asyncio 而不是time


THE_ROLE_ID替换为来自服务器的角色ID,您可以通过右键单击一个角色获得,如下所示。

【讨论】:

    【解决方案2】:

    要获取member join event,您的机器人需要members intent,默认情况下禁用。要获得它,您必须做两件事:

    转到开发人员门户并在“bot”==>“Privileged Gateway Intents”下切换“SERVER MEMBERS INTENT”以打开。

    在您的机器人中启用它,例如:

    intents = discord.Intents.default()
    intents.members = True
    
    bot = commands.Bot(intents=intents, ...) # command_prefix and other things like that in the ...
    

    【讨论】:

    • 我收到了这个错误:Traceback (most recent call last): File "bot.py", line 5, in <module> intents = discord.Intents.default() AttributeError: module 'discord' has no attribute 'Intents'
    猜你喜欢
    • 2020-09-29
    • 2019-10-18
    • 2021-08-12
    • 1970-01-01
    • 2021-06-10
    • 2019-06-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    相关资源
    最近更新 更多