D
D
Dima Remezkov2022-01-03 13:17:19
Python
Dima Remezkov, 2022-01-03 13:17:19

Can't start the bot?

I ran into a problem that when I add intents, the bot crashes.

import discord
import asyncio
from discord.ext import commands
from Cybernator import Paginator as pag
from discord.ext.commands.help import Paginator
from discord.flags import Intents
from config import TOKEN

bot = commands.Bot(command_prefix="$", intents = discord.Intents.all())
bot.remove_command("help")

@bot.event
async def on_ready():
    print(f"> {bot.user} successfully loaded!")

    await bot.change_presence(status = discord.Status.do_not_disturb, activity=discord.Game("$help"))

@bot.event
async def on_member_join(member):
    channel = member.guild.system_channel
    await channel.send(f"Привет, {member.mention}! Добро пожаловать к нам в 『』Ponchik Studio!")
    

@bot.command(name="clear")
@commands.has_permissions(administrator=True)
async def clear(ctx, amount=None):
    await ctx.channel.purge(limit=int(amount))

@bot.command(name="help")
async def help(ctx):
    embed1 = discord.Embed(title="Страница 1",
    description='$clear - очистка чата.\n\
                $kick - кикает участника.\n\
                $ban - банит участника.\n\
                $unban - разбанивает участника')
    embed2 = discord.Embed(title="Страница 2",
    description="$mute - мутит участника.\n\
                $unmute - убирает мут с участника.")
    embeds = [embed1, embed2]

    message = await ctx.send(embed = embed1)
    page = pag(bot, message, only=ctx.author, use_more=False, embeds = embeds)
    await page.start()


    @bot.command(name='kick')
    @commands.has_permissions(administrator=True)
    async def kick(ctx, member: discord.Member, *, reason=None):
        await member.kick(reason=reason)
        await ctx.send("Участник был кикнут!")

@bot.command(name="ban") # Создаем команду, и даем ей имя. Чтобы можно было обращаться через !ban
@commands.has_permissions(administrator=True) # Делаем команду только для администраторов
async def ban(ctx, user:discord.User, duration: int): # Создаем функцию, в который мы передаем человека которого будем банить, и время.
    if duration:
        await ctx.guild.ban(user) # баним юзера
        await ctx.send(f"Пользователь {user.mention}, был заблокирован!") # Пишем что пользователь заблокирован.
        await asyncio.sleep(duration) # ждем время
        await ctx.guild.unban(user) # разбаниваем юзера
    else:
        await ctx.send("Укажите время!")

 

@bot.command(name="unban")
@commands.has_permissions(administrator=True)
async def unban(ctx, *, user=None):

    try:
        user = await commands.converter.UserConverter().convert(ctx, user)
    except:
        await ctx.send("Ошибка: пользователь не найден!")
        return

    try:
        bans = tuple(ban_entry.user for ban_entry in await ctx.guild.bans())
        if user in bans:
            await ctx.guild.unban(user, reason="Ответственный модератор: "+ str(ctx.author))
        else:
            await ctx.send("Пользователь не забанен!")
            return

    except discord.Forbidden:
        await ctx.send("У меня нет разрешения на разблокировку!")
        return

    except:
        await ctx.send("Разбан не удался!")
        return

    await ctx.send(f"Пользователь удачно разбанен {user.mention}!")

@bot.command(name="roll")
async def roll(ctx):
    await ctx.send("Команда в разработке!")

@bot.command(name="mute")
async def mute(ctx, member: discord.Member, time:int, *, reason=None):
    if reason:
        emb = discord.Embed(title="Участник Был Замучен!", colour=discord.Color.blue())
        await ctx.channel.purge(limit=1)

        emb.set_author(name=member.name, icon_url=member.avatar_url )
        emb.set_footer(text="Его замутил {}".format(ctx.author.name ), icon_url=ctx.author.avatar_url )
        
        await ctx.send(embed=emb)
        muted_role = discord.utils.get(ctx.message.guild.roles, name="Muted")
        await member.add_roles(muted_role)
        
        # Спим X секунд, перед тем как снять роль.
        await asyncio.sleep(time) 
        # Снимаем роль замученного.
        await member.remove_roles(muted_role)
    else:
        await ctx.send("Укажите причину!")
    

@bot.command(name="unmute")
async def unmute(ctx, member: discord.Member):
    muted_role = discord.utils.get(ctx.message.guild.roles, name="Muted")
    await member.remove_roles(muted_role)
    await ctx.send("Участник размучен!")

bot.run(TOKEN)

Mistake:
C:\Games\Мое\DiscordBot>py main.py
Traceback (most recent call last):
  File "C:\Games\Мое\DiscordBot\main.py", line 124, in <module>
    bot.run(TOKEN)
  File "C:\Users\remez\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 723, in run
    return future.result()
  File "C:\Users\remez\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 702, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\remez\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 666, in start
    await self.connect(reconnect=reconnect)
  File "C:\Users\remez\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 601, in connect
    raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000021E6D6C2D40>
Traceback (most recent call last):
  File "C:\Users\remez\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\remez\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Users\remez\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
    self._check_closed()
  File "C:\Users\remez\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RuslanUC, 2022-01-03
@Leqort

The error text says that you are trying to use intents that are not allowed on the application page. Go to https://discord.com/developers/applications/ select your bot, go to the "Bot" tab, then check all the boxes in the "Privileged Gateway Intents" category (presence intent, server members intent and message content intent). After that try to start your bot with "discord.Intents.all()", most likely the problem will be solved.

Z
zxcigan, 2022-01-03
@zxcigan

Try just importing the config and together bot.run(TOKEN) -> client.run(config.TOKEN)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question