如何将bot.anything与嵌齿轮配合使用?

时间:2020-07-07 22:46:23

标签: python bots discord discord.py

我试图制造一个不和谐的机器人并实现音乐功能的Um,为此,我需要使用类似的代码 bot.voice_clients ,如果将它们放入其中,该命令将无法正常工作但是,如果我放入main.py

,则任何齿轮文件都可以完美运行
import discord
from discord.ext import commands
from discord.utils import get

class music(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

@bot.command()
async def join(self, ctx):
    global voice
    channel = ctx.message.author.voice.channel
    voice = get(self.voice_clients, guild=ctx.guild)

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

    await ctx.message.add_reaction('\U0001F44C')

@bot.command()
async def leave(self, ctx):
    channel = ctx.message.author.voice.channel
    voice = get(self.voice_clients, guild=ctx.guild)

    if voice and voice.is_connected():
        await ctx.message.add_reaction('\U0001F44B')
        await voice.disconnect()
    else:
        await ctx.send("Im not connected")

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

如果尝试这样做,这就是我进入终端机的原因


PS D:\Documentos\Predo\yunna-bot\yunna-bot-master> & C:/Users/pedro/AppData/Local/Programs/Python/Python38-32/python.exe d:/Documentos/Predo/yunna-bot/yunna-bot-master/main_test.py
Traceback (most recent call last):
  File "C:\Users\pedro\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 596, in _load_from_module_spec
    spec.loader.exec_module(lib)
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "d:\Documentos\Predo\yunna-bot\yunna-bot-master\cogs\music.py", line 10, in <module>
    @bot.command()
NameError: name 'bot' is not defined

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "d:/Documentos/Predo/yunna-bot/yunna-bot-master/main_test.py", line 33, in <module>
    bot.load_extension(f'cogs.{filename[:-3]}')
  File "C:\Users\pedro\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 653, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\pedro\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 599, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.music' raised an error: NameError: name 'bot' is not defined
PS D:\Documentos\Predo\yunna-bot\yunna-bot-master> 

1 个答案:

答案 0 :(得分:0)

您应查看cogs page of the documentation的示例。为此,您需要使用commands.command而不是bot.command作为装饰器(因为定义了cog类时,您没有bot实例)

class music(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def join(self, ctx):
        ...