Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

python - Issues giving role to the bot

I am creating a discord bot to change its own role. Currently I am just trying to give it a role.

import json
import discord
import os
import bs4
from dotenv import load_dotenv
from discord.ext import commands
from datetime import datetime
import time
import re
from string import digits, ascii_letters
from discord.ext.commands import Bot
import aiohttp
from discord.utils import get

load_dotenv()
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
bot = commands.Bot(command_prefix="$")
bot.remove_command('help')
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")

url = "hidden"

@bot.event
async def on_ready():
    await bot.wait_until_ready()
    bot.session = aiohttp.ClientSession()
    print("It's ready - fetching btc price")
    while True:
        async with bot.session.get(url) as resp:
            resp = await resp.text()
            auth = [MY BOTS ID]
            role = [ROLE ID, I.E 9234824234626534]
            await bot.add_roles(auth, role)

error AttributeError: 'Bot' object has no attribute 'add_roles'

How can I give my bot a role or remove a role? It must be in def on_ready()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To add roles, you need the member object. To get this, you need to know the guild that the member is in, so this would be impossible in on_ready() unless you wanted to iterate through every single guild in the guild cache (for guild in bot.guilds: if you're really interested in doing that, but still be sure to read the rest of this).

First off, to even be able to obtain a member object, you need to have your intents enabled. You can do this by just changing your bot ClientUser to commands.Bot(command_prefix="$", intents = discord.Intents.all()), as well as enabling your intents enabled on the Developer Portal.

For the example that I'll show you I will be using a command, but if you really want to use the on_ready() function you can by just replacing every ctx.guild with guild as you iterate through the guild cache as seen above. I also used the discord.utils.get method to define my role, any method that you use is fine so long as you end up with a role object

@bot.command()
def addRole(ctx):
    role = discord.utils.get(ctx.guild.roles, name = "Role Name")
    member = ctx.guild.get_member(bot.user.id)
    await member.add_roles(role)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...