【问题标题】:Python Discord bot give roles on joinPython Discord 机器人在加入时提供角色
【发布时间】:2021-08-14 22:59:41
【问题描述】:

我正在尝试制作一个简单的机器人,它将为刚加入服务器的人分配一个角色。

代码:

import discord
import os
from discord.utils import get

bot_acces_token = os.environ['token']

intents = discord.Intents.default()
intents.members = True

client = discord.Client(intents=intents)

@client.event
async def on_member_join(member):
  role = discord.utils.get(member.server.roles, id="123456789")
  await client.add_roles(member, role)

@client.event
async def on_ready():
  print('Bot is ready')

client.run(bot_acces_token)

但不幸的是我收到了这个错误:

Ignoring exception in on_member_join
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 17, in on_member_join
    role = discord.utils.get(member.server.roles, id="123456789")
AttributeError: 'Member' object has no attribute 'server'

【问题讨论】:

  • 您尝试添加角色的方式已过时。
  • server 不是 discordpy 中任何部分的有效属性。属性其实是guild

标签: python discord bots


【解决方案1】:

您尝试获得结果的方式已经过时并且已经改变。

您需要改变定义机器人的方式。您需要更改这段代码:

intents = discord.Intents.default()
intents.members = True

client = discord.Client(intents=intents)

您必须使用Command API 才能使用event。将这些行更改为:

client = commands.Bot(command_prefix='!', intents=discord.Intents.all())

在脚本顶部添加导入语句:

from discord.ext import commands

也将其删除:

from discord.utils import get

试试这个:

@client.event
async def on_member_join(member):
  role = discord.utils.get(member.guild.roles, id="123456789")
  await member.add_roles(role)

您需要使用member.guild.roles 而不是您实际使用的那个。您还需要使用await member.add_roles(role) 而不是您使用的那个。它会为你工作。如果您仍然有错误,请询问!

谢谢! :D

【讨论】:

  • 我试过了,但这次又遇到了另一个错误。忽略 on_member_join Traceback 中的异常(最后一次调用):文件“/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py”,第 343 行,在 _run_event await coro(*args, * *kwargs) 文件“main.py”,第 18 行,在 on_member_join 等待 member.add_roles(role) 文件“/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py”,第 777 行, 在 add_roles 中等待 req(guild_id, user_id, role.id, reason=reason) AttributeError: 'NoneType' object has no attribute 'id'
  • @OqOq 你做了所有的事情吗?我编辑了答案。
  • 是的,我尝试了你让我做的所有事情,但它还是让我遇到了同样的错误。
  • @OqOq 别担心!我会为你写一段代码并给出适当的解释。
  • 你不应该使用 "" 因为它是一个 int 数据类型
【解决方案2】:

这就是解决方案:

import discord
from discord.ext import commands
import os

client = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@client.event
async def on_member_join(member):
  channel = client.get_channel(1234567)
  role = discord.utils.get(member.guild.roles, id=1234567)
  await member.add_roles(role)

【讨论】:

    猜你喜欢
    • 2018-10-11
    • 2020-12-24
    • 1970-01-01
    • 2018-06-26
    • 2019-04-20
    • 2020-12-30
    • 2021-07-20
    • 2017-11-08
    • 1970-01-01
    相关资源
    最近更新 更多