Search Results for

    Show / Hide Table of Contents

    消息的发送与接收

    本项目中发送与接收到的消息同为Message类型。

    消息接收

    在事件处理函数中可通过(e is MessageEvent)判断收到的是否为消息事件,如下:

    static void Main() {
        var client = new HTTPApiClient(...);
        client.OnEventAsync += HandleEvent;
    }
    static async Task<CQResponse> HandleEvent(CQApiClient api, CQEvent e) {
        switch (e) {
        case MessageEvent me:
            await client.SendTextAsync(me.GetEndpoint(), "收到消息");
            return await HandleMessage (me.message);
        }
    }
    

    收到消息事件 e 后可以:

    • 通过 e.GetEndpoint 获取消息的发送位置。
    • 通过 e.message_id 调用撤回接口(pro only)
    • 通过 e.sender 获取消息的发送者

    消息发送

    可以自己构建需要发送的消息,也可以选择直接发送文本消息,亦或是发送定义好的常用消息

    static void Main() {
        var client = HTTPApiClient(...);
        //////////////////////
        client.SendTextAsync("text");
        //////////////////////
        client.SendMessageAsync(
            MessageType.private_/group_/discuss_,
            qq号/群号/讨论组号,
            new Message (
                new ElementText("part1"),
                new ElementFace(1),//1-170
                new ElementText("part2")
            )
        );
        //////////////////////
    }
    

    除了可以主动发送消息,在接收到特定事件时,也可以通过在OnEvent中返回CQResponse来发送消息,完整列表可以在这里找到

    消息构建

    与cqhttp以及酷Q的消息/消息段的概念相对应,cqhttp.Cyan中的消息(Message)也由消息元素(Elements)组成。完整的Element列表可以在这里找到。

    Message/Element之间支持判等、相加的操作:

    Message a = new Message(new ElementText("asdf"), new ElementFace(4));
    Message b = new Message(new ElementText("asdf"));
    b += new ElementFace(4);
    Console.WriteLine(a == b);//True
    Message c = new Message(new ElementText("asdf"), new ElementFace(3));
    Console.WriteLine(a == c);//False
    a + c;//asdf[CQ:face, id=4]asdf[CQ:face, id=3]
    

    Element相加会返回一个Message对象

    Message a = new ElementText("asdf")+new ElementFace(1);
    
    • Improve this Doc
    ☀
    ☾