Как правильно определить `` клиент '' в перезаписи Cog Discord.Py - PullRequest
0 голосов
/ 20 июня 2020

Попытка заставить работать команду присоединения / выхода внутри Cog. Получение ошибки «NameError: имя 'client' не определено» при использовании команды Join. Я попытался использовать вместо этого self.client, но получаю сообщение об ошибке, что self не определен. Любая помощь будет очень признательна. Спасибо :)

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

class music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    #Events

    #Commands
    #Join Voice Chat
    @commands.command(pass_context=True, aliases=['Join', 'JOIN'])
    async def join(self, ctx):
        channel = ctx.message.author.voice.channel
        voice = get(self.client.voice_clients, guild=ctx.guild)

        if voice and voice.is_connected():
            await voice.move_to(channel)
        else:
            voice = await channel.connect()

        await voice.disconnect()

        if voice and voice.is_connected():
            await voice.move_to(channel)
        else:
                voice = await channel.connect()
                print(f"Bot has connected to {channel}\n")

                await ctx.send(f"Connected to {channel}")

1 Ответ

0 голосов
/ 21 июня 2020

Вы должны создать папку с именем cogs, в которой будет содержаться каждый Cog.
Когда у вас есть Cogs, вы должны заменить каждое client.commands() на 'commands.command ()' и каждое client вхождение на self.client

В основном файле программы, например, bot.py:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!')
initial_extensions = ['cogs.my_cog'] #cog.(filename)

if __name__ == '__main__':
    for extension in initial_extensions:
        bot.load_extension(extension)

@client.event
async def on_ready():
    print('Bot is ready')

bot.run('Your token')

В файле программы Cog, например, my_cog.py:

import discord
from discord.ext import commands

class My_cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(pass_context=True, aliases=['Join', 'JOIN'])
    async def join(self, ctx):
        channel = ctx.message.author.voice.channel
        voice = get(self.bot.voice_clients, guild=ctx.guild)

        if voice and voice.is_connected():
            await voice.move_to(channel)
        else:
            voice = await channel.connect()

def setup(bot):
    bot.add_cog(My_cog(bot))
...