【踩坑】mirai挂机运行经常自动退出怎么办?

转载请注明出处:小锋学长生活大爆炸[xfxuezhang.cn]

目录

背景介绍

解决思路

实现方法

最终效果


背景介绍

        就是说,后台运行了mcl,但经常莫名其妙自动会退出,导致每次都得手动的去服务器上重新启动mcl。而对于自己运行的需要用到mirai的软件,也得重新获取bot id。非常的麻烦!       

解决思路

        1、通过一个python脚本,定时的去检查mcl的运行状态,如果发现mcl退出了,就赶紧重新运行起来。

        2、由于这里重新运行了mcl,我们应该通知其他用到了这个mirai的软件,也需要重新获取bot id。这里使用最简单粗暴的方法:每次重启了mcl,就在指定目录下生成一个文件。而其他软件可以判断是否存在这个,从而决定是否重新获取bot id。(当然,你的软件在每次使用时,都生成一个新的bot id也行,但会导致服务器的缓存占用变高。)

实现方法

        监控mcl的python脚本——listene.py:

import subprocess
import time
import os
import atexit

process = subprocess.Popen(['./mcl -u'])
stoped_flag = False

def kill_process():
    process.kill()

atexit.register(kill_process)  # 注册进程清理函数

while True:
    time.sleep(10)
    poll = process.poll()
    if poll is not None:
        print('./mcl exited unexpectedly, restarting...')
        process = subprocess.Popen(['./mcl -u'])
        stoped_flag = True
    else:
        print('./mcl is running')
        if stoped_flag:
            stoped_flag = False
            with open('mcl_restart', 'w+') as f:
                f.write('1')

        用到了mirai的软件中重新生成bot id的示例用法:

def qqTransfer():
    global bot
    with open('conf.json', 'r+', encoding="utf-8") as f:
        content = f.read()
    conf = json.loads(content)

    auth_key = conf['auth_key']
    bind_qq = conf['bind_qq']
    sleep_time = conf['sleep_time']
    debug_level = conf['debug_level']

    receive_groups = conf['receive_groups']
    send_groups = conf['send_groups']
    # receive_groups = ['537241540', '719684243']
    # send_groups = ['537241540', '719684243']

    logger.setDebugLevel(debug_level)
    
    session = bot.verifySession(auth_key)
    logger.DebugLog(">> session: "+session)
    bot.bindSession(session, bind_qq)
    while True:


        # 看这里看这里!!!!!!!!!!!!!!!!!!!
        if os.path.exists('mcl/mcl_restart'):
            print('>> 重新获取bot session')
            bot = QQBot()
            session = bot.verifySession(auth_key)
            logger.DebugLog(">> session: "+session)
            bot.bindSession(session, bind_qq)
            os.unlink('mcl/mcl_restart')



        cnt = bot.getMessageCount(session)
        if cnt:
            logger.DebugLog('>> 有消息了 => {}'.format(cnt))
            logger.DebugLog('获取消息内容')
            data = bot.getMsgFromGroup(session)
            if len(data) == 0:
                logger.DebugLog('消息为空')
                continue
            logger.DebugLog(data)

            bot.parseMsgForChatGPT(data, bind_qq, session)

            logger.DebugLog('解析消息内容')
            data = bot.parseGroupMsg(data)
            logger.DebugLog(data)
            logger.DebugLog('转发消息内容')
            bot.sendMsgToAllGroups(session, receive_groups, send_groups, data)
        sleep(sleep_time)
    bot.releaseSession(session, bind_qq)

        该代码段取自:mirai QQ机器人最详细教程 [附Q群消息转发例程]

最终效果

         目前mcl一直没有断过。

猜你喜欢

转载自blog.csdn.net/sxf1061700625/article/details/130939867
今日推荐