Как создавать и назначать роли с помощью discord.py? - PullRequest
1 голос
/ 26 мая 2020

Я пытаюсь создать совершенно новую роль в Discord (с помощью discord.py), но все, что я пытаюсь, не работает. Я уже пробовал

await guild.create_role(name("R3KT")) #NameError: name 'guild' not defined

и

author = ctx.message.author
await client.create_role(author.server, name="role name") #NameError: name 'ctx' not defined

. Я пробовал изменить ctx и гильдию на «клиент», но это все равно не сработало. при необходимости я пришлю весь код (без названия Discord и ключа бота)

вот весь код:

import discord

token = "bot-key"
client = discord.Client()


@client.event
async def on_ready():
    print("Bot is online and connected to Discord")


@client.event
async def on_message(message):

    message.content = message.content.upper()

    if message.author == client.user:
        return

    if message.content.startswith("AS HELLO"):
        await message.channel.send("works")

    elif message.content.startswith("AS CREATEROLE"):
        if str(message.author) == "myDiscName#6969":
            author = message.author
            await discord.create_role(author.server, name="R3KT")

    elif message.content.startswith("AS GIVEROLE"):
        if str(message.author) == "myDiscName#6969":
            print("give role")


client.run(token)

Ответы [ 2 ]

0 голосов
/ 26 мая 2020

Вы не хотите проверять по имени и номеру (поскольку вы можете изменить это, если у вас есть нитро), вы должны проверять по идентификатору, который является уникальным для каждого пользователя и неизменяемым.

Также обратите внимание, что server обозначается как guild в discord.py.

    elif message.content.startswith("AS CREATEROLE"):
        if message.author.id == YOUR_ID_GOES_HERE: # find your id by right clicking on yourself and selecting "copy id" at the bottom of the menu of options
            author = message.author
            # create a role named "R3KT" that has the permissions "Administrator" that has the color "white" that is not displayed separately and is not mentionable by everyone
            await message.guild.create_role(name="R3KT", permissions=discord.Permissions(8), colour=discord.Colour.from_rgb(255, 255, 255), hoist=False, mentionable=False)

Целочисленный калькулятор разрешений

discord.Guild.create_role

С присвоением себе роли:

    elif message.content.startswith("AS GIVEROLE"):
        if message.author.id == YOUR_ID_GOES_HERE:
            user = message.author
            await user.add_roles(message.guild.get_role(ROLE_ID_GOES_HERE), reason='Someone did a giverole bot command') # left click on the role and click "copy id"

discord.Member.add_roles

discord.Guild.get_role

0 голосов
/ 26 мая 2020

Во втором примере, который вы предоставили, похоже, что вы используете mi sh -ma sh между старыми d.py (0.16.x) docs и d.py rewrite (1.x).

Убедитесь, что у вас установлена ​​самая последняя версия (перезапись), поскольку asyn c больше не поддерживается.

Вот пример с декоратором команд (использование: !newrole Member)

@client.command()
async def newrole(ctx, *, rolename=None):
    if not rolename:
        await ctx.send("You forgot to provide a name!")
    else:
        role = await ctx.guild.create_role(name=rolename, mentionable=True)
        await ctx.author.add_roles(role)
        await ctx.send(f"Successfully created and assigned {role.mention}!")

mentionable kwarg не является обязательным - по умолчанию он равен False, если не указан - я просто установил его на True для примера. Вы также можете написать свои собственные разрешения для роли.


И еще один пример с использованием on_message - вместо этого рекомендуется использовать декоратор команд, так как с аргументами легче работать

async def on_message(message):
    args = message.content.split(" ")[2:] # 2: because prefix contains space
    if message.content.lower().startswith("as createrole"):
        role = await message.guild.create_role(name=" ".join(args))
        await message.author.add_roles(role)
        await message.channel.send(f"Successfully created and assigned {role.mention}!")

Ссылки:

...