0

проблема такова: При запуске всех функций кроме выдачи роли по реакции всё работает отлично и если запускать исключительно с выдачей ролей по реакции всё хорошо,но как только нужно заставить это работать вместе(для этого я прописую intents) бот перестаёт считывать команды,но роли выдаёт и забирает. Я не очень понимаю в программировании и делаю этого бота по инструкциям на ютубе,объясните пожалуйста как решить эту проблему и в чем конкретно дело.

from discord.ext import commands
from discord.utils import get
from discord import utils
import youtube_dl
import os
import config

intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='?', intents=intents)
client.remove_command('help')

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client)) #Просто проверка на запуск
    await  client.change_presence(status=discord.Status.online, activity=discord.Game('?help'))
#Join and leave

@client.command()
async def join(ctx):
    await ctx.channel.purge(limit=1)
    global voice
    channel = ctx.message.author.voice.channel
    voice=get(client.voice_clients,guild=ctx.guild)
    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()
        await ctx.send(f'Бот присоеденился к каналу: {channel}')

@client.command()
async def leave(ctx):
    await ctx.channel.purge(limit=1)
    channel = ctx.message.author.voice.channel
    voice=get(client.voice_clients,guild=ctx.guild)
    if voice and voice.is_connected():
        await voice.disconnect()
        await ctx.send(f'Бот отключился от канала: {channel}')

#Play
@client.command(pass_context=True, brief="Эта песня будет играть следующей  ' [url]'", aliases=['pl'])
async def play(ctx, url: str):
    await ctx.channel.purge(limit=1)
    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
    except PermissionError:
        await ctx.send("Подождите пока текущая песня закончится или используйте команду  '?stop'")
        return
    await ctx.send("Подождите немного музыка обрабатывается ...")
    print("Someone wants to play music let me get that ready for them...")
    voice = get(client.voice_clients, guild=ctx.guild)
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            name = file
            os.rename(file, 'song.mp3')
    voice.play(discord.FFmpegPCMAudio("song.mp3"))
    voice.volume = 100
    voice.is_playing()
    song_name = name.rsplit('-',2)
    await ctx.send(f'Сейчас проигрывается эта композиция: {song_name[0]}')
@client.command()
async def pause(ctx):
    await ctx.channel.purge(limit=1)
    "Ставит аудио на паузу"
    voice = discord.utils.get(client.voice_clients,guild=ctx.guild)
    if voice.is_playing():
        voice.pause()
        await ctx.channel.send(f'{ctx.author.name} Ставит трэк на паузу')
    else:
        await ctx.channel.send(f'Музыка уже на паузе')

@client.command()
async def resume(ctx):
    await ctx.channel.purge(limit=1)
    "Воспроизводит аудио"
    voice = discord.utils.get(client.voice_clients,guild=ctx.guild)
    if voice.is_paused():
        voice.resume()
        await ctx.channel.send(f'{ctx.author.name} Воспроизводит трэк')
    else:
        await ctx.channel.send(f'Музыка уже играет')

@client.command()
async def stop(ctx):
            await ctx.channel.purge(limit=1)
            "Воспроизводит аудио"
            voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
            if voice.is_playing():
                voice.stop()
                await ctx.channel.send(f'{ctx.author.name} Выключает музыку')
            else:
                await ctx.channel.send(f'Сейчас ничего не играет')

#очистка чата
@client.command()
@commands.has_permissions(administrator = True)
async def clear(ctx, amount : int):
    await  ctx.channel.purge(limit = 100)

#Ошибки при вводе не верных значений и недостатке прав
@clear.error
async def clear_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send (f'{ctx.author.name}, обязательно укажите кол-во удаляемых сообщений!')
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f'{ctx.author.name},у вас недостаточно прав!')

#очистка комманд
@client.command()
async def hello( ctx, amount = 1):
    await ctx.channel.purge( limit = amount )
    author = ctx.message.author
    await ctx.send(f'Hello { author.mention }' )

#Кик
@client.command()
@commands.has_permissions(administrator = True)
async def kick( ctx, member: discord.Member, *, reason = None ):
    await ctx.channel.purge( limit = 1)
    await member.kick(reason = reason)
    await ctx.send(f'kick user {member.mention}')

@kick.error
async def kick_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f'{ctx.author.name},у вас недостаточно прав!')

#Бан
@client.command()
@commands.has_permissions( administrator = True)
async def ban(ctx,member: discord.Member, *, reason = None):
    await ctx.channel.purge(limit= 1)
    await member.ban(reason = reason)
    await ctx.send(f'ban user {member.mention}')
@ban.error
async def ban_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f'{ctx.author.name},у вас недостаточно прав!')

#Help
@client.command()
async def help(ctx):
    await ctx.channel.purge(limit=1)
    emb = discord.Embed(title='Навигация по командам')
    emb.add_field(name= '{}clear'.format( '?' ),value='Очистка чата')
    emb.add_field(name= '{}ban'.format( '?' ),value='Бан на сервере')
    emb.add_field(name= '{}kick'.format( '?' ),value='Кик с сервера')
    emb.add_field(name='{}user_mute'.format('?'), value='Мут')
    await ctx.send( embed=emb )

#Mute
@client.command()
@commands.has_permissions(administrator = True)
async def user_mute(ctx, member: discord.Member):
    await ctx.channel.purge(limit=1)
    mute_role = discord.utils.get(ctx.message.guild.roles, name='Mute')
    await member.add_roles(mute_role)
    await ctx.send(f'У {member.mention},ограничение чата за нарушение правил!')

@user_mute.error
async def user_mute_error(ctx, error):
        if isinstance(error, commands.MissingPermissions):
            await ctx.send(f'{ctx.author.name},у вас недостаточно прав!')

#Выдача ролей при подключении
@client.event
async def on_member_join( member ) :
   channel = client.get_channel(672423347174375435)
   role = discord.utils.get( member.guild.roles, id = 830876511850201119 )
   await member.add_roles( role )
   await channel.send(emb = discord.Embed(description=f'Пользователь ``{member.name}``, присоеденился к нам!',color= 0x0c0c0c ))
#Выдача ролей по реакциям

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_raw_reaction_add(self, payload):
        if payload.message_id == config.POST_ID:
            channel = self.get_channel(payload.channel_id)  # получаем объект канала
            message = await channel.fetch_message(payload.message_id)  # получаем объект сообщения
            member = utils.get(message.guild.members,
                               id=payload.user_id)  # получаем объект пользователя который поставил реакцию

            try:
                emoji = str(payload.emoji)  # эмоджик который выбрал юзер
                role = utils.get(message.guild.roles, id=config.ROLES[emoji])  # объект выбранной роли (если есть)

                if (len([i for i in member.roles if i.id not in config.EXCROLES]) <= config.MAX_ROLES_PER_USER):
                    await member.add_roles(role)
                    print('[SUCCESS] User {0.display_name} has been granted with role {1.name}'.format(member, role))
                else:
                    await message.remove_reaction(payload.emoji, member)
                    print('[ERROR] Too many roles for user {0.display_name}'.format(member))

            except KeyError as e:
                print('[ERROR] KeyError, no role found for ' + emoji)
            except Exception as e:
                print(repr(e))

    async def on_raw_reaction_remove(self, payload):
        channel = self.get_channel(payload.channel_id)  # получаем объект канала
        message = await channel.fetch_message(payload.message_id)  # получаем объект сообщения
        member = utils.get(message.guild.members,
                           id=payload.user_id)  # получаем объект пользователя который поставил реакцию

        try:
            emoji = str(payload.emoji)  # эмоджик который выбрал юзер
            role = utils.get(message.guild.roles, id=config.ROLES[emoji])  # объект выбранной роли (если есть)

            await member.remove_roles(role)
            print('[SUCCESS] Role {1.name} has been remove for user {0.display_name}'.format(member, role))

        except KeyError as e:
            print('[ERROR] KeyError, no role found for ' + emoji)
        except Exception as e:
            print(repr(e))
