[Mirai-js] How to make a QQ robot quickly

Quick start

For complete documentation, see -> https://Drincann.github.io/Mirai-js

Clone the project to the local:

$ git clone https://github.com/Drincann/Mirai-js.git

Interface inlet located ./src/Mirai-js.jsdeconstruction from the file:

const {
    
     Bot, Message } = require('./src/Mirai-js');

log in

You can enter it directly in the mirai-console/login qq password .

If you want to remote control mirai-console login, by Botclass method sendCommendto send commands:

await Bot.sendCommand({
    
    
    // mirai-api-http 服务的网络位置
    baseUrl: 'http://example.com:8080',
    // 在 mirai-api-http 的配置中设置的 authKey
    authKey: 'authKey',
    // 指令名
    command: '/login',
    // 指令参数列表,这条指令等价于 /login 1019933576 password
    args: ['1019933576', 'password'],
});

Pay attention to the return value of this method, known problems:

'Login failed: Mirai could not complete the slider verification. Use the protocol ANDROID_PHONE to force the slider verification, please change the protocol and try again. See also: https://github.com/project-mirai/mirai-login-solver-selenium '

Do not log in repeatedly!

establish connection

Obtain an Botinstance, and then call a openmethod on the instance to connect to your mirai-api-http service:

const bot = new Bot();

// 连接到一个 mirai-api-http 服务
await bot.open({
    
    
    baseUrl: 'http://example.com:8080',
    authKey: 'authKey',
    // 要绑定的 qq,须确保该用户已在 mirai-console 登录
    qq: 1019933576,
});

Repeated calls to openthe method will re-establish the connection, if necessary reestablish the connection, you can pass parameters you want to modify.

If no parameters are provided, the original configuration will be maintained.

send messages

Send a message to a friend:

await bot.sendMessage({
    
    
    // 好友 qq 号
    friend: '1019933576',
    // Message 实例,表示一条消息
    message: new Message().addText('hello world!').addImageUrl('http://exapmle/image.jpg')});

note! These methods are asynchronous

You can also use the original format required by the mirai-api-http interface as the message.

Send a message to the group:

await bot.sendMessage({
    
    
    // 群号
    group: '123456789',
    // 是 http server 接口所需的原始格式,若提供则优先使用
    messageChain: [
    	{
    
     type: 'Plain', text: 'hello world!'},
        {
    
     type: 'Image', url:;'http://example/image.jpg'},
	],
});

For specific MessageChainmessage types, see MessageType .

Receive messages and events

Register the event handler to receive friend messages:

// 监听好友消息事件
bot.on('FriendMessage', async data => {
    
    
    await bot.sendMessage({
    
    
        friend: data.sender.id,
        message: new Message().addText('hello world!'),
    });
});

The message structure of the FriendMessage event:

{
    
    
    messageChain,
    sender: {
    
    
        id,
        nickname,
        remark
    }
}

The framework gives the specific message content in the form of the original messageChain. Its structure is an array of MessageType. See MessageType for various MessageTypes.

It doesn't matter if you don't want to watch it. If you only focus on text messages, then we can easily solve this problem using the middleware predefined by the framework.

Receive group messages:

// 监听群消息事件
bot.on('GroupMessage', async data => {
    
    
    await bot.sendMessage({
    
    
        group: data.sender.group.id,
        message: new Message().addText('hello world!'),
    });

    // 你可以像这样来判断群成员的权限
    switch (data.sender.permission) {
    
    
        case Bot.GroupPermission.OWNER:
            // 群主
            break;
        case Bot.GroupPermission.ADMINISTRATOR:
            // 管理员
            break;
        case Bot.GroupPermission.MEMBER:
            // 普通群成员
            break;
    }
});

The message structure of the GroupMessage event:

{
    
    
    messageChain,
    sender: {
    
    
        id,
        memberName,
        permission,
        group: {
    
    
            id,
            name,
            permission
        }
    }
}

For specific event types and message structure, see EventType .

Use middleware

The framework also provides a series of predefined middleware for processing messages:

const {
    
     Middleware } = require('./src/Mirai-js');

Obtain a Middlewareexamples:

const middleware = new Middleware();

Call the middleware you need on the instance (chained):

textProcessorFor stitching messageChainall text messages, and placed data.text, groupFilterit will filter out designated group number of group message events.

middleware.textProcessor().groupFilter([123456789, 987654321]);

By calling the donemethod, passing in your event handler, the event handler is obtained with a middleware:

const processor = middleware.done(async data => {
    
    
    bot.sendMessage({
    
    
        friend: data.sender.id,
        message: new Message().addText(data.text),
    });
});

Register to an event:

bot.on('FriendMessage', processor);

It can also be combined together:

bot.on('FriendMessage', new Middleware()
    .textProcessor()
    .groupFilter([123456789, 987654321])
    .done(async data => {
    
    
        bot.sendMessage({
    
    
            friend: data.sender.id,
            message: new Message().addText(data.text),
        });
    })
);

In addition, you can also customize the middleware, using use:

Finally, call nexttransfers control to the next middleware.

const processor = middleware.use((data, next) => {
    
    
    data.text = data.messageChain
        .filter((val) => val.type == 'Plain')
        .map((val) => val.text)
        .join('');
    next();
}).done(/* callback */);

Known issues

When our bot goes offline and re-login, the current session will fall into a state that is not invalidated but cannot be operated. Forcible operations (such as sending a message) will throw a server exception (status 500).

Calling the openmethod again after logging in again can avoid this problem.

Or use a predefined autoReLoginmiddleware in an event that requires re-login , and it will automatically log in after the connection is dropped. Example:

bot.on('BotOfflineEventForce',
    new Middleware()
       .autoReLogin({
    
     bot, baseUrl, authKey, password })
       .done()
);

Guess you like

Origin blog.csdn.net/qq_16181837/article/details/113702321