当命令在DM中时,Python Discord.py机器人程序将角色分配给服务器中的用户



我正试图在服务器中获得一个机器人程序,当用户被dm'ed时,它会赋予用户特定的角色。现在,只有在服务器中使用该命令时,它才能工作。有没有办法把它放到dm频道?

@client.command(brief="Sets favorite programming language", description="Set a role as either Python, C++, C#, or Java",
aliases=["lang"])
async def language(ctx, lang=""):
if isinstance(ctx.channel, discord.DMChannel):
if lang.lower() not in ["python", 'c++', 'java', 'c#']:
await ctx.send("The available languages are Python, C++, C#, and Java.")
else:
await ctx.send("Your role is now " + lang.lower().capitalize() + ".")
await ctx.message.add_reaction("👌")
role = get(client.get_guild(guild_id).roles, name=lang.lower().capitalize())
print(ctx.message.author.guild(guild_id).roles)
roles = [role for role in ctx.message.author.roles if role.name in ['C++', "Java", 'Python', 'C#']]
await ctx.message.author.remove_roles(*roles)
await ctx.message.author.add_roles(role)

您需要找到要将规则提供给该公会中用户的公会。

如果你的机器人是一台服务器的私人机器人,你可以获得服务器id并使用client.get_guild(id)并使用公会作为参考,或者如果你的机器是一个将在多台服务器中使用的公共机器人,你应该添加另一个参数作为公会id,该参数应由用户提供。

如果你要制作一个私人机器人,这里是你编辑过的代码:

@client.command(brief="Sets favorite programming language", description="Set a role as either Python, C++, C#, or Java",
aliases=["lang"])
async def language(ctx, lang=""):
guild_id = 123456789   # Replace it with yours
if lang.lower() not in ["python", 'c++', 'java', 'c#']:
await ctx.send("The available languages are Python, C++, C#, and Java.")
else:
await ctx.send("Your role is now "+lang.lower().capitalize()+".")
await ctx.message.add_reaction("👌")
role = get(client.get_guild(guild_id).roles, name=lang.lower().capitalize())
roles = [role for role in ctx.message.author.roles if role.name in ['C++', "Java", 'Python', 'C#']]
await ctx.message.author.remove_roles(*roles)
await ctx.message.author.add_roles(role)

如果你正在制作一个公共机器人

@client.command(brief="Sets favorite programming language", description="Set a role as either Python, C++, C#, or Java",
aliases=["lang"])
async def language(ctx, *args):
lang = args[0]
guild = client.get_guild(int(args[1])) if isinstance(ctx.channel, discord.DMChannel) else ctx.guild
if lang.lower() not in ["python", 'c++', 'java', 'c#']:
await ctx.send("The available languages are Python, C++, C#, and Java.")
else:
await ctx.send("Your role is now "+lang.lower().capitalize()+".")
await ctx.message.add_reaction("👌")
role = get(ctx.message.guild.roles, name=lang.lower().capitalize())
roles = [role for role in guild.get_member(ctx.author.id).roles if role.name in ['C++', "Java", 'Python', 'C#']]
await ctx.message.author.remove_roles(*roles)
await ctx.message.author.add_roles(role)

最新更新