如何在Cog Discord.Py中正确定义“客户端”

时间:2020-06-20 19:28:09

标签: python discord.py-rewrite

试图在Cog内部运行加入/离开命令。使用连接命令时收到错误“ NameError:未定义名称'client'”。我尝试改用'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 :(得分:0)

您应该创建一个名为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')

在您的齿轮程序文件中,例如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))