MiraiForum

    • Register
    • Login
    • Search
    • Popular
    • Recent
    • Unsolved
    • Tags
    • Groups
    • 友情链接

    Myrai - 用 Python 直接基于 mirai-core 写机器人!

    其他项目发布
    1
    1
    697
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • rebuild
      rebuild last edited by rebuild

      项目地址:https://github.com/Shimogawa/myrai

      build
      PyPI

      注意:还在测试阶段,很多功能还未实现,仅供测试使用,请多指正

      简介

      为了用 Python 连接 mirai-core,现在需要经过 mirai-api-http。通用方法是使用 mirai-console-loader 进行启动,这样可能对于某些开发者比较麻烦(需要额外的软件与插件)。为了节省这些麻烦,直接通过 py4j 利用 socket 实现了 Python 与 mirai-core 的交互,节省了中间使用 HTTP 的环节,让你更快的部署你的机器人。

      由于用到了 py4j,在 mirai-core 上使用的接口都是 Java 版的。

      使用方法

      例子:https://github.com/Shimogawa/myrai/blob/master/examples/a.py

      要求

      • Python 3.9+
      • Java 11+

      安装

      pip install myrai
      

      初始化

      from myrai import mirai
      
      mirai.init()
      # ========
      bot = mirai.start_bot(114514, "password")  # qq 和 password
      # -------- 或者
      import hashlib
      bot = mirai.start_bot(
          114514,
          hashlib.md5("password".encode("utf-8")).digest()  # 用 MD5
      )
      # ========
      bot.login()
      

      初始化完成后

      使用方式与 mirai-core 一模一样。在 mirai_types 包中提供了大部分(以后会补全)在 mirai-core 中有的类。在 java 包中提供了一部分会经常使用的 Java 类。

      这些类大多用作代码提示,因为运行时它们的类型都不一样,都是 py4j 的 JavaClass,JavaObject 等。

      使用 .new 可以创建它的 Java 对象,使用 .static 能获取到它的类对象。所以想要调用静态方法和其它的方法可以这样:

      def listener(e: MessageEvent):
          e.getSender().sendMessage(
              MessageUtils.static.newChain(
                  [
                      QuoteReply.new(e.getMessage()),
                      PlainText.new("hi"),
                  ]
              )
          )
      

      注意:有些 Java 静态方法 / 成员为了方便使用,可以在 Python 类上直接调用静态方法 / 变量 (实际使用了 classmethod 和 property),而某些不常用的方法没有实现。这些能直接调用的方法会有代码提示。没有代码提示的静态方法请使用 .static。如果你没有代码提示或不放心一直报错,那就使用 .static 调用静态成员。例如:

      MessageUtils.newChain(...)  # OK
      MessageUtils.static.newChain(...)  # OK
      MessageUtils.static.buildMessageChain(...)  # OK
      
      MessageUtils.buildMessageChain(...)  # 不OK
      

      收尾

      import atexit
      from myrai import mirai
      
      atexit.register(mirai.close)
      
      1 Reply Last reply Reply Quote 1
      • 1 / 1
      • First post
        Last post
      Powered by Mamoe Technologies & NodeBB | 友情链接 | 服务监控 | Contact