client = MyClient(intents=discord.Intents.all())
client.run(config.TOKEN)```

1 ответ 1

0

Это происходит потому что у вас отдельные команды привязаны к объекту client, который вы объявляете в этой строке:

client = commands.Bot(command_prefix='?', intents=intents)

А функции async def on_raw_reaction_add() и async def on_raw_reaction_remove() находятся внутри класса class MyClient(discord.Client)

И в самом конце, вы переопределяете объект client и задаете новое значение:

client = MyClient(intents=discord.Intents.all())

В итоге вы запускаете только отдельный класс этой строчкой:

client.run(config.TOKEN)

Соответственно, запущенный в отдельном классе бот имеет только 2 функции-события для работы с реакциями. А бот с остальными командами вообще не запущен.


Чтобы избавиться от проблемы, нужно вынести функции класса в общий код и запускать одного цельного бота discord.ext.commands.Bot().

Этот код должен работать:

from discord.ext import commands
from discord.utils import get
from discord import utils
import youtube_dl
import os
import config

client = commands.Bot(command_prefix='?', intents=discord.Intents.all())
client.remove_command('help')

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client)) #Просто проверка на запуск
    await  client.change_presence(status=discord.Status.online, activity=discord.Game('?help'))
#Join and leave

@client.command()
async def join(ctx):
    await ctx.channel.purge(limit=1)
    global voice
    channel = ctx.message.author.voice.channel
    voice=get(client.voice_clients,guild=ctx.guild)
    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()
        await ctx.send(f'Бот присоеденился к каналу: {channel}')

@client.command()
async def leave(ctx):
    await ctx.channel.purge(limit=1)
    channel = ctx.message.author.voice.channel
    voice=get(client.voice_clients,guild=ctx.guild)
    if voice and voice.is_connected():
        await voice.disconnect()
        await ctx.send(f'Бот отключился от канала: {channel}')

#Play
@client.command(pass_context=True, brief="Эта песня будет играть следующей  ' [url]'", aliases=['pl'])
async def play(ctx, url: str):
    await ctx.channel.purge(limit=1)
    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
    except PermissionError:
        await ctx.send("Подождите пока текущая песня закончится или используйте команду  '?stop'")
        return
    await ctx.send("Подождите немного музыка обрабатывается ...")
    print("Someone wants to play music let me get that ready for them...")
    voice = get(client.voice_clients, guild=ctx.guild)
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            name = file
            os.rename(file, 'song.mp3')
    voice.play(discord.FFmpegPCMAudio("song.mp3"))
    voice.volume = 100
    voice.is_playing()
    song_name = name.rsplit('-',2)
    await ctx.send(f'Сейчас проигрывается эта композиция: {song_name[0]}')
@client.command()
async def pause(ctx):
    await ctx.channel.purge(limit=1)
    "Ставит аудио на паузу"
    voice = discord.utils.get(client.voice_clients,guild=ctx.guild)
    if voice.is_playing():
        voice.pause()
        await ctx.channel.send(f'{ctx.author.name} Ставит трэк на паузу')
    else:
        await ctx.channel.send(f'Музыка уже на паузе')

@client.command()
async def resume(ctx):
    await ctx.channel.purge(limit=1)
    "Воспроизводит аудио"
    voice = discord.utils.get(client.voice_clients,guild=ctx.guild)
    if voice.is_paused():
        voice.resume()
        await ctx.channel.send(f'{ctx.author.name} Воспроизводит трэк')
    else:
        await ctx.channel.send(f'Музыка уже играет')

@client.command()
async def stop(ctx):
            await ctx.channel.purge(limit=1)
            "Воспроизводит аудио"
            voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
            if voice.is_playing():
                voice.stop()
                await ctx.channel.send(f'{ctx.author.name} Выключает музыку')
            else:
                await ctx.channel.send(f'Сейчас ничего не играет')

#очистка чата
@client.command()
@commands.has_permissions(administrator = True)
async def clear(ctx, amount : int):
    await  ctx.channel.purge(limit = 100)

#Ошибки при вводе не верных значений и недостатке прав
@clear.error
async def clear_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send (f'{ctx.author.name}, обязательно укажите кол-во удаляемых сообщений!')
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f'{ctx.author.name},у вас недостаточно прав!')

#очистка комманд
@client.command()
async def hello( ctx, amount = 1):
    await ctx.channel.purge( limit = amount )
    author = ctx.message.author
    await ctx.send(f'Hello { author.mention }' )

#Кик
@client.command()
@commands.has_permissions(administrator = True)
async def kick( ctx, member: discord.Member, *, reason = None ):
    await ctx.channel.purge( limit = 1)
    await member.kick(reason = reason)
    await ctx.send(f'kick user {member.mention}')

@kick.error
async def kick_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f'{ctx.author.name},у вас недостаточно прав!')

#Бан
@client.command()
@commands.has_permissions( administrator = True)
async def ban(ctx,member: discord.Member, *, reason = None):
    await ctx.channel.purge(limit= 1)
    await member.ban(reason = reason)
    await ctx.send(f'ban user {member.mention}')
@ban.error
async def ban_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f'{ctx.author.name},у вас недостаточно прав!')

#Help
@client.command()
async def help(ctx):
    await ctx.channel.purge(limit=1)
    emb = discord.Embed(title='Навигация по командам')
    emb.add_field(name= '{}clear'.format( '?' ),value='Очистка чата')
    emb.add_field(name= '{}ban'.format( '?' ),value='Бан на сервере')
    emb.add_field(name= '{}kick'.format( '?' ),value='Кик с сервера')
    emb.add_field(name='{}user_mute'.format('?'), value='Мут')
    await ctx.send( embed=emb )

#Mute
@client.command()
@commands.has_permissions(administrator = True)
async def user_mute(ctx, member: discord.Member):
    await ctx.channel.purge(limit=1)
    mute_role = discord.utils.get(ctx.message.guild.roles, name='Mute')
    await member.add_roles(mute_role)
    await ctx.send(f'У {member.mention},ограничение чата за нарушение правил!')

@user_mute.error
async def user_mute_error(ctx, error):
        if isinstance(error, commands.MissingPermissions):
            await ctx.send(f'{ctx.author.name},у вас недостаточно прав!')

#Выдача ролей при подключении
@client.event
async def on_member_join( member ) :
   channel = client.get_channel(672423347174375435)
   role = discord.utils.get( member.guild.roles, id = 830876511850201119 )
   await member.add_roles( role )
   await channel.send(emb = discord.Embed(description=f'Пользователь ``{member.name}``, присоеденился к нам!',color= 0x0c0c0c ))
#Выдача ролей по реакциям

@client.event
async def on_raw_reaction_add(payload):
    if payload.message_id == config.POST_ID:
        channel = client.get_channel(payload.channel_id)  # получаем объект канала
        message = await channel.fetch_message(payload.message_id)  # получаем объект сообщения
        member = utils.get(message.guild.members,
                           id=payload.user_id)  # получаем объект пользователя который поставил реакцию

        try:
            emoji = str(payload.emoji)  # эмоджик который выбрал юзер
            role = utils.get(message.guild.roles, id=config.ROLES[emoji])  # объект выбранной роли (если есть)

            if (len([i for i in member.roles if i.id not in config.EXCROLES]) <= config.MAX_ROLES_PER_USER):
                await member.add_roles(role)
                print('[SUCCESS] User {0.display_name} has been granted with role {1.name}'.format(member, role))
            else:
                await message.remove_reaction(payload.emoji, member)
                print('[ERROR] Too many roles for user {0.display_name}'.format(member))

        except KeyError as e:
            print('[ERROR] KeyError, no role found for ' + emoji)
        except Exception as e:
            print(repr(e))

@client.event
async def on_raw_reaction_remove(payload):
    channel = client.get_channel(payload.channel_id)  # получаем объект канала
    message = await channel.fetch_message(payload.message_id)  # получаем объект сообщения
    member = utils.get(message.guild.members,
                       id=payload.user_id)  # получаем объект пользователя который поставил реакцию

    try:
        emoji = str(payload.emoji)  # эмоджик который выбрал юзер
        role = utils.get(message.guild.roles, id=config.ROLES[emoji])  # объект выбранной роли (если есть)

        await member.remove_roles(role)
        print('[SUCCESS] Role {1.name} has been remove for user {0.display_name}'.format(member, role))

    except KeyError as e:
        print('[ERROR] KeyError, no role found for ' + emoji)
    except Exception as e:
        print(repr(e))

client.run(config.TOKEN)
1
  • Спасибо,большое за помощь,я частично понял свою ошибку,и кажется заметил где конкретно всё ломалось.За информацию еще раз спасибо.
    – Ренат
    20 мая 2021 в 16:32

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.