You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过类实现Hikari插件并在加载时引用该类?

问题分析与修复方案

你的代码核心思路是对的——Lightbulb完全支持用类继承lightbulb.Plugin来实现插件,但存在几个小问题导致无法正常运行:

存在的问题

  1. 未定义的类型注解:load函数中的Bot类型没有导入或定义,Lightbulb的Bot实例类型是lightbulb.BotApp,需要修正注解。
  2. 可选优化:显式指定插件名称:虽然继承Plugin会默认用类名作为插件名,但显式指定更清晰,避免类名变化导致插件标识混乱。

修正后的代码

import hikari
import lightbulb

# 显式指定插件名称(可选但推荐)
class Test(lightbulb.Plugin, name="test_plugin"):
    @lightbulb.command(name="ping", description="Sends a ping to the bot")
    @lightbulb.implements(lightbulb.SlashCommand)  # 可选:指定为斜杠命令,否则默认是前缀命令
    async def ping(self, ctx: lightbulb.Context) -> None:
        await ctx.respond(f"Latency: {ctx.bot.heartbeat_latency * 1000:,.0f} ms.")

# 修正类型注解为lightbulb.BotApp
def load(bot: lightbulb.BotApp) -> None:
    bot.add_plugin(Test())

# 主程序示例(需要添加这部分才能运行)
if __name__ == "__main__":
    bot = lightbulb.BotApp(
        token="YOUR_DISCORD_BOT_TOKEN",
        prefix="!",  # 前缀命令的前缀,若只使用斜杠命令可省略
        intents=hikari.Intents.ALL_UNPRIVILEGED | hikari.Intents.MESSAGE_CONTENT
    )
    load(bot)
    bot.run()

额外说明

  • 如果要让命令支持斜杠命令,必须加上@lightbulb.implements(lightbulb.SlashCommand)装饰器,否则默认仅支持前缀触发(比如!ping)。
  • 确保你的Bot令牌正确,并且在Discord开发者门户中开启了对应的意图(比如MESSAGE_CONTENT意图,用于处理前缀命令的消息内容)。

内容的提问来源于stack exchange,提问作者Tristen Dillon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:05:13