出于某种原因,机器人不断制作新的“Valorant”角色,而且仅适用于“Valorant”。 即使存在也创建。
@client.event
async def on_member_update(before, after):
game_before = [i for i in before.activities if str(i.type) == "ActivityType.playing"]
game_after = [i for i in after.activities if str(i.type) == "ActivityType.playing"]
try:
if game_after:
game_name = game_after[0].name
role = discord.utils.get(after.guild.roles, name=game_name)
if role == None:
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
await after.guild.create_role(name=game_name, hoist=True, mentionable=True, colour=discord.Colour.from_rgb(r,g,b))
role = discord.utils.get(after.guild.roles, name=game_name)
await after.add_roles(role)
elif game_before and not game_after:
game_name = game_before[0].name
role = discord.utils.get(after.guild.roles, name=game_name)
if role in before.roles:
await after.remove_roles(role)
except AttributeError:
print('oops')
答案 0 :(得分:0)
这可能不正确,但我无法测试解决方案。
我的假设是 game_name 末尾包含一个空格,并且正如我能够测试的那样,您不能创建以空格结尾的角色(末尾的空格将被删除)。
因此,例如检查名称为“Valorant”的角色是否在角色列表中时,答案是否定的。解决方案是在创建或搜索角色之前strip 游戏名称。您的代码将是
@client.event
async def on_member_update(before, after):
game_before = [i for i in before.activities if str(i.type) == "ActivityType.playing"]
game_after = [i for i in after.activities if str(i.type) == "ActivityType.playing"]
try:
if game_after:
game_name = game_after[0].name.strip() # I just added the .strip()
role = discord.utils.get(after.guild.roles, name=game_name)
if role == None:
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
await after.guild.create_role(name=game_name, hoist=True, mentionable=True, colour=discord.Colour.from_rgb(r,g,b))
role = discord.utils.get(after.guild.roles, name=game_name)
await after.add_roles(role)
elif game_before and not game_after:
game_name = game_before[0].name
role = discord.utils.get(after.guild.roles, name=game_name)
if role in before.roles:
await after.remove_roles(role)
except AttributeError:
print('oops')
如果不清楚或不起作用,请随时发表评论