TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'

Написал бота для дискорда, после добавления функции edit и delete с проверкой на роль 'Администратор', появляется данная ошибка, читал инфу по данной теме, везде написано про новый параметр intents, который был корректно написан с самого начала описания программы. Ниже приведён код:

import discord
from discord.ext import commands
import asyncio
import datetime
import os
import matplotlib.pyplot as plt

intents = discord.Intents.all()
intents.typing = False
intents.presences = False
intents.messages = True
intents.message_content = True
intents.members = True
bot = commands.Bot(command_prefix='*', intents=intents)

created_roles = {}
currency_rates = {}
country = {}
industry_status = {}

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='*')
country = {}
industry_status = {}

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.command()
async def create_country(ctx, name):
    global country
    country[ctx.author.name] = name
    with open("base.txt", "a") as file:
        file.write(f"{ctx.author.name}: {name}\n")
    await ctx.send(f"Country {name} created for user {ctx.author.name}")

    role = await ctx.guild.create_role(name=name)
    await ctx.author.add_roles(role)
    await ctx.send(f"Role {name} created and assigned to user {ctx.author.name}")

@bot.command()
async def get_industry_status(ctx, country):
    global industry_status
    if country in industry_status:
        await ctx.send(f"The industry status of {country} is {industry_status[country]}")
    else:
        await ctx.send("Country not found")

@bot.command()
@commands.has_role("Администратор")
async def edit_country(ctx, name, new_name):
    global country
    if name in country:
        country[name] = new_name
        await ctx.send(f"Country {name} has been updated to {new_name}")
    else:
        await ctx.send(f"Country {name} not found")

@bot.command()
@commands.has_role("Администратор")
async def delete_country(ctx, name):
    global country
    if name in country:
        del country[name]
        await ctx.send(f"Country {name} has been deleted")
    else:
        await ctx.send(f"Country {name} not found")

@bot.command()
async def help(ctx):
    embed = discord.Embed(title="Список команд", description="Список всех доступных команд:")
    embed.add_field(name="*create_country [название]", value="Создает страну с указанным названием и присваивает ее пользователю", inline=False)
    embed.add_field(name="*get_industry_status [страна]", value="Возвращает статус отрасли экономики указанной страны", inline=False)
    embed.add_field(name="*help", value="Выводит список всех команд", inline=False)
    await ctx.send(embed=embed)

def get_next_filename():
    i = 1
    while os.path.exists(f"graphic_{i}.png"):
        i += 1
    return f"graphic_{i}.png"

def get_nextfilename():
    i = 1
    while os.path.exists(f"graphic{i}.png"):
        i += 1
    return f"graphic_{i}.png"

def save_currency_rate(valute_name, rate):
    with open("base.txt", "a") as file:
        file.write(f"{valute_name}: {rate}\n")

def get_currency_rate(valute_name):
    if valute_name in currency_rates:
        return currency_rates[valute_name]
    else:
        return 0

def update_currency_rates():
    for valute_name in currency_rates:
        currency_rates[valute_name] += 100

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')
    await bot.wait_until_ready()
    while not bot.is_closed():
        update_currency_rates()
        await asyncio.sleep(86400)  # Обновление курсов каждые 24 часа

@bot.command()
async def create_valute(ctx, valute_name):
    if ctx.author.id in created_roles:
        await ctx.send("Вы уже создали роль ранее.")
    else:
        role = await ctx.guild.create_role(name=valute_name)
        await ctx.author.add_roles(role)
        await ctx.send(f"Роль с названием '{valute_name}' была создана и выдана вам.")
        created_roles[ctx.author.id] = True
        currency_rates[valute_name] = 0

@bot.command()
async def graphic(ctx, valute_name=None):
    if valute_name is None:
        await ctx.send("Укажите название валюты.")
        return

    if valute_name not in created_roles:
        await ctx.send("Такая валюта не существует.")
        return

    rate = get_currency_rate(valute_name)

    current_time = datetime.datetime.now()
    fixed_rate = rate

    plt.figure(facecolor=discord.Color.dark_gray().to_rgb())
    x = [current_time - datetime.timedelta(hours=5),
         current_time - datetime.timedelta(hours=4),
         current_time - datetime.timedelta(hours=3),
         current_time - datetime.timedelta(hours=2),
         current_time - datetime.timedelta(hours=1)]
    y = [fixed_rate, fixed_rate, fixed_rate, fixed_rate, fixed_rate]
    plt.plot(x, y)
    filename = get_next_filename()
    plt.savefig(filename)
    await ctx.send(f"График для валюты '{valute_name}':", file=discord.File(filename))
    save_currency_rate(valute_name, fixed_rate)

bot.run('Токен')

Полный код ошибки:

Traceback (most recent call last):
  File "d:\ProgrammsVSC\DSbot\Body.py", line 24, in <module>
    bot = commands.Bot(command_prefix='*')
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'

Ответы (1 шт):

Автор решения: zrx

Дело в том, что Discord обновили API ботов, и теперь обязательно нужно использовать intents.

В Вашем коде строчку

bot = commands.Bot(command_prefix='*')

Нужно заменить на

bot = commands.Bot(command_prefix='*', intents=discord.Intents.all())

И всё будет работать.

Почитать подробнее про Intents - тут.

→ Ссылка