繁体   English   中英

discord.py 1.5.0:NameError:未定义名称“客户端”

[英]discord.py 1.5.0: NameError: name 'client' is not defined

我是discord.py的新手,并遵循关于 cogs 的教程。 我遵循了教程告诉我的所有内容,但是在运行命令时出现名称错误。

这是代码:

./bot.py

import os
import discord
from discord.ext import commands

client = commands.Bot(command_prefix = '/')

@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.online, activity=discord.Game('Under Development'))
    print('Bot Online')

@client.command()
async def load(ctx, extension):
    client.load_extension(f'cogs.{extension}')

@client.command()
async def unload(ctx, extension):
    client.unload_extension(f'cogs.{extension}')

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')

client.run(os.environ['TOKEN'])

./cogs.commands.py

import discord
from discord.ext import commands

class Commands(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def ping(self, ctx):
        await ctx.send(f'Network Delay: **{round(client.latency * 1000)} ms**')

def setup(client):
    client.add_cog(Commands(client))

当我在不和谐消息框中输入/ping时,我得到了这个回溯

回溯(最近一次调用):文件“C:\\Users\\bryan\\source\\repos\\discord_music_bot\\env\\lib\\site-packages\\discord\\ext\\commands\\bot.py”,第 903 行,调用 await ctx。 command.invoke(ctx) 文件“C:\\Users\\bryan\\source\\repos\\discord_music_bot\\env\\lib\\site-packages\\discord\\ext\\commands\\core.py”,第 859 行,在调用中等待注入(*ctx .args, **ctx.kwargs) 文件“C:\\Users\\bryan\\source\\repos\\discord_music_bot\\env\\lib\\site-packages\\discord\\ext\\commands\\core.py”,第 94 行,包装引发 CommandInvokeError (exc) from exc discord.ext.commands.errors.CommandInvokeError: 命令引发异常: NameError: name 'client' is not defined

感谢@Brian,我终于修复了错误。 我写client.latency而不是self.client.latency

async def ping(self, ctx):
        await ctx.send(f'Network Delay: **{round(self.client.latency * 1000)} ms**')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM