如何在 Cog Discord.Py 重写中正确定义 'client'

How to define 'client' correctly in a Cog Discord.Py rewrite

正在尝试让加入/离开命令在 Cog 内部运行。使用命令 Join 时出现错误“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}")

您应该创建一个名为 cogs 的文件夹,其中将包含每个齿轮。
当你有齿轮时,你必须用 'commands.command()' 替换每个 client.commands(),用 self.client

替换每个 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))