Reputation: 29
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()
Upvotes: 1
Views: 50
Reputation: 1318
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)
Upvotes: 1