Greasy Fork is available in English.

战斗吧歌姬!!

修仙!修仙!修仙!修仙!

// ==UserScript==
// @name         战斗吧歌姬!!
// @homepage     https://greasyfork.org/scripts/398085
// @version      4.13.9
// @description  修仙!修仙!修仙!修仙!
// @author       风绫丨钰袖、逆回十六夜、indefined、SeaLoong
// @iconURL      https://i0.hdslb.com/bfs/article/927cc195124c47474b4a150d8b09e00536d15a0a.gif
// @icon64URL    https://i0.hdslb.com/bfs/article/927cc195124c47474b4a150d8b09e00536d15a0a.gif
// @include      /https?:\/\/live\.bilibili\.com\/\d+\??.*/
// @include      /https?:\/\/live\.bilibili\.com/blanc/\d+\??.*/
// @include      /https?:\/\/live\.bilibili\.com/p/html/live-room-treasurebox/\??.*/
// @require      https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js
// @require      https://cdn.bootcss.com/layer/2.4/layer.js
//@require      https://cdn.jsdelivr.net/gh/FLYX-LL/ZDBGJ@1.1/BilibiliAPI_mod.user.js
//@require      https://cdn.jsdelivr.net/gh/FLYX-LL/ZDBGJ@1.0/OCRAD.min.js
// @grant        unsafeWindow
// @grant        GM_xmlhttpRequest
// @run-at       document-idle
// @license      MIT License
// @namespace http://tampermonkey.net/
// ==/UserScript==
/*
瓜子初始化失败问题自行替换上方对应OCRAD源
[greasyfork源]
// @require      https://greasyfork.org/scripts/44866-ocrad/code/OCRAD.js
[github源]
// @require      https://raw.githubusercontent.com/SeaLoong/Bilibili-LRHH/master/OCRAD.min.js
[gitee源]
// @require      https://gitee.com/SeaLoong/Bilibili-LRHH/raw/master/OCRAD.min.js
[腾讯云源]
// @require      https://js-1258131272.file.myqcloud.com/OCRAD.min.js
[jsDelivr源]
// @require      https://cdn.jsdelivr.net/gh/SeaLoong/Bilibili-LRHH/OCRAD.min.js
*/
window.onload=(function ZDBGJ_BLRHH_Plus(){
    let NAME='ZDBGJ';
    let BAPI;
    let server_host;
    let ZBJ='中国虚拟偶像天团【战斗吧歌姬!】';
    let CJ;
    var riqi;
    var goldbox;
    var BPDJ;
    var COUNT;
    var Lcount;
    var QMD;
    var DMCHECK=0;
    riqi=new Date();
    let yue=riqi.getMonth()+1;
    let ri=riqi.getDate();
    let xiaoshi=riqi.getHours();
    let fenzhong=riqi.getMinutes();
    let nowTime = riqi.getTime();
    riqi.setTime(parseInt(nowTime -24*3600*1000));
    let yyue = (riqi.getMonth() + 1);
    let yri = riqi.getDate();
    let Live_info = {
        room_id: undefined,
        uid: undefined,
        mobile_verify: undefined,
        blocked:undefined,
    };
    const tz_offset = new Date().getTimezoneOffset() + 480;
    const ts_ms = () => Date.now();
    const ts_s = () => Math.round(ts_ms() / 1000);
    const runUntilSucceed = (callback, delay = 0, period = 100) => {
        setTimeout(() => {
            if (!callback()) runUntilSucceed(callback, period, period);
        }, delay);
    };
    const delayCall = (callback, delay = 10e3) => {
        const p = $.Deferred();
        setTimeout(() => {
            const t = callback();
            if (t && t.then) t.then((arg1, arg2, arg3, arg4, arg5, arg6) => p.resolve(arg1, arg2, arg3, arg4, arg5, arg6));
            else p.resolve();
        }, delay);
        return p;
    };
    async function sleep(time) {
        return new Promise((resolve) => {
            setInterval(() => {
                resolve();
            }, time);
        });
    }
    $(function () {//DOM完毕,等待弹幕加载完成
        let href = parent.location.href;
        if (href.indexOf('treasurebox') >= 0) {
            $(".bl-button.bl-button--primary.bl-button--size").click();
            setTimeout(() => {
                $(".bl-button.bl-button--primary.bl-button--size").click();
            }, 1000);
            setTimeout(() => {
                window.close();
            }, 5000);

        }
        const chatLog=function (text, type = 'info') {//自定义提示
            let div = $("<div class='zdbgjMsg'>");
            let msg = $("<div>");
            let ct = $('#chat-items');
            let myDate = new Date();
            msg.text(text);
            div.text(myDate.toLocaleString());
            div.append(msg);
            div.css({
                'text-align': 'center',
                'border-radius': '4px',
                'min-height': '30px',
                'width': '256px',
                'color': 'red',
                'line-height': '30px',
                'padding': '0 10px',
                'margin': '10px auto',
                'border': '1px solid rgb(203, 195, 255)',
                'background': 'rgb(233, 230, 255) none repeat scroll 0% 0%',
            });
            msg.css({
                'word-wrap': 'break-word',
                'width': '100%',
                'line-height': '1em',
                'margin-bottom': '10px',
            });
            ct.append(div);//向聊天框加入信息
            let ctt = $('#chat-history-list');
            ctt.animate({scrollTop: ctt.prop("scrollHeight")}, 0);//滚动到底部
        }
        document.getElementById("my-dear-haruna-vm").style.display = "none"; //去掉2233 sections-vm
        document.getElementById("sections-vm").style.display = "none"; //去掉直播画面下方内容
        let i=0
        let loadInfo = (delay) => {
            setTimeout(function () {
                if (BilibiliLive === undefined || parseInt(BilibiliLive.UID) === 0 || isNaN(parseInt(BilibiliLive.UID))) {
                    loadInfo(5000);
                    chatLog('未登录或网络卡顿,请先登录或检查网络!');
                    i +=1
                    if(i>15) {
                        window.location.reload()
                    }
                    console.log('无配置信息');
                } else {
                    Live_info.room_id = BilibiliLive.ROOMID;
                    Live_info.uid = BilibiliLive.UID;
                    console.log(Live_info);
                    init();
                    i=0
                }
            }, delay);
        };
        loadInfo(3000);
        $('head').append('<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/layer/2.4/skin/layer.css">');//加载layer样式
    });

    Array.prototype.remove = function (val) {
        let index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };

    function init() {//API初始化
        try {
            BAPI = BilibiliAPI;
            // document.domain = 'bilibili.com'
        } catch (err) {
            console.error(`[${NAME}]`, err);
            // document.domain = 'bilibili.com'
            return;
        }
        BAPI.live_user.get_info_in_room(Live_info.room_id).then((response) => {
            console.log('InitData: API.live_user.get_info_in_room', response);
            Live_info.mobile_verify = response.data.info.mobile_verify;
        });

        const MY_API = {
            CONFIG_DEFAULT: {
                GIFT_AUTO:true,
                GIFT_NUM: 1500,
                GIFT_ROOM: 2374828,
                TOP: false,//实时小时榜监测开关
                TALK: false,  //不显示抽奖反馈
                RANDOM_DELAY: true,
                TIMEAREADISABLE: true,
                TIMEAREASTART: 2,
                TIMEAREAEND: 8,
                TIMESTART: 2,
                TIMEEND: 8,
                RANDOMSKIP: 0,
                MAXGIFT: 99999,
                TOPFLASH: 180,
                TOPspeedup: 4,
                CZ: 180,
                JSMARK:0,   //多开标记
                AUTO_OLDTOP: false,//上小时小时榜监测开关
                AUTO_TREASUREBOX: true,//每日宝箱
                AUTO_BOX: true,//每日硬币
                AUTO_HEART: true,
                materialobject_ts:0,
                last_aid:600,
                AUTO_GOLDBOX: true,//金箱子抽奖
                COUNT_GOLDBOX: 0,
            },

            CONFIG: {},
            GIFT_COUNT: {
                COUNT: 0,
                LCOUNT: 0,
                LOVE_COUNT: 0,
                CLEAR_TS: 0,
                TTCOUNT: 0,
                TTLOVE_COUNT: 0,
                BPJY: 0,
                BPDJ: 1,
                DJLVMK: 100,
                CLOCL01:0,
                CLOCL26:0,
                CLOCL712:0,
                CLOCL1317:0,
                CLOCL18:0,
                CLOCL19:0,
                CLOCL20:0,
                CLOCL21:0,
                CLOCL22:0,
                CLOCL23:0,
                YCLOCL01:0,
                YCLOCL26:0,
                YCLOCL712:0,
                YCLOCL1317:0,
                YCLOCL18:0,
                YCLOCL19:0,
                YCLOCL20:0,
                YCLOCL21:0,
                YCLOCL22:0,
                YCLOCL23:0,
                YGIFT:0,
                blockedb:0,
                blockedn: 0,//银瓜子宝箱累计黑屋次数
                blockedt: 0,//银瓜子宝箱上次黑屋日期及时间
                giftblockedb:0,
                giftblockedn: 0,//抽奖累计黑屋次数
                giftblockedt: 0,//抽奖上次黑屋日期及时间
                guardblockedb: 0,
                guardblockedt: 0,//舰长上次黑屋日期及时间
                guardblockedn: 0,//舰长累计黑屋次数
                pkblockedb: 0,
                pkblockedn: 0,//PK累计黑屋次数
                pkblockedt: 0,//PK上次黑屋日期及时间
            },
            init: function () {
                try {
                    BAPI.setCommonArgs(BAPI.getCookie('bili_jct'));// 设置token
                } catch (err) {
                    console.error(`[${NAME}]`, err);
                    return;
                }

                let p = $.Deferred();
                try {
                    MY_API.loadConfig().then(function () {
                        MY_API.chatLog('正在配置次元之门....', 'success');
                        setTimeout(() => {
                            $("div.checkin-btn.t-center.pointer").click();
                        }, 1000);
                        setTimeout(() => {
                            $("div.checkin-btn.t-center.pointer").click();
                        }, 10000);
                        setTimeout(() => {
                            $("div.checkin-btn.t-center.pointer").click();
                        }, 100000);
                        setTimeout(() => {
                            $("div.checkin-btn.t-center.pointer").click();
                        }, 1000000);
                        if (MY_API.GIFT_COUNT.BPDJ<20) {
                            CJ='筑基白嫖怪';
                        } else if(MY_API.GIFT_COUNT.BPDJ<30){
                            CJ='旋照白嫖怪'
                        } else if(MY_API.GIFT_COUNT.BPDJ<40){
                            CJ='辟谷白嫖怪'
                        } else if(MY_API.GIFT_COUNT.BPDJ<50){
                            CJ='结丹白嫖怪'
                        } else if(MY_API.GIFT_COUNT.BPDJ<60){
                            CJ='元婴白嫖怪'
                        } else if(MY_API.GIFT_COUNT.BPDJ<70){
                            CJ='出窍白嫖怪'
                        } else if(MY_API.GIFT_COUNT.BPDJ<80){
                            CJ='分神白嫖怪';
                        } else if(MY_API.GIFT_COUNT.BPDJ<90){
                            CJ='合体白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<100){
                            CJ='渡劫白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<200){
                            CJ='大乘白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<300){
                            CJ='仙人白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<400){
                            CJ='地仙白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<500){
                            CJ='天仙白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<600){
                            CJ='玄仙白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<700){
                            CJ='神境白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<900){
                            CJ='神人白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<1200){
                            CJ='准神白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<1500){
                            CJ='主神白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<2000){
                            CJ='神王白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<3000){
                            CJ='天尊白嫖怪'
                        }else if(MY_API.GIFT_COUNT.BPDJ<4000){
                            CJ='天尊白嫖怪一重天'
                        }else if(MY_API.GIFT_COUNT.BPDJ<5000){
                            CJ='天尊白嫖怪二重天'
                        }else if(MY_API.GIFT_COUNT.BPDJ<6000){
                            CJ='天尊白嫖怪三重天'
                        }else if(MY_API.GIFT_COUNT.BPDJ<7000){
                            CJ='天尊白嫖怪四重天'
                        }else if(MY_API.GIFT_COUNT.BPDJ<8000){
                            CJ='天尊白嫖怪五重天'
                        }else if(MY_API.GIFT_COUNT.BPDJ<9000){
                            CJ='天尊白嫖怪六重天'
                        }else if(MY_API.GIFT_COUNT.BPDJ<10000){
                            CJ='天尊白嫖怪七重天'
                        }else if(MY_API.GIFT_COUNT.BPDJ<11000){
                            CJ='天尊白嫖怪八重天'
                        }else if(MY_API.GIFT_COUNT.BPDJ<12000){
                            CJ='天尊白嫖怪九重天'
                        }else if(MY_API.GIFT_COUNT.BPDJ>=20000){
                            CJ='天尊白嫖怪大圆满'
                        };
                        p.resolve();
                    });
                } catch (e) {
                    console.log('API初始化出错', e);
                    MY_API.chatLog('脚本初始化出错', 'warning');
                    p.reject()
                }
                return p
            },

            loadConfig: function () {
                let p = $.Deferred();
                try {
                    let config = JSON.parse(localStorage.getItem(`${NAME}_CONFIG`));
                    $.extend(true, MY_API.CONFIG, MY_API.CONFIG_DEFAULT);
                    for (let item in MY_API.CONFIG) {
                        if (!MY_API.CONFIG.hasOwnProperty(item)) continue;
                        if (config[item] !== undefined && config[item] !== null) MY_API.CONFIG[item] = config[item];
                    }
                    MY_API.loadGiftCount();//载入礼物统计
                    p.resolve()
                } catch (e) {
                    console.log('API载入配置失败,加载默认配置', e);
                    MY_API.setDefaults();
                    p.reject()
                }
                return p
            },
            saveConfig: function () {
                try {
                    localStorage.setItem(`${NAME}_CONFIG`, JSON.stringify(MY_API.CONFIG));
                    MY_API.chatLog('配置已保存');
                    //     console.log(MY_API.CONFIG);
                    return true
                } catch (e) {
                    console.log('API保存出错', e);
                    return false
                }
            },
            GsaveConfig: function () {
                try {
                    localStorage.setItem(`${NAME}_CONFIG`, JSON.stringify(MY_API.CONFIG));
                    return true
                } catch (e) {
                    console.log('API保存出错', e);
                    return false
                }
            },
            setDefaults: function () {
                MY_API.CONFIG = MY_API.CONFIG_DEFAULT;
                MY_API.saveConfig();
                MY_API.chatLog('欢迎来到白嫖怪的修仙世界!', 'warning');
                MY_API.chatLog('正常开启传送,3秒后穿越次元!', 'warning');
                CJ='筑基白嫖怪';
                setTimeout(() => {
                    window.location.reload()
                }, 3000);
            },
            loadGiftCount: function () {
                try {
                    let config = JSON.parse(localStorage.getItem(`${NAME}_GIFT_COUNT`));
                    for (let item in MY_API.GIFT_COUNT) {
                        if (!MY_API.GIFT_COUNT.hasOwnProperty(item)) continue;
                        if (config[item] !== undefined && config[item] !== null) MY_API.GIFT_COUNT[item] = config[item];
                    }
                    BPDJ=MY_API.GIFT_COUNT.BPDJ;
                    COUNT=MY_API.GIFT_COUNT.COUNT;
                    QMD=MY_API.GIFT_COUNT.LOVE_COUNT;
                } catch (e) {
                    console.log('读取统计失败', e);
                }
            },
            saveGiftCount: function () {
                try {
                    localStorage.setItem(`${NAME}_GIFT_COUNT`, JSON.stringify(MY_API.GIFT_COUNT));
                    console.log('统计保存成功', MY_API.GIFT_COUNT);
                    BPDJ=MY_API.GIFT_COUNT.BPDJ;
                    COUNT=MY_API.GIFT_COUNT.COUNT;
                    QMD=MY_API.GIFT_COUNT.LOVE_COUNT;

                    $('#hls0 span:eq(0)').text(MY_API.GIFT_COUNT.pkblockedn);
                    $('#hls1 span:eq(0)').text(MY_API.GIFT_COUNT.pkblockedt);
                    $('#hls2 span:eq(0)').text(MY_API.GIFT_COUNT.blockedn);
                    $('#hls3 span:eq(0)').text(MY_API.GIFT_COUNT.blockedt);
                    $('#hls4 span:eq(0)').text(MY_API.GIFT_COUNT.guardblockedn);
                    $('#hls5 span:eq(0)').text(MY_API.GIFT_COUNT.guardblockedt);
                    $('#hls6 span:eq(0)').text(MY_API.GIFT_COUNT.giftblockedn);
                    $('#hls7 span:eq(0)').text(MY_API.GIFT_COUNT.giftblockedt);

                    return true
                } catch (e) {
                    console.log('统计保存出错', e);
                    return false
                }
            },

            cjcheck: function () {
                if (MY_API.GIFT_COUNT.BPDJ<20) {
                    CJ='筑基白嫖怪';
                } else if(MY_API.GIFT_COUNT.BPDJ==20){
                    CJ='旋照白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【旋照白嫖怪】');
                } else if(MY_API.GIFT_COUNT.BPDJ==30){
                    CJ='辟谷白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【避谷白嫖怪】');
                } else if(MY_API.GIFT_COUNT.BPDJ==40){
                    CJ='结丹白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【结丹白嫖怪】');
                } else if(MY_API.GIFT_COUNT.BPDJ==50){
                    CJ='元婴白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【元婴白嫖怪】');
                } else if(MY_API.GIFT_COUNT.BPDJ==60){
                    CJ='出窍白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【出窍白嫖怪】');
                } else if(MY_API.GIFT_COUNT.BPDJ==70){
                    CJ='分神白嫖怪';
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【分神白嫖怪】');
                } else if(MY_API.GIFT_COUNT.BPDJ==80){
                    CJ='合体白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【合体白嫖怪】');
                }else if(MY_API.GIFT_COUNT.BPDJ==90){
                    CJ='渡劫白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【渡劫白嫖怪】');
                }else if(MY_API.GIFT_COUNT.BPDJ==100){
                    CJ='大乘白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【大乘白嫖怪】');
                }else if(MY_API.GIFT_COUNT.BPDJ==200){
                    CJ='仙人白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【仙人白嫖怪】');
                }else if(MY_API.GIFT_COUNT.BPDJ==300){
                    CJ='地仙白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【地仙白嫖怪】');
                }else if(MY_API.GIFT_COUNT.BPDJ==400){
                    CJ='天仙白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【天仙白嫖怪】');
                }else if(MY_API.GIFT_COUNT.BPDJ==500){
                    CJ='玄仙白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【玄仙白嫖怪】');
                }else if(MY_API.GIFT_COUNT.BPDJ==600){
                    CJ='神境白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【神境白嫖怪】');
                }else if(MY_API.GIFT_COUNT.BPDJ==700){
                    CJ='神人白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【神人白嫖怪】');
                }else if(MY_API.GIFT_COUNT.BPDJ==900){
                    CJ='准神白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【准神白嫖怪】');
                }else if(MY_API.GIFT_COUNT.BPDJ==1200){
                    CJ='主神白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【主神白嫖怪】');
                }else if(MY_API.GIFT_COUNT.BPDJ==1500){
                    CJ='神王白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为【神王白嫖怪】');
                }else if(MY_API.GIFT_COUNT.BPDJ==2000){
                    CJ='天尊白嫖怪'
                    MY_API.chatLog('仙路漫漫,道法天成,恭喜你成为修仙至尊【天尊白嫖怪】');
                }

            },
            addGift: function (count) {
                let riqi=new Date();
                let xiaoshi=riqi.getHours();
                if(xiaoshi<2)
                {
                    MY_API.GIFT_COUNT.CLOCL01 += count;
                }else if(xiaoshi<7){
                    MY_API.GIFT_COUNT.CLOCL26 += count;
                }else if(xiaoshi<13){
                    MY_API.GIFT_COUNT.CLOCL712 += count;
                }else if(xiaoshi<18){
                    MY_API.GIFT_COUNT.CLOCL1317 += count;
                }else if(xiaoshi<19){
                    MY_API.GIFT_COUNT.CLOCL18 += count;
                }else if(xiaoshi<20){
                    MY_API.GIFT_COUNT.CLOCL19 += count;
                }else if(xiaoshi<21){
                    MY_API.GIFT_COUNT.CLOCL20 += count;
                }else if(xiaoshi<22){
                    MY_API.GIFT_COUNT.CLOCL21 += count;
                }else if(xiaoshi<23){
                    MY_API.GIFT_COUNT.CLOCL22 += count;
                }else if(xiaoshi<24){
                    MY_API.GIFT_COUNT.CLOCL23 += count;
                };
                $('#clockgift01 span:eq(0)').text(MY_API.GIFT_COUNT.CLOCL01);
                $('#clockgift26 span:eq(0)').text(MY_API.GIFT_COUNT.CLOCL26);
                $('#clockgift712 span:eq(0)').text(MY_API.GIFT_COUNT.CLOCL712);
                $('#clockgift1317 span:eq(0)').text(MY_API.GIFT_COUNT.CLOCL1317);
                $('#clockgift18 span:eq(0)').text(MY_API.GIFT_COUNT.CLOCL18);
                $('#clockgift19 span:eq(0)').text(MY_API.GIFT_COUNT.CLOCL19);
                $('#clockgift20 span:eq(0)').text(MY_API.GIFT_COUNT.CLOCL20);
                $('#clockgift21 span:eq(0)').text(MY_API.GIFT_COUNT.CLOCL21);
                $('#clockgift22 span:eq(0)').text(MY_API.GIFT_COUNT.CLOCL22);
                $('#clockgift23 span:eq(0)').text(MY_API.GIFT_COUNT.CLOCL23);
                MY_API.GIFT_COUNT.COUNT += count;
                MY_API.GIFT_COUNT.TTCOUNT+= count;
                let BPJY=MY_API.GIFT_COUNT.BPJY
                MY_API.GIFT_COUNT.BPJY += count*4;
                if (MY_API.GIFT_COUNT.BPJY >= MY_API.GIFT_COUNT.DJLVMK && BPJY < MY_API.GIFT_COUNT.DJLVMK ) {
                    MY_API.GIFT_COUNT.BPDJ +=1;
                    MY_API.cjcheck();
                    MY_API.GIFT_COUNT.DJLVMK +=1000
                    MY_API.chatLog('恭喜你升级了ヾ(o◕∀◕)ノヾ');
                }
                $('#TTgiftCount span:eq(0)').text(MY_API.GIFT_COUNT.TTCOUNT);
                $('#giftCount span:eq(2)').text(MY_API.GIFT_COUNT.COUNT);
                $('#giftCount span:eq(0)').text(yue);
                $('#giftCount span:eq(1)').text(ri);
                $('#giftCoun span:eq(0)').text(MY_API.GIFT_COUNT.COUNT);
                $('#CJ span:eq()').text(CJ);
                $('#BPJY span:eq(0)').text(MY_API.GIFT_COUNT.BPJY);
                $('#BPJY span:eq(1)').text(MY_API.GIFT_COUNT.BPDJ);
                $('#clockgift span:eq(0)').text(MY_API.GIFT_COUNT.COUNT);
                MY_API.saveGiftCount();
            },
            addLove: function (count) {
                MY_API.GIFT_COUNT.LOVE_COUNT += count;
                MY_API.GIFT_COUNT.TTLOVE_COUNT += count;
                let BPJY=MY_API.GIFT_COUNT.BPJY
                MY_API.GIFT_COUNT.BPJY += count*6;
                if (MY_API.GIFT_COUNT.BPJY >= MY_API.GIFT_COUNT.DJLVMK && BPJY < MY_API.GIFT_COUNT.DJLVMK ) {
                    MY_API.GIFT_COUNT.BPDJ +=1;
                    MY_API.cjcheck();
                    MY_API.GIFT_COUNT.DJLVMK +=1000
                    MY_API.chatLog('恭喜你升级了ヾ(o◕∀◕)ノヾ');
                }
                $('#TTgiftCount span:eq(1)').text(MY_API.GIFT_COUNT.TTLOVE_COUNT);
                $('#giftCount span:eq(3)').text(MY_API.GIFT_COUNT.LOVE_COUNT);
                $('#giftCoun span:eq(1)').text(MY_API.GIFT_COUNT.LOVE_COUNT);
                $('#BPJY span:eq(0)').text(MY_API.GIFT_COUNT.BPJY);
                $('#BPJY span:eq(1)').text(MY_API.GIFT_COUNT.BPDJ);
                MY_API.saveGiftCount();
            },
            creatSetBox: function () {//创建设置框


                let btn1 = $('<button style="position: absolute; top: 132px; left: 0;z-index: 1;background-color: pink;color: #FF34B3;border-radius: 4px;border: none;padding: 5px;cursor: pointer;box-shadow: 1px 1px 2px #00000075;">' +
                             '隐藏插件参数界面</button>');
                btn1.click(function () {
                    $('.hls').hide();
                    div.css({
                        'z-index': '-1',
                    });
                    tj.css({
                        'z-index': '-1',
                    });
                    tp.css({
                        'z-index': '-1',
                    });
                    goldbox.css({
                        'z-index': '-1',
                    });
                    tppp.css({
                        'z-index': '-1',
                    });
                    msg.css({
                        'z-index': '10',
                    });

                });
                $('.chat-history-panel').append(btn1);
                let btn2 = $('<button style="position: absolute; top: 156px; left: 0;z-index:1;background-color:yellow;color: #FF34B3;border-radius: 4px;border: none;padding: 5px;cursor: pointer;box-shadow: 1px 1px 2px #00000075;">' +
                             '显示插件参数界面</button>');
                btn2.click(function () {
                    div.css({
                        'z-index': '10',
                    });
                    tj.css({
                        'z-index': '10',
                    });
                    tp.css({
                        'z-index': '10',
                    });
                    goldbox.css({
                        'z-index': '10',
                    });
                    tppp.css({
                        'z-index': '10',
                    });
                    msg.css({
                        'z-index': '-1',
                    });
                });
                $('.chat-history-panel').append(btn2);

                let btn3 = $('<button style="position: absolute; top: 179px; left: 0;z-index:1;background-color:purple;color: #FF34B3;border-radius: 4px;border: none;padding: 5px;cursor: pointer;box-shadow: 1px 1px 2px #00000075;">' +
                             '清空抽奖反馈信息</button>');
                btn3.click(function () {
                    $('.zdbgjMsg').hide();
                });
                $('.chat-history-panel').append(btn3);
                let msg = $("<div>");
                msg.css({
                    'width': '99px',
                    'height': '15px',
                    'position': 'absolute',
                    'top': '202px',
                    'left': '0px',
                    'background': '#00FFFF',
                    'padding': '4px',
                    'z-index': '10',
                    'border-radius': '4px',
                    'transition': 'height .3s',
                    'overflow': 'hidden',
                });

                //<div id="giftCoun" style="font-size: small;color:blue;">
                //亲密度:<span>${MY_API.GIFT_COUNT.LOVE_COUNT}</span>
                msg.append(`

<div id="giftCoun" style="font-size: small;color:blue;">
辣条:<span>${MY_API.GIFT_COUNT.COUNT}</span>

`);
                $('.chat-history-panel').append(msg);

                let div = $('<div>');
                div.css({
                    'width': '320px',
                    'height': '480px',
                    'position': 'absolute',
                    'top': '10px',
                    'right': '10px',
                    'background': 'rgba(255,255,255,.8)',
                    'padding': '10px',
                    'z-index': '-1',
                    'border-radius': '12px',
                    'transition': 'height .3s',
                    'overflow': 'hidden',
                    'line-height': '18px'
                });


                let tj = $('<div>');
                tj.css({
                    'width': '125px',
                    'height': '480px',
                    'position': 'absolute',
                    'top': '10px',
                    'right': '355px',
                    'background': 'rgba(255,255,255,.8)',
                    'padding': '10px',
                    'z-index': '-1',
                    'border-radius': '12px',
                    'transition': 'height .3s',
                    'overflow': 'hidden',
                    'line-height': '15px'
                });


                tj.append(`

<fieldset>
<legend append style="color: #FF34B3;text-align: left;"><span>${yue}</span>月<span>${ri}</span>日辣条统计</legend> </div>
<div id="clockgift01" style="font-size: small;color:#FF34B3;">
0-1点:<span>${MY_API.GIFT_COUNT.CLOCL01}</span></div>
<div id="clockgift26" style="font-size: small;color:#FF34B3;">
2-6点:<span>${MY_API.GIFT_COUNT.CLOCL26}</span></div>
<div id="clockgift712" style="font-size: small;color:#FF34B3;">
7-12点:<span>${MY_API.GIFT_COUNT.CLOCL712}</span></div>
<div id="clockgift1317" style="font-size: small;color:#FF34B3;">
13-17点:<span>${MY_API.GIFT_COUNT.CLOCL1317}</span></div>
<div id="clockgift18" style="font-size: small;color:#FF34B3;">
18点:<span>${MY_API.GIFT_COUNT.CLOCL18}</span></div>
<div id="clockgift19" style="font-size: small;color:#FF34B3;">
19点:<span>${MY_API.GIFT_COUNT.CLOCL19}</span></div>
<div id="clockgift20" style="font-size: small;color:#FF34B3;">
20点:<span>${MY_API.GIFT_COUNT.CLOCL20}</span></div>
<div id="clockgift21" style="font-size: small;color:#FF34B3;">
21点:<span>${MY_API.GIFT_COUNT.CLOCL21}</span></div>
<div id="clockgift22" style="font-size: small;color:#FF34B3;">
22点:<span>${MY_API.GIFT_COUNT.CLOCL22}</span></div>
<div id="clockgift23" style="font-size: small;color:#FF34B3;">
23点:<span>${MY_API.GIFT_COUNT.CLOCL23}</span></div>
<div id="clockgift" style="font-size: small;color:#FF34B3;">
合计:<span>${MY_API.GIFT_COUNT.COUNT}</span></div>
</fieldset>

<fieldset>
<legend append id="guanzhu" style="color:#FF34B3;">
关注我</legend> </div>
<div id="guanzhu" style="color:#FF34B3;">
<button data-action="guanzhu" style="font-size: 120%;color: Orange " title="关注我,升职加薪不秃头,获得女神阿库娅的祝福,幸运值+++,SSR+++,黑屋概率---">\n♪幸运值♪\n++++</button></div>

<div data-toggle="AUTO_GOLDBOX">
<apend style="margin: 5px auto; color: #FF34B3">
<input style="vertical-align: text-top;" type="checkbox">自动金箱子抽奖
</div>
<div id="COUNT_GOLDBOX" style="font-size: small;color:#FF34B3;">
已参与:<span>${MY_API.CONFIG.COUNT_GOLDBOX}</span>次</div>

</fieldset>

<fieldset>
<legend append style="color: #FF34B3;text-align: left;"><span>${yyue}</span>月<span>${yri}</span>日辣条统计</legend> </div>
<div id="yclockgift01" style="font-size: small;color:#FF34B3;">
0-1点:<span>${MY_API.GIFT_COUNT.YCLOCL01}</span></div>
<div id="yclockgift26" style="font-size: small;color:#FF34B3;">
2-6点:<span>${MY_API.GIFT_COUNT.YCLOCL26}</span></div>
<div id="yclockgift712" style="font-size: small;color:#FF34B3;">
7-12点:<span>${MY_API.GIFT_COUNT.YCLOCL712}</span></div>
<div id="yclockgift1317" style="font-size: small;color:#FF34B3;">
13-17点:<span>${MY_API.GIFT_COUNT.YCLOCL1317}</span></div>
<div id="yclockgift18" style="font-size: small;color:#FF34B3;">
18点:<span>${MY_API.GIFT_COUNT.YCLOCL18}</span></div>
<div id="yclockgift19" style="font-size: small;color:#FF34B3;">
19点:<span>${MY_API.GIFT_COUNT.YCLOCL19}</span></div>
<div id="yclockgift20" style="font-size: small;color:#FF34B3;">
20点:<span>${MY_API.GIFT_COUNT.YCLOCL20}</span></div>
<div id="yclockgift21" style="font-size: small;color:#FF34B3;">
21点:<span>${MY_API.GIFT_COUNT.YCLOCL21}</span></div>
<div id="yclockgift22" style="font-size: small;color:#FF34B3;">
22点:<span>${MY_API.GIFT_COUNT.YCLOCL22}</span></div>
<div id="yclockgift23" style="font-size: small;color:#FF34B3;">
23点:<span>${MY_API.GIFT_COUNT.YCLOCL23}</span></div>
<div id="ygift" style="font-size: small;color:#FF34B3;">
合计:<span>${MY_API.GIFT_COUNT.YGIFT}</span></div>
</fieldset>
`);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(tj);
                let TP_Timer = () => {
                    setTimeout(() => {
                        var img = document.getElementById("img1")
                        img.src = "https://i0.hdslb.com/bfs/article/10aca7fbe5247b1f217763a12afa0012d988d311.png@1320w_2198h.webp";
                        img.title="神宫司玉藻"
                    }, 5000);
                    setTimeout(() => {
                        var img = document.getElementById("img1")
                        img.src = "https://i0.hdslb.com/bfs/article/fe789e3af417418ad8c0a4e03ba40867dba0c55f.png@1320w_2198h.webp";
                        img.title="罗兹·巴蕾特"
                    }, 10000);
                    setTimeout(() => {
                        var img = document.getElementById("img1")
                        img.src = "https://i0.hdslb.com/bfs/article/69468feeb1263f7653adf2bc0e3379d32ad71ac3.png@1320w_2198h.webp";
                        img.title="伊莎贝拉·霍利"
                    }, 15000);
                    setTimeout(() => {
                        var img = document.getElementById("img1")
                        img.src = "https://i0.hdslb.com/bfs/article/1986b954aff538dc8b18ca1cc29e9eccc49df4fc.png@1320w_2198h.webp";
                        img.title="卡缇娅·乌拉诺娃"
                    }, 20000);
                    setTimeout(() => {
                        var img = document.getElementById("img1")
                        img.src = "https://i0.hdslb.com/bfs/article/fce8ebfb187e0f979da10bd32e9e912da9535dd4.png@1320w_2198h.webp";
                        img.title="墨汐"
                    }, 25000);
                    setTimeout(() => {
                        var img = document.getElementById("img1")
                        img.src = "https://i0.hdslb.com/bfs/article/18e41e6720042647581bca0b24b86082e995f5be.png@1320w_2198h.webp";
                        img.title="李清歌"
                    }, 30000);
                };
                TP_Timer();
                setInterval(TP_Timer, 30e3);

                let TPP_Timer = () => {
                    setTimeout(() => {
                        var img = document.getElementById("img2")
                        img.src = "https://i0.hdslb.com/bfs/article/17b1da8162347cd24d8d18a90d3c65962bf63116.png@1320w_742h.webp";
                    }, 5000);
                    setTimeout(() => {
                        var img = document.getElementById("img2")
                        img.src = "https://i0.hdslb.com/bfs/article/0f12ac73dad762c00797c689bccafe42b99219c4.png@1320w_742h.webp";
                    }, 10000);
                    setTimeout(() => {
                        var img = document.getElementById("img2")
                        img.src = "https://i0.hdslb.com/bfs/article/6a7b6b232036ecadc221e7a741c9910273782081.png@1320w_742h.webp";
                    }, 15000);
                    setTimeout(() => {
                        var img = document.getElementById("img2")
                        img.src = "https://i0.hdslb.com/bfs/article/8f79f9c1f1f7a6698a27d423db22e263d09ed179.png@1320w_742h.webp";
                    }, 20000);
                    setTimeout(() => {
                        var img = document.getElementById("img2")
                        img.src = "https://i0.hdslb.com/bfs/article/5fe092b5c2c32c3363dd447ac9b71b97d9606684.png@1320w_742h.webp";
                    }, 25000);
                    setTimeout(() => {
                        var img = document.getElementById("img2")
                        img.src = "https://i0.hdslb.com/bfs/article/1b709eed8bd104d2429cf294be6e7e5448a45e47.png@1320w_742h.webp";
                    }, 30000);
                };
                TPP_Timer();
                setInterval(TPP_Timer, 30e3);

                let tp = $('<div>');//立牌
                tp.css({
                    'position': 'absolute',
                    'top': '5px',
                    'right': '30px',
                    'z-index': '-1',
                    'overflow': 'hidden',
                });
                tp.append(`
<img id="img1" src="https://i0.hdslb.com/bfs/article/18e41e6720042647581bca0b24b86082e995f5be.png@1320w_2198h.webp" width="116" height="195" title="李清歌" />
`);

                goldbox = $('<div>');//金宝箱
                goldbox.css({
                    'position': 'absolute',
                    'top': '285px',
                    'right': '50px',
                    'z-index': '-1',
                });
                goldbox.append(`
<img id="box" src="https://i0.hdslb.com/bfs/live/c3ed87683f6e87d256d1f5fdddbfb220fc4c2cdf.png"/>
`);


                let tpp = $("<div class='zdbgjtpp'>");//海报
                tpp.css({
                    'position': 'absolute',
                    'z-index': '-99',
                    'overflow': 'hidden',
                });


                tpp.append(`

<img id="img2" src="https://i0.hdslb.com/bfs/article/2dc43fa70b7ee108787716f3003691fe9fe8876f.png@1320w_742h.webp" />

`);
                //     $('.bilibili-live-player-video-area').prepend(tpp);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').prepend(tpp);
                let tppp = $("<div class='zdbgjtppp'>");
                tppp.css({
                    'position': 'absolute',
                    'top': '225px',
                    'right': '360px',
                    'z-index': '-1',
                    'overflow': 'hidden',
                });
                let tpppp = $("<div class='zdbgjtpppp'>");   ///虚拟小电视
                tpppp.css({
                    'position': 'Absolute',
                    'top': '-170px',
                    'right': '10px',
                    'z-index': '-1111',

                });
                tpppp.append(`

<img id="img4" src="https://i0.hdslb.com/bfs/live/746a8db0702740ec63106581825667ae525bb11a.gif"/>

`);
                let ctt = $('.control-panel-ctnr.border-box.p-relative');
                ctt.append(tpppp);//向聊天框加入信息
                tj.find('#guanzhu [data-action="guanzhu"]').click(function () {//
                    setTimeout(() => {
                        tpppp.css({
                            'z-index': '9999',
                        });
                    }, 3e3);
                    MY_API.chatLog('感谢小可爱赠送的虚拟小电视');
                    setTimeout(() => {
                        tpppp.css({
                            'z-index': '-9999',
                        });
                    }, 13e3);
                });

                tppp.append(`

<img id="img3" src="https://i0.hdslb.com/bfs/article/f1f1c5f49a3561b28b85304ceaed678a14dad39a.gif" width="60" height="60" />

`);



                div.append(`
<fieldset>
<legend append style="color: #FF34B3;text-align: left;">欢迎来到<span>${ZBJ}</span>的直播间</legend> </div>
<div id="giftCount" style="font-size: small;color:  green;">
<span>${yue}</span>月<span>${ri}</span>日&nbsp;&nbsp;&nbsp今日辣条:<span>${MY_API.GIFT_COUNT.COUNT}</div>
</fieldset>

<fieldset>
<legend id="CJ" style="color: #FF34B3;text-align: left;">我要修仙【<span>${CJ}</span>】</legend></div>
<div id="TTgiftCount" style="font-size: small;color:  green;">
<div>攻击:<span>${MY_API.GIFT_COUNT.TTCOUNT}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
防御:<span>${MY_API.GIFT_COUNT.TTLOVE_COUNT}</span></div>

<div id="BPJY" style="font-size: small;color:  green;">
<div>经验:<span>${MY_API.GIFT_COUNT.BPJY}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
等级:Lv<span>${MY_API.GIFT_COUNT.BPDJ}</span></div>
</fieldset>



<fieldset>
<legend append style="color: #FF34B3">修仙插件参数设置</legend></div>
<a target="_blank" href="https://greasyfork.org/zh-CN/scripts/398119"><button style="color: red">脚本更新</button></a>
<a target="_blank" href="https://shang.qq.com/wpa/qunwpa?idkey=6a64d45dd58c63491c2c9a1da8aa3a0b94c09c4eee576ed601b8094b6bf44eb8"><button style="color: red">加入Q群</button></a>
<apend id="giftCountsent" style="color: blue">
<button data-action="countsent" style="color: red" title="点击发送等级辣条弹幕">低调使用,闷声发财,交流加群</button>

<div data-toggle="TOP">
<input style="vertical-align: text-top;" type="checkbox" ><append style="color: Orange" title="开启领取舰长抽奖">自动现时榜抽奖等 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<data-toggle="CZ" title="自动刷新直播间间隔时间" >自动刷新间隔设置
</div>
<div data-toggle="TALK">
<input style="vertical-align: text-top;" type="checkbox" ><append style="color: Orange">隐藏抽奖信息反馈 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input class="CZTIME" style="width: 35px;vertical-align: AUTO;" type="text">分钟
<button data-action="save" style="color: Orange">保存</button>
</div>

<div data-toggle="AUTO_OLDTOP">
<apend style="margin: 5px auto; color: #FF34B3">
<input style="vertical-align: text-top;" type="checkbox">自动昔时榜抽奖等&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<apend style="color: red">(注:时榜抽奖较占内存!)
</div>


<div data-toggle="AUTO_TREASUREBOX">
<apend style="margin: 5px auto; color: #FF34B3">
<input style="vertical-align: text-top;" type="checkbox">自动嗑银瓜子宝箱&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<apend style="color: red">(昔榜抽奖收益可能较少!)
</div>

<div data-toggle="AUTO_BOX">
<apend style="margin: 5px auto; color: #FF34B3">
<input style="vertical-align: text-top;" type="checkbox">自动兑换每日硬币&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<apend style="color: red">(超出量的辣条会送给我!)
</div>

<div data-toggle="AUTO_HEART">
<apend style="margin: 5px auto; color: #FF34B3">
<input style="vertical-align: text-top;" type="checkbox">自动加速领取心心&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<apend style="color: red">(加速倍率与开播数相关!)
</div>


<div data-toggle="TOPFLASH">
<apend style="margin: 5px auto; color: blue">
双时榜单抽奖间隔:<input class="num" style="width: 36px;vertical-align: top;" type="text">秒
<button data-action="save" style="color: blue">保存</button>
</div>

<div data-toggle="TOPspeedup">
<apend style="margin: 5px auto; color: blue">
最大心心加速倍率:<input class="num" style="width: 36px;vertical-align: top;" type="text">倍
<button data-action="save" style="color: blue">保存</button>
</div>



<div data-toggle="RANDOM_DELAY">
<apend style="margin: 5px auto; color: blue">
<input style="vertical-align: text-top;" type="checkbox">随机延迟

<input class="start" style="width: 15px;vertical-align: top;" type="text">~
<input class="end" style="width: 15px;vertical-align: top;" type="text">秒后抽奖
<button data-action="save" style="color: blue">保存</button>
</div>


<div data-toggle="MAXGIFT">
<apend style="margin: 5px auto; color: blue">
每日辣条数上限(整数)<input class="num" style="width: 40px;vertical-align: top;" type="text">
<button data-action="save" style="color: blue">保存</button>
</div>


<div data-toggle="RANDOMSKIP">
<apend style="color: purple">
百分比随机跳过礼物<input class="per" style="width: 20px;vertical-align: top;" type="text">%(整数0-100)
<button data-action="save" style="color: purple">保存</button>
</div>


<div data-toggle="TIMEAREADISABLE">
<apend style="margin: 5px auto; color: purple">
<input style="vertical-align: text-top;" type="checkbox">启用
<input class="start" style="width: 15px;vertical-align: top;" type="text">点至
<input class="end" style="width: 15px;vertical-align: top;" type="text">点不抽奖(24小时制)
<button data-action="save" style="color: purple">保存</button>
</div>

<div data-toggle="onedayLT">
<apend style="margin: 5px auto; color: purple">
<input style="vertical-align: text-top;" type="checkbox">5分钟后过期辣条:房间
<input class="start" style="width: 50px;vertical-align: top;" type="text">数量
<input class="end" style="width: 30px;vertical-align: top;" type="text">
<button data-action="save" style="color: purple">保存</button>
</div>

</fieldset>

<fieldset>
<legend append style="color: #FF34B3">温馨提示:本插件仅在以下直播间有效</legend>
<div style="color: red">传送门:<a target="_blank" href="https://live.bilibili.com/14578426"><button style="color: red">战斗吧歌姬</button></a>(墙裂推荐,人美歌甜请单推)</div>
<div style="color: red">传送门:<a target="_blank" href="https://live.bilibili.com/2374828"><button style="color: red">风绫丨钰袖</button></a>(无声挂机,不占网络求关注)</div>

<div id="hb" style="color: #FF34B3">
<button data-action="tpphide" style="color: #FF34B3" title="点击显示/隐藏" >【战斗吧歌姬海报】</button>
<button data-action="tppshow" style="color: #FF34B3" title="点击显示/隐藏" >【黑历史统计】</button></div>
</fieldset>
`);
                //<div style="color: #FF34B3">欢迎投喂B坷垃/20币/充电50电池领取修仙勋章</div>
                /*<div id="giftCount" style="color: blue">
        归零辣条亲密度,三秒后刷新直播间<button style="font-size: small" data-action="countReset" ><append style="color: red">归零</button>
        </div>


        <div data-toggle="TIME_GET" style="color: #FF34B3">
礼物点击速度(整数):
<input class="delay-seconds" type="text" style="width: 30px;vertical-align: top;" style="color: #FF34B3">毫秒
<button data-action="save" style="color: red">保存</button>
</div>
*/
                let hls = $("<div class='hls'>");//黑历史框
                hls.css({
                    'width': '250px',
                    'height': '150px',
                    'position': 'absolute',
                    'top': '10px',
                    'right': '505px',
                    'background': 'rgba(255,255,255,.8)',
                    'padding': '10px',
                    'z-index': '11',
                    'border-radius': '12px',
                    'transition': 'height .3s',
                    'overflow': 'hidden',
                    'line-height': '15px'
                });


                hls.append(`
<fieldset>
<legend append style="color: #FF34B3;text-align: left;"><span>黑历史统计</legend> </div>
<div  id="hls0" style="font-size: small;color:#FF34B3;">
PK抽奖黑屋次数:<span>${MY_API.GIFT_COUNT.pkblockedn}</span></div>
<div  id="hls1" style="font-size: small;color:#FF34B3;">
PK抽奖黑屋时间:<span>${MY_API.GIFT_COUNT.pkblockedt}</span></div>
<div id="hls2" style="font-size: small;color:#FF34B3;">
瓜子宝箱黑屋次数:<span>${MY_API.GIFT_COUNT.blockedn}</span></div>
<div id="hls3" style="font-size: small;color:#FF34B3;">
瓜子宝箱黑屋时间:<span>${MY_API.GIFT_COUNT.blockedt}</span></div>
<div id="hls4" style="font-size: small;color:#FF34B3;">
舰长抽奖黑屋次数:<span>${MY_API.GIFT_COUNT.guardblockedn}</span></div>
<div id="hls5" style="font-size: small;color:#FF34B3;">
舰长抽奖黑屋时间:<span>${MY_API.GIFT_COUNT.guardblockedt}</span></div>
<div id="hls6" style="font-size: small;color:#FF34B3;">
礼物抽奖黑屋次数:<span>${MY_API.GIFT_COUNT.giftblockedn}</span></div>
<div id="hls7" style="font-size: small;color:#FF34B3;">
礼物抽奖黑屋时间:<span>${MY_API.GIFT_COUNT.giftblockedt}</span></div>
</fieldset>

`);

                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(hls);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(div);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(tp);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(goldbox);
                //$('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(tppp);
                $('.hls').hide();
                //对应配置状态
                div.find('div[data-toggle="RANDOMSKIP"] .per').val((parseInt(MY_API.CONFIG.RANDOMSKIP)).toString());
                div.find('div[data-toggle="MAXGIFT"] .num').val((parseInt(MY_API.CONFIG.MAXGIFT)).toString());
                div.find('div[data-toggle="TOPFLASH"] .num').val((parseInt(MY_API.CONFIG.TOPFLASH)).toString());
                div.find('div[data-toggle="TOPspeedup"] .num').val((parseInt(MY_API.CONFIG.TOPspeedup)).toString());
                div.find('div[data-toggle="TALK"] .CZTIME').val((parseInt(MY_API.CONFIG.CZ)).toString());
                if (MY_API.CONFIG.TOP) div.find('div[data-toggle="TOP"] input').attr('checked', '');
                if (MY_API.CONFIG.TALK) div.find('div[data-toggle="TALK"] input').attr('checked', '');
                if (MY_API.CONFIG.AUTO_OLDTOP) div.find('div[data-toggle="AUTO_OLDTOP"] input').attr('checked', '');
                if (MY_API.CONFIG.AUTO_TREASUREBOX) div.find('div[data-toggle="AUTO_TREASUREBOX"] input').attr('checked', '');
                if (MY_API.CONFIG.AUTO_BOX) div.find('div[data-toggle="AUTO_BOX"] input').attr('checked', '');
                if (MY_API.CONFIG.AUTO_HEART) div.find('div[data-toggle="AUTO_HEART"] input').attr('checked', '');
                if (MY_API.CONFIG.RANDOM_DELAY) div.find('div[data-toggle="RANDOM_DELAY"] input').attr('checked', '');


                if (MY_API.CONFIG.AUTO_GOLDBOX) tj.find('div[data-toggle="AUTO_GOLDBOX"] input').attr('checked', '');


                div.find('div[data-toggle="RANDOM_DELAY"] .start').val(MY_API.CONFIG.TIMESTART.toString());
                div.find('div[data-toggle="RANDOM_DELAY"] .end').val(MY_API.CONFIG.TIMEEND.toString());

                if (MY_API.CONFIG.GIFT_AUTO) div.find('div[data-toggle="onedayLT"] input').attr('checked', '');
                div.find('div[data-toggle="onedayLT"] .start').val(MY_API.CONFIG.GIFT_ROOM.toString());
                div.find('div[data-toggle="onedayLT"] .end').val(MY_API.CONFIG.GIFT_NUM.toString());



                if (MY_API.CONFIG.TIMEAREADISABLE) div.find('div[data-toggle="TIMEAREADISABLE"] input').attr('checked', '');
                div.find('div[data-toggle="TIMEAREADISABLE"] .start').val(MY_API.CONFIG.TIMEAREASTART.toString());
                div.find('div[data-toggle="TIMEAREADISABLE"] .end').val(MY_API.CONFIG.TIMEAREAEND.toString());
                div.find('div[data-toggle="RANDOMSKIP"] [data-action="save"]').click(function () {//RANDOMSKIP save按钮
                    let val = parseInt(div.find('div[data-toggle="RANDOMSKIP"] .per').val());
                    if (MY_API.CONFIG.RANDOMSKIP === val) {
                        MY_API.chatLog('改都没改保存嘛呢');
                        return
                    }
                    MY_API.CONFIG.RANDOMSKIP = val;
                    MY_API.saveConfig()
                });

                div.find('div[data-toggle="MAXGIFT"] [data-action="save"]').click(function () {//MAXGIFT save按钮
                    let val = parseInt(div.find('div[data-toggle="MAXGIFT"] .num').val());
                    if (MY_API.CONFIG.MAXGIFT === val) {
                        MY_API.chatLog('改都没改保存嘛呢');
                        return
                    }
                    MY_API.CONFIG.MAXGIFT = val;
                    MY_API.saveConfig()
                });

                div.find('div[data-toggle="TOPFLASH"] [data-action="save"]').click(function () {//TOPFLASH save按钮
                    let val = parseInt(div.find('div[data-toggle="TOPFLASH"] .num').val());
                    if (MY_API.CONFIG.TOPFLASH === val) {
                        MY_API.chatLog('改都没改保存嘛呢');
                        return
                    }
                    if(val<120){
                        MY_API.chatLog('男人不能太快哦ლ(╹◡╹ლ)');
                        val=120

                    }else if(val>1000){
                        MY_API.chatLog('你要上天啊Σ( ° △ °|||)︴');
                        val=1000
                    }
                    MY_API.CONFIG.TOPFLASH = val;
                    MY_API.saveConfig()
                    MY_API.chatLog('现时榜单抽奖间隔时间已设置,刷新页面后生效');
                });

                div.find('div[data-toggle="TOPspeedup"] [data-action="save"]').click(function () {//TOPspeedup save按钮
                    let val = parseInt(div.find('div[data-toggle="TOPspeedup"] .num').val());
                    if (MY_API.CONFIG.TOPspeedup === val) {
                        MY_API.chatLog('改都没改保存嘛呢');
                        return
                    }
                    if(val<1){
                        MY_API.chatLog('男人不能太小哦ლ(╹◡╹ლ)');
                        val=2

                    }else if(val>10){
                        MY_API.chatLog('你要上天啊Σ( ° △ °|||)︴');
                        val=10
                    }
                    MY_API.CONFIG.TOPspeedup = val;
                    MY_API.saveConfig()
                    MY_API.chatLog('最大加速倍率已设置,加速倍率受开播的有勋章的直播间数量限制,刷新页面后生效');
                });

                div.find('div[data-toggle="TALK"] [data-action="save"]').click(function () {
                    let val = parseInt(div.find('div[data-toggle="TALK"] .CZTIME').val());
                    if (MY_API.CONFIG.CZ === val) {
                        MY_API.chatLog('改都没改保存嘛呢');
                        return
                    }

                    if(val<30){
                        MY_API.chatLog('男人不能太快哦ლ(╹◡╹ლ)');
                        val=30

                    }else if(val>1500){
                        MY_API.chatLog('你要上天啊Σ( ° △ °|||)︴');
                        val=1500
                    }
                    MY_API.CONFIG.CZ = val;
                    MY_API.saveConfig()
                    MY_API.chatLog('直播间自动刷新时间已设置,刷新页面后生效');

                });


                div.find('div[data-toggle="TOP"] input').change(function () {//
                    MY_API.CONFIG.TOP = $(this).prop('checked');
                    MY_API.saveConfig()
                });

                div.find('div[data-toggle="AUTO_OLDTOP"] input').change(function () {//
                    MY_API.CONFIG.AUTO_OLDTOP = $(this).prop('checked');
                    MY_API.saveConfig()
                });


                div.find('div[data-toggle="TALK"] input').change(function () {//
                    MY_API.CONFIG.TALK = $(this).prop('checked');
                    if (MY_API.CONFIG.TALK == true) {//自定义提示开关
                        $('.zdbgjMsg').hide(); //隐藏反馈信息
                    }
                    MY_API.saveConfig()
                });

                div.find('div[data-toggle="AUTO_BOX"] input').change(function () {//
                    MY_API.CONFIG.AUTO_BOX = $(this).prop('checked');
                    MY_API.saveConfig()
                    if(MY_API.CONFIG.AUTO_BOX){
                        setTimeout(() => {
                            MY_API.Exchange.run();
                        }, 3e3);
                    }
                });

                div.find('div[data-toggle="AUTO_HEART"] input').change(function () {//
                    MY_API.CONFIG.AUTO_HEART = $(this).prop('checked');
                    MY_API.saveConfig()
                    if(MY_API.CONFIG.AUTO_HEART){
                        setTimeout(() => {
                            MY_API.SmallHeart.run();
                        }, 3e3);
                    }
                });

                tj.find('div[data-toggle="AUTO_GOLDBOX"] input').change(function () {//
                    MY_API.CONFIG.AUTO_GOLDBOX = $(this).prop('checked');
                    MY_API.saveConfig()
                    if(MY_API.CONFIG.AUTO_GOLDBOX){
                        setTimeout(() => {
                            MY_API.MaterialObject.run();
                        }, 3e3);
                    }
                });

                div.find('div[data-toggle="AUTO_TREASUREBOX"] input').change(function () {//
                    MY_API.CONFIG.AUTO_TREASUREBOX = $(this).prop('checked');
                    MY_API.saveConfig()
                    if(MY_API.CONFIG.AUTO_TREASUREBOX){
                        setTimeout(() => {
                            MY_API.TreasureBox.run();
                        }, 3e3);
                    }
                });

                div.find('div[data-toggle="RANDOM_DELAY"] input').change(function () {//
                    MY_API.CONFIG.RANDOM_DELAY = $(this).prop('checked');
                    MY_API.saveConfig()
                });

                div.find('div[data-toggle="RANDOM_DELAY"] [data-action="save"]').click(function () {//
                    MY_API.CONFIG.TIMESTART = parseInt(div.find('div[data-toggle="RANDOM_DELAY"] .start').val());
                    MY_API.CONFIG.TIMEEND = parseInt(div.find('div[data-toggle="RANDOM_DELAY"] .end').val());
                    MY_API.saveConfig()
                });


                //GIFT_AUTO:false,
                //GIFT_NUM: 2000,
                // GIFT_ROOM: 2374828,

                div.find('div[data-toggle="onedayLT"] input:checkbox').change(function () {//
                    MY_API.CONFIG.GIFT_AUTO = $(this).prop('checked');
                    MY_API.saveConfig()
                });

                div.find('div[data-toggle="onedayLT"] [data-action="save"]').click(function () {//
                    MY_API.CONFIG.GIFT_ROOM = parseInt(div.find('div[data-toggle="onedayLT"] .start').val());
                    MY_API.CONFIG.GIFT_NUM = parseInt(div.find('div[data-toggle="onedayLT"] .end').val());
                    MY_API.saveConfig()
                });


                div.find('div[data-toggle="TIMEAREADISABLE"] input:checkbox').change(function () {//
                    MY_API.CONFIG.TIMEAREADISABLE = $(this).prop('checked');
                    MY_API.saveConfig()
                });

                div.find('div[data-toggle="TIMEAREADISABLE"] [data-action="save"]').click(function () {//
                    MY_API.CONFIG.TIMEAREASTART = parseInt(div.find('div[data-toggle="TIMEAREADISABLE"] .start').val());
                    MY_API.CONFIG.TIMEAREAEND = parseInt(div.find('div[data-toggle="TIMEAREADISABLE"] .end').val());
                    MY_API.saveConfig()
                });

                if(Live_info.room_id === 2374828){
                    let GJTP_Timer = () => {
                        var kd=  $('.bilibili-live-player-video-area').width();
                        var gd=  $('.bilibili-live-player-video-area').height();
                        //$('.bilibili-live-player-ending-panel').remove();
                        $("#img2").width(kd).height(gd);
                    };
                    GJTP_Timer();
                    setInterval(GJTP_Timer, 5e3);

                    div.css({
                        'z-index': '10',
                    });
                    tj.css({
                        'z-index': '10',
                    });
                    tp.css({
                        'z-index': '10',
                    });
                    goldbox.css({
                        'z-index': '10',
                    });
                    tpp.css({
                        'z-index': '10',
                    });
                    tppp.css({
                        'z-index': '10',
                    });
                    msg.css({
                        'z-index': '-1',
                    });

                }else  {
                    tpp.css({
                        'width': '0px',
                        'height': '0px',
                    });
                }


                div.find('#giftCountsent [data-action="countsent"]').click(function () {//
                    BAPI.room.room_entry_action(2374828);//直播间进入记录
                    BAPI.sendLiveDanmu(`Lv${BPDJ},${COUNT}`,2374828)

                });
                setTimeout(() => {
                    BAPI.room.room_entry_action(2374828);//直播间进入记录
                    BAPI.sendLiveDanmu(`嘀,修仙卡`,2374828)
                }, 5000);

                div.find('#hb [data-action="tpphide"]').click(function () {//
                    $('.zdbgjtpp').toggle();

                });

                div.find('#hb [data-action="tppshow"]').click(function () {//
                    $('.hls').toggle();
                });
                /* div.find('#giftCount [data-action="countReset"]').click(function () {//
                MY_API.GIFT_COUNT = {
                    COUNT: 0,
                    LOVE_COUNT: 0,
                    CLEAR_TS: 0,
                };
                MY_API.saveGiftCount();
               MY_API.chatLog('辣条亲密度正在清零,3秒后刷新页面');
               setTimeout(() => {
                   window.location.reload()
                }, 3000);
            });

            */
            },



            chatLog: function (text, type = 'info') {//自定义提示
                let div = $("<div class='zdbgjMsg'>");
                let msg = $("<div>");
                let ct = $('#chat-items');
                let myDate = new Date();
                msg.text(text);
                div.text(myDate.toLocaleString());
                div.append(msg);
                div.css({
                    'text-align': 'center',
                    'border-radius': '4px',
                    'min-height': '30px',
                    'width': '256px',
                    'color': '#00B2EE',
                    'line-height': '30px',
                    'padding': '0 10px',
                    'margin': '10px auto',
                });
                msg.css({
                    'word-wrap': 'break-word',
                    'width': '100%',
                    'line-height': '1em',
                    'margin-bottom': '10px',
                });
                switch (type) {
                    case 'warning':
                        div.css({
                            'border': '1px solid rgb(236, 221, 192)',
                            'color': 'rgb(218, 142, 36)',
                            'background': 'rgb(245, 235, 221) none repeat scroll 0% 0%',
                        });
                        break;
                    case 'success':
                        div.css({
                            'border': '1px solid rgba(22, 140, 0, 0.28)',
                            'color': 'rgb(69, 171, 69)',
                            'background': 'none 0% 0% repeat scroll rgba(16, 255, 0, 0.18)',
                        });
                        break;
                    default:
                        div.css({
                            'border': '1px solid rgb(203, 195, 255)',
                            'background': 'rgb(233, 230, 255) none repeat scroll 0% 0%',
                        });
                }

                ct.append(div);//向聊天框加入信息
                let ctt = $('#chat-history-list');
                ctt.animate({scrollTop: ctt.prop("scrollHeight")}, 0);//滚动到底部
            },
            //blocked: false,
            giftblocked: false,
            guardblocked: false,
            pkblocked: false,
            listen: (roomId, uid, area = '本直播间') => {
                BAPI.room.getConf(roomId).then((response) => {
                    server_host = response.data.host;
                    console.log('服务器地址', response);
                    let wst = new BAPI.DanmuWebSocket(uid, roomId, response.data.host_server_list, response.data.token);
                    wst.bind((newWst) => {
                        wst = newWst;
                        if (MY_API.GIFT_COUNT.CLEAR_TS) {
                            MY_API.chatLog(`【${area}】弹幕服务器连接断开,尝试重连`, 'warning');
                        }
                    }, () => {
                        if (MY_API.GIFT_COUNT.CLEAR_TS) {
                            MY_API.chatLog(`【${area}】连接弹幕服务器成功 `, 'success');
                        }
                    },() => {
                        if (MY_API.GIFT_COUNT.COUNT >= MY_API.CONFIG.MAXGIFT) {//判断是否超过辣条限制
                            console.log('超过今日辣条限制,不参与抽奖');
                            wst.close();
                            MY_API.chatLog(`超过今日辣条限制,主动与弹幕服务器断开连接-【${area}】`, 'warning')
                        };
                        if (MY_API.giftblocked &MY_API.guardblocked &MY_API.pkblocked) {
                            wst.close();
                            MY_API.chatLog(`进了小黑屋主动与弹幕服务器断开连接-【${area}】`, 'warning')
                        };
                    }, (obj) => {
                        if (inTimeArea(MY_API.CONFIG.TIMEAREASTART, MY_API.CONFIG.TIMEAREAEND) && MY_API.CONFIG.TIMEAREADISABLE) return;//当前是否在两点到八点 如果在则返回
                        console.log('弹幕公告' + area, obj);
                        switch (obj.cmd) {
                            case 'GUARD_MSG':
                                if (obj.roomid === obj.real_roomid) {
                                    MY_API.checkRoom(obj.roomid, area);
                                } else {
                                    MY_API.checkRoom(obj.roomid, area);
                                    MY_API.checkRoom(obj.real_roomid, area);
                                }
                                break;
                            case 'PK_BATTLE_SETTLE_USER':
                                MY_API.checkRoom(obj.data.winner.room_id, area);
                                break;
                            case 'NOTICE_MSG':
                                if (obj.roomid === obj.real_roomid) {
                                    MY_API.checkRoom(obj.roomid, area);
                                } else {
                                    MY_API.checkRoom(obj.roomid, area);
                                    MY_API.checkRoom(obj.real_roomid, area);
                                }
                                break;
                            default:
                                return;
                        }
                    });
                }, () => {
                    MY_API.chatLog('获取弹幕服务器地址错误', 'warning')
                });
            },
            RoomId_list: [],
            checkRoom: function (roomId, area = '本直播间') {
                if (MY_API.giftblocked &MY_API.guardblocked &MY_API.pkblocked) {
                    return
                }
                if (MY_API.RoomId_list.indexOf(roomId) >= 0) {//防止重复检查直播间
                    return
                } else {
                    MY_API.RoomId_list.push(roomId);
                }
                BAPI.room.room_entry_action(roomId);//直播间进入记录
                $.get('https://api.live.bilibili.com/xlive/lottery-interface/v1/lottery/Check?roomid=' + roomId,
                      function (re) {
                    setTimeout(() => {
                        MY_API.RoomId_list.remove(roomId);//移除房间号
                        console.log('防重复检查房间号列表', MY_API.RoomId_list);
                    }, 5e3);
                    console.log('检查房间返回信息', re);
                    let data = re.data;
                    if (re.code === 0) {
                        let list;
                        if (data.gift) {
                            if (MY_API.giftblocked ) {
                                return
                            }
                            list = data.gift;
                            for (let i in list) {
                                if (!list.hasOwnProperty(i)) continue;
                                MY_API.creat_join(roomId, list[i], 'gift', area)
                            }
                        }
                        if (data.guard) {
                            if (MY_API.guardblocked) {
                                return
                            }
                            list = data.guard;
                            for (let i in list) {
                                if (!list.hasOwnProperty(i)) continue;
                                MY_API.creat_join(roomId, list[i], 'guard', area)
                            }
                        }
                        if (data.pk) {
                            if (MY_API.pkblocked) {
                                return
                            }
                            list = data.pk;
                            for (let i in list) {
                                if (!list.hasOwnProperty(i)) continue;
                                MY_API.creat_join(roomId, list[i], 'pk', area)
                            }
                        }
                        let ct = $('#chat-items');
                        let ctt = $('#chat-history-list');
                        ctt.animate({scrollTop: ctt.prop("scrollHeight")}, 0);//滚动到底部

                    } else {
                        MY_API.chatLog(`[检查房间出错]${response.msg}`, 'warning');
                    }
                });
            },

            Id_list_history: {//白嫖十六夜代码
                add: function (id, type) {
                    let id_list = [];
                    try {
                        let config = JSON.parse(localStorage.getItem(`${NAME}_${type}Id_list`));
                        id_list = [].concat(config.list);
                        id_list.push(id);
                        if (id_list.length > 1000) {
                            id_list.splice(0, 200);//删除前200条数据
                        }

                        localStorage.setItem(`${NAME}_${type}Id_list`, JSON.stringify({list: id_list}));
                        console.log(`${NAME}_${type}Id_list_add`, id_list);
                    } catch (e) {
                        id_list.push(id);
                        localStorage.setItem(`${NAME}_${type}Id_list`, JSON.stringify({list: id_list}));
                    }
                },
                isIn: function (id, type) {
                    let id_list = [];
                    try {
                        let config = JSON.parse(localStorage.getItem(`${NAME}_${type}Id_list`));
                        if (config === null) {
                            id_list = [];
                        } else {
                            id_list = [].concat(config.list);
                        }
                        console.log(`${NAME}_${type}Id_list_read`, config);
                        return id_list.indexOf(id) > -1
                    } catch (e) {
                        localStorage.setItem(`${NAME}_${type}Id_list`, JSON.stringify({list: id_list}));
                        console.log('读取' + `${NAME}_${type}Id_list` + '缓存错误已重置');
                        return id_list.indexOf(id) > -1
                    }
                },
            },
            raffleId_list: [],
            raffleId_list_history: [],
            guardId_list: [],
            pkId_list: [],
            creat_join: function (roomId, data, type, area = '本直播间') {
                console.log('礼物信息', data);
                switch (type) {//防止重复抽奖上船PK
                    case 'gift':
                        if (MY_API.GIFT_COUNT.COUNT >= MY_API.CONFIG.MAXGIFT) {//判断是否超过辣条限制
                            console.log('超过今日辣条限制,不参与抽奖');
                            MY_API.chatLog('超过今日辣条限制,不参与抽奖');
                            return
                        }
                        if (MY_API.giftblocked ) {
                            /* let bj1=0;
                            if (bj1==0) {
                                bj1=1;
                                setTimeout(() => {
                                    MY_API.giftblocked=false;
                                }, 1800000);
                            };*/
                            return;
                        }
                        if (MY_API.raffleId_list_history.indexOf(data.raffleId) > -1) {
                            return
                        } else {
                            MY_API.raffleId_list.push(data.raffleId);
                            MY_API.raffleId_list_history.push(data.raffleId);
                        }
                        if (MY_API.Id_list_history.isIn(data.raffleId, 'raffle')) {
                            console.log('礼物重复');
                            return
                        } else {
                            MY_API.raffleId_list.push(data.raffleId);
                            MY_API.Id_list_history.add(data.raffleId, 'raffle');
                        }
                        break;
                    case 'guard':
                        if (MY_API.GIFT_COUNT.COUNT >= MY_API.CONFIG.MAXGIFT) {//判断是否超过辣条限制
                            console.log('超过今日辣条限制,不参与抽奖');
                            MY_API.chatLog('超过今日辣条限制,不参与抽奖');
                            return
                        }
                        if (MY_API.guardblocked ) {
                            /*  let bj2=0;
                            if (bj2==0) {
                                bj2=1;
                                setTimeout(() => {
                                    MY_API.guardblocked=false;
                                }, 1800000);
                            };*/
                            return;
                        }
                        if (MY_API.guardId_list.indexOf(data.id) >= 0) {
                            return
                        } else {
                            MY_API.guardId_list.push(data.id);
                        }
                        if (MY_API.Id_list_history.isIn(data.id, 'guard')) {
                            console.log('舰长重复');
                            return
                        } else {
                            MY_API.guardId_list.push(data.id);
                            MY_API.Id_list_history.add(data.id, 'guard');
                        }
                        break;
                    case 'pk':
                        if (MY_API.GIFT_COUNT.COUNT >= MY_API.CONFIG.MAXGIFT) {//判断是否超过辣条限制
                            console.log('超过今日辣条限制,不参与抽奖');
                            MY_API.chatLog('超过今日辣条限制,不参与抽奖');
                            return
                        }
                        if (MY_API.pkblocked ) {
                            /*let bj3=0;
                            if (bj3==0) {
                                bj3=1;
                                setTimeout(() => {
                                    MY_API.pkblocked=false;
                                }, 1800000);
                            };*/
                            return;
                        }
                        if (MY_API.pkId_list.indexOf(data.id) >= 0) {
                            return
                        } else {
                            MY_API.pkId_list.push(data.id);
                        }
                        if (MY_API.Id_list_history.isIn(data.id, 'pk')) {
                            console.log('pk重复');
                            return
                        } else {
                            MY_API.pkId_list.push(data.id);
                            MY_API.Id_list_history.add(data.id, 'pk');
                        }
                        break;
                }

                let delay = data.time_wait || 0;

                if (MY_API.CONFIG.RANDOM_DELAY) delay += MY_API.CONFIG.TIMESTART + Math.ceil(Math.random() * (MY_API.CONFIG.TIMEEND-MY_API.CONFIG.TIMESTART));//随机延迟
                let div = $("<div class='zdbgjMsg'>");
                let msg = $("<div>");
                let aa = $("<div>");
                let ct = $('#chat-items');
                let myDate = new Date();
                msg.text(`【${area}】` + data.thank_text.split('<%')[1].split('%>')[0] + data.thank_text.split('%>')[1]);
                div.text(myDate.toLocaleString());
                div.append(msg);
                aa.css('color', 'red');
                aa.text('等待抽奖');
                msg.append(aa);
                div.css({
                    'text-align': 'center',
                    'border-radius': '4px',
                    'min-height': '30px',
                    'width': '256px',
                    'color': '#9585FF',
                    'line-height': '30px',
                    'padding': '0 10px',
                    'margin': '10px auto',
                });
                msg.css({
                    'word-wrap': 'break-word',
                    'width': '100%',
                    'line-height': '1em',
                    'margin-bottom': '10px',
                });

                div.css({
                    'border': '1px solid rgb(203, 195, 255)',
                    'background': 'rgb(233, 230, 255) none repeat scroll 0% 0%',
                });


                if (MY_API.CONFIG.TALK == false) {//自定义提示开关
                    ct.append(div);//向聊天框加入信息
                }


                let timer = setInterval(function () {
                    aa.text(`等待抽奖倒计时${delay}秒`);
                    if (delay <= 0) {
                        if (probability(MY_API.CONFIG.RANDOMSKIP)) {
                            aa.text(`跳过此礼物抽奖`);
                        } else {
                            aa.text(`进行抽奖...`);
                            switch (type) {
                                case 'gift':
                                    MY_API.gift_join(roomId, data.raffleId, data.type).then(function (msg, num) {
                                        aa.text('获得' + msg);
                                        if (num && msg.indexOf('辣条') >= 0) {
                                            MY_API.addGift(num);
                                        }
                                    });
                                    break;
                                case 'guard':
                                    MY_API.guard_join(roomId, data.id).then(function (msg, num) {
                                        aa.text('获得' + msg);
                                        if (num) {
                                            MY_API.addLove(num);
                                            MY_API.addGift(num);
                                        }
                                    });
                                    break;
                                case 'pk':
                                    MY_API.pk_join(roomId, data.id).then(function (msg, num) {
                                        aa.text('获得' + msg);
                                        if (num && msg.indexOf('辣条') >= 0) {
                                            MY_API.addGift(num);
                                        }
                                    });
                                    break;
                            }
                        }

                        aa.css('color', 'green');
                        MY_API.raffleId_list.remove(data.raffleId);
                        clearInterval(timer)
                    }
                    delay--;

                }, 1000);

            },
            gift_join: function (roomid, raffleId, type) {
                let p = $.Deferred();
                BAPI.Lottery.Gift.join(roomid, raffleId, type).then((response) => {
                    console.log('抽奖返回信息', response);
                    switch (response.code) {
                        case 0:
                            if (response.data.award_text) {
                                p.resolve(response.data.award_text, response.data.award_num);
                            } else {
                                p.resolve(response.data.award_name + 'X' + response.data.award_num.toString()
                                          , response.data.award_num);
                            }
                            break;
                        default:
                            if (response.msg.indexOf('拒绝') > -1) {
                                MY_API.giftblocked = true;//停止抽奖


                                if(!MY_API.GIFT_COUNT.giftblockedb) {
                                    let yue=riqi.getMonth()+1;
                                    let ri=riqi.getDate();
                                    let xiaoshi=riqi.getHours();
                                    let fenzhong=riqi.getMinutes();
                                    MY_API.GIFT_COUNT.giftblockedn+=1;
                                    MY_API.GIFT_COUNT.giftblockedt=`${yue}月${ri}日${xiaoshi}时${fenzhong}分`;
                                    MY_API.saveGiftCount();
                                };

                                p.resolve('抽奖访问被拒绝,暂停抽奖,30分钟后自动重试');
                            } else {

                                MY_API.GIFT_COUNT.giftblockedb=0;
                                MY_API.saveGiftCount();
                                p.resolve(`[礼物抽奖](roomid=${roomid},id=${raffleId},type=${type})${response.msg}`);
                            }
                    }
                });
                return p
            },

            guard_join: function (roomid, Id) {
                let p = $.Deferred();
                BAPI.Lottery.Guard.join(roomid, Id).then((response) => {
                    console.log('上船抽奖返回信息', response);
                    switch (response.code) {
                        case 0:
                            if (response.data.award_text) {
                                p.resolve(response.data.award_text, response.data.award_num);
                            } else {
                                p.resolve(response.data.award_name + 'X' + response.data.award_num.toString()
                                          , response.data.award_num);
                            }
                            break;
                        default:
                            if (response.msg.indexOf('拒绝') > -1) {
                                MY_API.guardblocked = true;//停止抽奖

                                if(!MY_API.GIFT_COUNT.guardblockedb) {
                                    let yue=riqi.getMonth()+1;
                                    let ri=riqi.getDate();
                                    let xiaoshi=riqi.getHours();
                                    let fenzhong=riqi.getMinutes();
                                    MY_API.GIFT_COUNT.guardblockedn+=1;
                                    MY_API.GIFT_COUNT.guardblockedt=`${yue}月${ri}日${xiaoshi}时${fenzhong}分`;
                                    MY_API.saveGiftCount();
                                };

                                p.resolve('上舰抽奖访问被拒绝,暂停上船抽奖,30分钟后自动重试');
                            } else {

                                MY_API.GIFT_COUNT.guardblockedb=0;
                                MY_API.saveGiftCount();
                                p.resolve(`[上船](roomid=${roomid},id=${Id})${response.msg}`);
                            }
                            break;
                    }
                });
                return p
            },


            pk_join: function (roomid, Id) {
                let p = $.Deferred();
                BAPI.Lottery.Pk.join(roomid, Id).then((response) => {
                    console.log('PK抽奖返回信息', response);
                    switch (response.code) {
                        case 0:
                            if (response.data.award_text) {
                                p.resolve(response.data.award_text, response.data.award_num);
                            } else {
                                p.resolve(response.data.award_name + 'X' + response.data.award_num.toString()
                                          , response.data.award_num);
                            }
                            break;
                        default:
                            if (response.msg.indexOf('拒绝') > -1) {
                                MY_API.pkblocked = true;//停止抽奖

                                if(!MY_API.GIFT_COUNT.pkblockedb) {
                                    let yue=riqi.getMonth()+1;
                                    let ri=riqi.getDate();
                                    let xiaoshi=riqi.getHours();
                                    let fenzhong=riqi.getMinutes();
                                    MY_API.GIFT_COUNT.pkblockedn+=1;
                                    MY_API.GIFT_COUNT.pkblockedt=`${yue}月${ri}日${xiaoshi}时${fenzhong}分`;
                                    MY_API.saveGiftCount();
                                };

                                p.resolve('PK抽奖访问被拒绝,暂停PK抽奖,30分钟后自动重试');
                            } else {

                                MY_API.GIFT_COUNT.pkblockedb=0;
                                MY_API.saveGiftCount();
                                p.resolve(`[PK](roomid=${roomid},id=${Id})${response.msg}`);
                            }
                            break;
                    }
                });
                return p
            },

            sendonedayLT: function () {//二次检查时会继续送到设定房间,未做总量累计,剩余少量辣条,可忽略
                BAPI.gift.bag_list().then(function (bagResult) {
                    if (bagResult.data.list[0].corner_mark === '1天' && bagResult.data.list[0].gift_name === '辣条') {
                        BAPI.live_user.get_anchor_in_room(MY_API.CONFIG.GIFT_ROOM).then(function (roomResult) {
                            if(bagResult.data.list[0].gift_num<=MY_API.CONFIG.GIFT_NUM){
                                onedayLT(roomResult.data.info.uid,
                                         bagResult.data.list[0].gift_id,
                                         bagResult.data.list[0].bag_id,
                                         bagResult.data.list[0].gift_num)
                            }else{
                                onedayLT(roomResult.data.info.uid,
                                         bagResult.data.list[0].gift_id,
                                         bagResult.data.list[0].bag_id,
                                         MY_API.CONFIG.GIFT_NUM)
                            }
                            setTimeout(() => {
                                if(bagResult.data.list[0].gift_num > MY_API.CONFIG.GIFT_NUM){
                                    onedayLTUP(roomResult.data.info.uid,
                                               bagResult.data.list[0].gift_id,
                                               bagResult.data.list[0].bag_id,
                                               bagResult.data.list[0].gift_num-MY_API.CONFIG.GIFT_NUM)
                                }
                            },5000);
                        });
                    }
                });
                let onedayLT = (rUid, gift_id, bag_id, num) => {
                    let ts = Math.round(new Date() / 1000);//时间戳
                    BAPI.gift.bag_send(Live_info.uid, gift_id, rUid, num, bag_id, MY_API.CONFIG.GIFT_ROOM, ts).then(function (result) {
                        if (result.code === 0 && result.msg === 'success') {
                            MY_API.chatLog('[马上要过期的1天辣条]' + result.data.send_tips, 'success');
                        } else {
                            MY_API.chatLog('[礼物]赠送失败', 'warning');
                        }
                    });
                };
                let onedayLTUP = (rUid, gift_id, bag_id, num) => {
                    let ts = Math.round(new Date() / 1000);//时间戳
                    BAPI.gift.bag_send(Live_info.uid, gift_id, rUid, num, bag_id, 2374828, ts).then(function (result) {
                        if (result.code === 0 && result.msg === 'success') {
                            MY_API.chatLog('[给UP丢1天辣条吧]' + result.data.send_tips, 'success');
                        } else {
                            MY_API.chatLog('[礼物]赠送失败', 'warning');
                        }
                    });
                };
            },
            SmallHeart:{//引用十六夜代码
                openRoom: [],//记录以及打开的直播间
                timer: undefined,
                run() {
                    if (!MY_API.CONFIG.AUTO_HEART) return;
                    MY_API.chatLog('小心心加速模块开始加载。。。');
                    if (MY_API.SmallHeart.timer) {
                        clearInterval(MY_API.SmallHeart.timer);
                    }
                    if (MY_API.GIFT_COUNT.LCOUNT >= 24) {
                        setTimeout(() => {
                            MY_API.chatLog(`今日小心心已满,停止挂小心心`);
                        }, 1000);
                        MY_API.SmallHeart.stop();
                        return
                    }

                    let LCOUNT_timer = setInterval(() => {//每隔360s检查心心数量,防止意外情况心心数量异常
                        if (MY_API.GIFT_COUNT.LCOUNT == Lcount && Lcount<24 && MY_API.SmallHeart.openRoom.length > 0 ) {
                            MY_API.chatLog(`小心心数长时间未变化可能已满,停止挂小心心`);
                            MY_API.SmallHeart.stop();
                            clearInterval(LCOUNT_timer);
                            return
                        }else {
                            Lcount=MY_API.GIFT_COUNT.LCOUNT;
                        }
                    }, 610e3);


                    MY_API.SmallHeart.timer = setInterval(() => {//每隔60s检查开播勋章直播间
                        if (MY_API.GIFT_COUNT.LCOUNT >= 24) {
                            MY_API.chatLog(`今日小心心已满,停止挂小心心`);
                            MY_API.SmallHeart.stop();
                            return
                        }
                        MY_API.SmallHeart.checkMedalRoom();
                        MY_API.SmallHeart.checkSmallHeartCount();
                    }, 60e3);
                    MY_API.SmallHeart.checkSmallHeartCount();
                    //MY_API.SmallHeart.checkMedalRoom();
                },
                stop() {
                    layer.closeAll();
                    clearInterval(MY_API.SmallHeart.timer);
                },
                checkSmallHeartCount: async () => {
                    let bagResult = await BAPI.gift.bag_list();
                    if (bagResult.code === 0) {
                        for (let i of bagResult.data.list) {
                            if (i.corner_mark === '7天' && i.gift_name === '小心心') {
                                console.log(`[${NAME}]今日小心心数量:${i.gift_num}`);
                                MY_API.GIFT_COUNT.LCOUNT = i.gift_num;
                                MY_API.saveGiftCount();
                                if (i.gift_num === 24) {
                                    MY_API.chatLog(`今日小心心已满,停止挂小心心`);
                                    MY_API.SmallHeart.stop();
                                }
                            }
                        }
                    } else {
                        console.log(`[${NAME}]检查心心数量,获取背包礼物失败`)
                    }
                },
                checkMedalRoom: async () => {
                    if (MY_API.GIFT_COUNT.LCOUNT >= 24) return;
                    let result = await MY_API.SmallHeart.getMedalList();
                    if (result.code === 0) {
                        for (let i of result.data) {
                            if (i.live_stream_status === 1) {
                                let roomId = i.room_id;
                                if (!MY_API.SmallHeart.openRoom.includes(roomId)) {
                                    MY_API.SmallHeart.openWin(roomId);
                                } else {
                                    console.log(`[${NAME}]直播间${roomId}已打开`)
                                }
                            }
                        }
                    } else {
                        console.log(`[${NAME}]获取勋章列表失败`)
                    }
                },
                openWin(roomId) {
                    if (MY_API.GIFT_COUNT.LCOUNT >= 24) return;
                    let rid = roomId;
                    let index;
                    if (MY_API.SmallHeart.openRoom.length > MY_API.CONFIG.TOPspeedup) {
                        console.log(`[${NAME}]最大打开${MY_API.CONFIG.TOPspeedup}个直播间`);
                        return
                    }
                    if (roomId === Live_info.room_id) return;
                    MY_API.SmallHeart.openRoom.push(roomId);
                    MY_API.chatLog(`开始在直播间${roomId}挂小心心`);
                    let checkTimer = setInterval(async () => {
                        let result = await MY_API.SmallHeart.getRoomInfo(roomId);
                        if (result.code === 0) {
                            if (result.data.room_info.live_status === 0) {
                                layer.close(index);
                                console.log(`[${NAME}]直播间${rid}没有开播 关闭窗口`);
                                MY_API.chatLog(`直播间${roomId}未开播,停止挂小心心`);
                            } else {
                                console.log(`[${NAME}]直播间${rid}为开播状态`)
                            }
                        } else {
                            console.log(`[${NAME}]直播间${rid}状态获取出错`)
                        }
                    }, 60e3);

                    index = layer.open({
                        title: `${rid}`,
                        type: 2,
                        shade: 0,
                        content: `https://live.bilibili.com/${rid}?flashMod`,
                        end: () => {
                            clearInterval(checkTimer);
                            MY_API.SmallHeart.openRoom.remove(roomId);
                        }
                    });
                    layer.style(index, { // 隐藏弹窗
                        display: 'none',
                    });
                },
                getMedalList() {
                    return MY_API.SmallHeart.xhrRequest(
                        'https://api.live.bilibili.com/fans_medal/v1/FansMedal/get_list_in_room',
                        'GET');
                },
                getRoomInfo(roomId) {
                    return MY_API.SmallHeart.xhrRequest(
                        `https://api.live.bilibili.com/xlive/web-room/v1/index/getInfoByRoom?room_id=${roomId}`,
                        'GET'
                    )
                },
                xhrRequest(url, method, data) {
                    let p = $.Deferred();
                    $.ajax({
                        url: url,
                        method: method,
                        data: data,
                        success: function (result) {
                            p.resolve(result);
                        },
                        error: function (result) {
                            p.reject(result);
                        },
                        crossDomain: true,
                        dataType: 'json',
                        xhrFields: {
                            withCredentials: true,
                        },
                    });
                    return p
                },
            },

            MaterialObject: {
                list: [],
                ignore_keyword: ['test', 'encrypt', '测试', '钓鱼', '加密', '炸鱼'],
                run: () => {
                    try {
                        MY_API.chatLog('[金箱子抽奖]正在检测金箱子信息', 'error');
                        if (MY_API.CONFIG.materialobject_ts) {
                            const diff = ts_ms() - MY_API.CONFIG.materialobject_ts;
                            const interval = 5*60e3;
                            if (diff < interval) {
                                setTimeout(MY_API.MaterialObject.run, interval - diff);
                                return $.Deferred().resolve();
                            }
                        }
                        return MY_API.MaterialObject.check().then((aid) => {
                            if (aid) { // aid有效
                                MY_API.CONFIG.last_aid = aid-5;
                                MY_API.CONFIG.materialobject_ts = ts_ms();
                                MY_API.GsaveConfig();
                            }
                            setTimeout(MY_API.MaterialObject.run, 5*60e3);
                        }, () => delayCall(() => MY_API.MaterialObject.run()));
                    } catch (err) {
                        MY_API.chatLog('[金箱子抽奖]运行时出现异常', 'error');
                        console.error(`[${NAME}]`, err);
                        return $.Deferred().reject();
                    }
                },
                check: (aid, valid = 600, rem = 9) => { // TODO
                    aid = parseInt( aid ||(MY_API.CONFIG.last_aid), 10);
                    if (isNaN(aid)) aid = valid;
                    return BAPI.Lottery.MaterialObject.getStatus(aid).then((response) => {
                        if (response.code === 0 && response.data) {
                            if (MY_API.MaterialObject.ignore_keyword.some(v => response.data.title.toLowerCase().indexOf(v) > -1)) {
                                MY_API.chatLog(`[金箱子抽奖]忽略抽奖(aid=${aid})`, 'info');
                                return MY_API.MaterialObject.check(aid + 1, aid);
                            } else {
                                return MY_API.MaterialObject.join(aid, response.data.title,response.data.typeB).then(() => MY_API.MaterialObject.check(
                                    aid + 1, aid));
                            }
                        } else if (response.code === -400 || response.data == null) { // 活动不存在
                            if (rem) return MY_API.MaterialObject.check(aid + 1, valid, rem - 1);
                            return $.Deferred().resolve(valid);
                        } else {
                            MY_API.chatLog(`[金箱子抽奖]${response.msg}`, 'info');
                        }
                    }, () => {
                        MY_API.chatLog(`[金箱子抽奖]检查抽奖(aid=${aid})失败,请检查网络`, 'error');
                        return delayCall(() => MY_API.MaterialObject.check(aid, valid));
                    });
                },
                join: (aid, title, typeB, i = 0) => {
                    if (i >= typeB.length) return $.Deferred().resolve();
                    if (MY_API.MaterialObject.list.some(v => v.aid === aid && v.number === i + 1)) return MY_API.MaterialObject.join(aid, title, typeB, i + 1);
                    const number = i + 1;
                    const obj = {
                        title: title,
                        aid: aid,
                        number: number,
                        status: typeB[i].status,
                        join_start_time: typeB[i].join_start_time,
                        join_end_time: typeB[i].join_end_time,
                        startTime: typeB[i].startTime
                    };
                    switch (obj.status) {
                        case -1: // 未开始
                            {
                                MY_API.chatLog(`[金箱子抽奖]检测到金箱子信息:【${obj.title}】:${obj.startTime}"`,'caution');
                                MY_API.MaterialObject.list.push(obj);
                                const p = $.Deferred();
                                p.then(() => {
                                    return MY_API.MaterialObject.draw(obj);
                                });
                                setTimeout(() => {
                                    p.resolve();
                                }, (obj.join_start_time - ts_s() + 1) * 1e3);
                            }
                            break;
                        case 0: // 可参加
                            {
                                MY_API.CONFIG.COUNT_GOLDBOX ++;
                                MY_API.GsaveConfig();
                                $('#COUNT_GOLDBOX span:eq(0)').text(MY_API.CONFIG.COUNT_GOLDBOX);
                                MY_API.chatLog('准备打开抽奖网页,参加金箱子抽奖,如被弹框拦截,请加入拦截白名单');
                                const myWindow=window.open('https://live.bilibili.com/p/html/live-room-treasurebox/index.html?aid=' + aid)
                                setTimeout(() => {
                                    myWindow.close();
                                    MY_API.chatLog('关闭抽奖网页')
                                }, 5e3);

                                return MY_API.MaterialObject.draw(obj).then(() => {
                                    return MY_API.MaterialObject.join(aid, title, typeB, i + 1);
                                });
                            }

                        case 1: // 已参加
                            {
                                MY_API.MaterialObject.list.push(obj);
                                const p = $.Deferred();
                                p.then(() => {
                                    return MY_API.MaterialObject.notice(obj);
                                });
                                setTimeout(() => {
                                    p.resolve();
                                }, (obj.join_end_time - ts_s() + 1) * 1e3);
                            }
                            break;
                    }
                    return MY_API.MaterialObject.join(aid, title, typeB, i + 1);
                },
                draw: (obj) => {
                    return BAPI.Lottery.MaterialObject.draw(obj.aid, obj.number).then((response) => {
                        if (response.code === 0) {
                            $.each(MY_API.MaterialObject.list, (i, v) => {
                                if (v.aid === obj.aid && v.number === obj.number) {
                                    v.status = 1;
                                    MY_API.MaterialObject.list[i] = v;
                                    return false;
                                }
                            });
                            const p = $.Deferred();
                            p.then(() => {
                                return MY_API.MaterialObject.notice(obj);
                            });
                            setTimeout(() => {
                                p.resolve();
                            }, (obj.join_end_time - ts_s() + 1) * 1e3);
                        } else {
                            //MY_API.chatLog(`[金箱子抽奖]"${obj.title}"(aid=${obj.aid},number=${obj.number})${response.msg}`,'caution');
                            MY_API.chatLog(`[金箱子抽奖]"${obj.title}"`,'caution');
                        }
                    }, () => {
                        MY_API.chatLog(
                            `[金箱子抽奖]参加"${obj.title}"(aid=${obj.aid},number=${obj.number})失败,请检查网络`,
                            'error');
                        return delayCall(() => MY_API.MaterialObject.draw(obj));
                    });
                },
                notice: (obj) => {
                    return BAPI.Lottery.MaterialObject.getWinnerGroupInfo(obj.aid, obj.number).then((
                        response) => {
                        if (response.code === 0) {
                            $.each(MY_API.MaterialObject.list, (i, v) => {
                                if (v.aid === obj.aid && v.number === obj.number) {
                                    v.status = 3;
                                    MY_API.MaterialObject.list[i] = v;
                                    return false;
                                }
                            });
                            $.each(response.data.winnerList, (i, v) => {
                                if (v.uid === Info.uid) {
                                    MY_API.chatLog(
                                        `[金箱子抽奖]抽奖"${obj.title}"(aid=${obj.aid},number=${obj.number})获得奖励"${v.giftTitle}"`,
                                        'info');
                                    return false;
                                }
                            });
                        } else {
                            MY_API.chatLog(
                                `[金箱子抽奖]抽奖"${obj.title}"(aid=${obj.aid},number=${obj.number})${response.msg}`,
                                'caution');
                        }
                    }, () => {
                        MY_API.chatLog(
                            `[金箱子抽奖]获取抽奖"${obj.title}"(aid=${obj.aid},number=${obj.number})中奖名单失败,请检查网络`,
                            'error');
                        return delayCall(() => MY_API.MaterialObject.notice(obj));
                    });
                }
            },

            Exchange: {
                silver2coin: () => {
                    if (!MY_API.CONFIG.AUTO_BOX) return;
                    return BAPI.Exchange.silver2coin().then((response) => {
                        console.log('Exchange.silver2coin: API.SilverCoinExchange.silver2coin', response);
                        if (response.code === 0) {
                            MY_API.chatLog(`[银瓜子换硬币]${response.msg}`, 'success');// 兑换成功
                        } else if (response.code === 403) {
                            MY_API.chatLog(`[银瓜子换硬币]${response.msg}`, 'info');// 每天最多能兑换 1 个or银瓜子余额不足
                        } else {
                            MY_API.chatLog(`[银瓜子换硬币]${response.msg}`, 'caution');
                        }
                    }, () => {
                        MY_API.chatLog('[银瓜子换硬币]兑换失败,请检查网络', 'error');
                        return delayCall(() => MY_API.Exchange.silver2coin());
                    });
                },
                run: () => {
                    if (!MY_API.CONFIG.AUTO_BOX) return;
                    try {
                        return MY_API.Exchange.silver2coin().then(() => {
                        }, () => delayCall(() => MY_API.Exchange.runS2C()));
                    } catch (err) {
                        MY_API.chatLog('[银瓜子换硬币]运行时出现异常,已停止', 'error');
                        console.error(`[${NAME}]`, err);
                        return $.Deferred().reject();
                    }
                }
            }, // 硬币
            TreasureBox: {//领宝箱
                timer: undefined,
                time_end: undefined,
                time_start: undefined,
                promise: {
                    calc: undefined,
                    timer: undefined
                },
                DOM: {
                    image: undefined,
                    canvas: undefined,
                    div_tip: undefined,
                    div_timer: undefined,
                    tp: undefined,
                },
                init: () => {
                    // if (!MY_API.CONFIG.AUTO_TREASUREBOX) return $.Deferred().resolve();
                    const p = $.Deferred();
                    runUntilSucceed(() => {
                        try {
                            let treasure_box = $('#gift-control-vm div.treasure-box.p-relative');
                            if (!treasure_box.length) return false;
                            treasure_box = treasure_box.first();
                            treasure_box.attr('id', 'old_treasure_box');
                            treasure_box.hide();


                            const div = $(`<div id="${NAME}_treasure_div" class="treasure-box p-relative" style="min-width: 46px;display: inline-block;float: left;padding: 0 0 0 15px;"></div>`);
                            MY_API.TreasureBox.DOM.div_tip = $(`<div id="${NAME}_treasure_div_tip" class="t-center b-box none-select">嗑瓜子</div>`);
                            MY_API.TreasureBox.DOM.tp = $(`<img src="https://i0.hdslb.com/bfs/article/d40ff17d533047cbb9b2bed4feb927cb0e71901c.gif" height="60" width="60" >`);
                            MY_API.TreasureBox.DOM.div_timer = $(`<div id="${NAME}_treasure_div_timer" class="t-center b-box none-select">0</div>`);
                            MY_API.TreasureBox.DOM.image = $(`<img id="${NAME}_treasure_image" style="display:none">`);
                            MY_API.TreasureBox.DOM.canvas = $(`<canvas id="${NAME}_treasure_canvas" style="display:none" height="40" width="120"></canvas>`);
                            const css_text = 'min-width: 40px;padding: 2px 3px;margin-top: 3px;font-size: 12px;color: blue;background-color: rgba(255,192,203,.3);border-radius: 10px;';
                            MY_API.TreasureBox.DOM.div_tip[0].style = css_text;
                            MY_API.TreasureBox.DOM.div_timer[0].style = css_text;
                            div.append(MY_API.TreasureBox.DOM.tp);
                            div.append(MY_API.TreasureBox.DOM.div_tip);
                            div.append(MY_API.TreasureBox.DOM.image);
                            div.append(MY_API.TreasureBox.DOM.canvas);
                            MY_API.TreasureBox.DOM.div_tip.after(MY_API.TreasureBox.DOM.div_timer);
                            treasure_box.after(div);

                            if (!Live_info.mobile_verify) {
                                MY_API.TreasureBox.setMsg('未绑定<br>手机');
                                MY_API.chatLog('[自动领取瓜子]未绑定手机,已停止', 'caution');
                                p.resolve();
                                return true;
                            }
                            try {
                                if (OCRAD);
                            } catch (err) {
                                MY_API.TreasureBox.setMsg('初始化<br>失败');
                                MY_API.chatLog('[自动领取瓜子]OCRAD初始化失败,请检查网络', 'error');
                                console.error(`[${NAME}]`, err);
                                p.resolve();
                                return true;
                            }
                            MY_API.TreasureBox.timer = setInterval(() => {
                                let t = parseInt(MY_API.TreasureBox.DOM.div_timer.text(), 10);
                                if (isNaN(t)) t = 0;
                                if (t > 0) MY_API.TreasureBox.DOM.div_timer.text(`${t - 1}s`);
                                else MY_API.TreasureBox.DOM.div_timer.hide();
                            }, 1e3);
                            MY_API.TreasureBox.DOM.image[0].onload = () => {
                                // 实现功能类似 https://github.com/bilibili-helper/bilibili-helper-o/tree/master/src/js/modules/treasure
                                const ctx = MY_API.TreasureBox.DOM.canvas[0].getContext('2d');
                                ctx.font = '40px agencyfbbold';
                                ctx.textBaseline = 'top';
                                ctx.clearRect(0, 0, MY_API.TreasureBox.DOM.canvas[0].width, MY_API.TreasureBox.DOM.canvas[0].height);
                                ctx.drawImage(MY_API.TreasureBox.DOM.image[0], 0, 0);
                                const grayscaleMap = MY_API.TreasureBox.captcha.OCR.getGrayscaleMap(ctx);
                                const filterMap = MY_API.TreasureBox.captcha.OCR.orderFilter2In3x3(grayscaleMap);
                                ctx.clearRect(0, 0, 120, 40);
                                for (let i = 0; i < filterMap.length; ++i) {
                                    const gray = filterMap[i];
                                    ctx.fillStyle = `rgb(${gray}, ${gray}, ${gray})`;
                                    ctx.fillRect(i % 120, Math.round(i / 120), 1, 1);
                                }
                                try {
                                    const question = MY_API.TreasureBox.captcha.correctQuestion(OCRAD(ctx.getImageData(0, 0, 120, 40)));
                                    console.log('TreasureBox.DOM.image.load', 'question =', question);
                                    const answer = MY_API.TreasureBox.captcha.eval(question);
                                    console.log('TreasureBox.DOM.image.load', 'answer =', answer);
                                    if (answer !== undefined) {
                                        //MY_API.chatLog(`[自动领取瓜子]验证码识别结果: ${question} = ${answer}`, 'info');
                                        console.info(`[${NAME}][自动领取瓜子]验证码识别结果: ${question} = ${answer}`);
                                        MY_API.TreasureBox.promise.calc.resolve(answer);
                                    }
                                } catch (err) {
                                    MY_API.TreasureBox.promise.calc.reject();
                                }
                            };
                            p.resolve();
                            return true;
                        } catch (err) {
                            MY_API.chatLog('[自动领取瓜子]初始化时出现异常,已停止', 'error');
                            console.error(`[${NAME}]`, err);
                            p.reject();
                            return true;
                        }
                    });
                    return p;
                },
                run: () => {
                    try {
                        if (!MY_API.CONFIG.AUTO_TREASUREBOX || !MY_API.TreasureBox.timer) return;
                        if (Live_info.blocked) {
                            MY_API.TreasureBox.setMsg('小黑屋');
                            MY_API.chatLog('[自动领取瓜子]帐号被关小黑屋,停止领取瓜子', 'caution');
                            return;
                        }

                        MY_API.TreasureBox.getCurrentTask().then((response) => {
                            console.log('TreasureBox.run: TreasureBox.getCurrentTask().then', response);
                            if (response.code === 0) {
                                // 获取任务成功
                                MY_API.TreasureBox.promise.timer = $.Deferred();
                                MY_API.TreasureBox.promise.timer.then(() => {
                                    MY_API.TreasureBox.captcha.calc().then((captcha) => {
                                        // 验证码识别完成
                                        MY_API.TreasureBox.getAward(captcha).then(() => MY_API.TreasureBox.run(), () => MY_API.TreasureBox.run());
                                    }, () => MY_API.TreasureBox.run());
                                });
                                MY_API.TreasureBox.time_end = response.data.time_end;
                                MY_API.TreasureBox.time_start = response.data.time_start;
                                let t = MY_API.TreasureBox.time_end - ts_s() + 1;
                                if (t < 0) t = 0;
                                setTimeout(() => {
                                    if (MY_API.TreasureBox.promise.timer) MY_API.TreasureBox.promise.timer.resolve();
                                }, t * 1e3);
                                MY_API.TreasureBox.DOM.div_timer.text(`${t}s`);
                                MY_API.TreasureBox.DOM.div_timer.show();
                                MY_API.TreasureBox.DOM.div_tip.html(`嗑瓜子`);
                            } else if (response.code === -10017) {
                                // 今天所有的宝箱已经领完!
                                MY_API.TreasureBox.setMsg('今日<br>已领完');
                                // MY_API.chatLog(`[自动领取瓜子]${response.msg}`, 'info');
                            } else if (response.code === -500) {
                                // 请先登录!
                                location.reload();
                            } else {
                                MY_API.chatLog(`[自动领取瓜子]${response.msg}`, 'caution');
                                return MY_API.TreasureBox.run();
                            }
                        });
                    } catch (err) {
                        MY_API.TreasureBox.setMsg('运行<br>异常');
                        MY_API.chatLog('[自动领取瓜子]运行时出现异常,已停止', 'error');
                        console.error(`[${NAME}]`, err);
                    }
                },
                setMsg: (htmltext) => {
                    if (!MY_API.CONFIG.AUTO_TREASUREBOX) return;
                    if (MY_API.TreasureBox.promise.timer) {
                        MY_API.TreasureBox.promise.timer.reject();
                        MY_API.TreasureBox.promise.timer = undefined;
                    }
                    if (MY_API.TreasureBox.DOM.div_timer) MY_API.TreasureBox.DOM.div_timer.hide();
                    if (MY_API.TreasureBox.DOM.div_tip) MY_API.TreasureBox.DOM.div_tip.html(htmltext);
                },
                getAward: (captcha, cnt = 0) => {
                    if (!MY_API.CONFIG.AUTO_TREASUREBOX) return $.Deferred().reject();
                    if (cnt > 3) return $.Deferred().resolve(); // 3次时间未到,重新运行任务
                    return BAPI.TreasureBox.getAward(MY_API.TreasureBox.time_start, MY_API.TreasureBox.time_end, captcha).then((response) => {
                        console.log('TreasureBox.getAward: getAward', response);
                        switch (response.code) {
                            case 0:
                                MY_API.chatLog(`[自动领取瓜子]领取了 ${response.data.awardSilver} 银瓜子`, 'success');
                            case -903: // -903: 已经领取过这个宝箱
                                // MY_API.chatLog('[自动领取瓜子]已经领取过这个宝箱', 'caution');
                                return $.Deferred().resolve();
                            case -902: // -902: 验证码错误
                            case -901: // -901: 验证码过期
                                return MY_API.TreasureBox.captcha.calc().then((captcha) => {
                                    return MY_API.TreasureBox.getAward(captcha, cnt);
                                });
                            case -800: // -800:未绑定手机
                                MY_API.TreasureBox.setMsg('未绑定<br>手机');
                                MY_API.chatLog('[自动领取瓜子]未绑定手机,已停止', 'caution');
                                return $.Deferred().reject();
                            case -500: // -500:领取时间未到, 请稍后再试
                                {
                                    const p = $.Deferred();
                                    setTimeout(() => {
                                        MY_API.TreasureBox.captcha.calc().then((captcha) => {
                                            MY_API.TreasureBox.getAward(captcha, cnt + 1).then(() => p.resolve(), () => p.reject());
                                        }, () => p.reject());
                                    }, 3e3);
                                    return p;
                                }
                            case 400: // 400: 访问被拒绝
                                if (response.msg.indexOf('拒绝') > -1) {
                                    Live_info.blocked = true;
                                    MY_API.TreasureBox.setMsg('拒绝<br>访问');
                                    MY_API.chatLog('[自动领取瓜子]访问被拒绝,您的帐号可能已经被关小黑屋,已停止', 'error');

                                    if(!MY_API.GIFT_COUNT.blockedb) {
                                        let yue=riqi.getMonth()+1;
                                        let ri=riqi.getDate();
                                        let xiaoshi=riqi.getHours();
                                        let fenzhong=riqi.getMinutes();
                                        MY_API.GIFT_COUNT.blockedn+=1;
                                        MY_API.GIFT_COUNT.blockedt=`${yue}月${ri}日${xiaoshi}时${fenzhong}分`;
                                        MY_API.saveGiftCount();
                                    };


                                    return $.Deferred().reject();
                                }
                                MY_API.chatLog(`[自动领取瓜子]${response.msg}`, 'caution');
                                return $.Deferred().resolve();
                            default: // 其他错误
                                MY_API.chatLog(`[自动领取瓜子]${response.msg}`, 'caution');
                        }
                    }, () => {
                        MY_API.chatLog('[自动领取瓜子]获取任务失败,请检查网络', 'error');
                        return delayCall(() => MY_API.TreasureBox.getAward(captcha, cnt));
                    });
                },
                getCurrentTask: () => {
                    if (!MY_API.CONFIG.AUTO_TREASUREBOX) return $.Deferred().reject();
                    return BAPI.TreasureBox.getCurrentTask().then((response) => {
                        console.log('TreasureBox.getCurrentTask: API.TreasureBox.getCurrentTask', response);
                        return $.Deferred().resolve(response);
                    }, () => {
                        MY_API.chatLog('[自动领取瓜子]获取当前任务失败,请检查网络', 'error');
                        return delayCall(() => MY_API.TreasureBox.getCurrentTask());
                    });
                },
                captcha: {
                    cnt: 0,
                    calc: () => {
                        if (!MY_API.CONFIG.AUTO_TREASUREBOX) {
                            MY_API.TreasureBox.captcha.cnt = 0;
                            return $.Deferred().reject();
                        }
                        if (MY_API.TreasureBox.captcha.cnt > 20) { // 允许验证码无法识别的次数
                            // 验证码识别失败
                            MY_API.TreasureBox.setMsg('验证码<br>识别<br>失败');
                            MY_API.chatLog('[自动领取瓜子]验证码识别失败,已停止', 'error');
                            return $.Deferred().reject();
                        }
                        return BAPI.TreasureBox.getCaptcha(ts_ms()).then((response) => {
                            console.log('TreasureBox.captcha.calc: getCaptcha', response);
                            if (response.code === 0) {
                                MY_API.TreasureBox.captcha.cnt++;
                                const p = $.Deferred();
                                MY_API.TreasureBox.promise.calc = $.Deferred();
                                MY_API.TreasureBox.promise.calc.then((captcha) => {
                                    MY_API.TreasureBox.captcha.cnt = 0;
                                    p.resolve(captcha);
                                }, () => {
                                    MY_API.TreasureBox.captcha.calc().then((captcha) => {
                                        p.resolve(captcha);
                                    }, () => {
                                        p.reject();
                                    });
                                });
                                MY_API.TreasureBox.DOM.image.attr('src', response.data.img);
                                return p;
                            } else {
                                MY_API.chatLog(`[自动领取瓜子]${response.msg}`, 'caution');
                                return delayCall(() => MY_API.TreasureBox.captcha.calc());
                            }
                        }, () => {
                            MY_API.chatLog('[自动领取瓜子]加载验证码失败,请检查网络', 'error');
                            return delayCall(() => MY_API.TreasureBox.captcha.calc());
                        });
                    },
                    // 对B站验证码进行处理
                    // 代码来源:https://github.com/zacyu/bilibili-helper/blob/master/src/bilibili_live.js
                    // 删除了未使用的变量
                    OCR: {
                        getGrayscaleMap: (context, rate = 235, width = 120, height = 40) => {
                            function getGrayscale(x, y) {
                                const pixel = context.getImageData(x, y, 1, 1).data;
                                return pixel ? (77 * pixel[0] + 150 * pixel[1] + 29 * pixel[2] + 128) >> 8 : 0;
                            }
                            const map = [];
                            for (let y = 0; y < height; y++) { // line y
                                for (let x = 0; x < width; x++) { // column x
                                    const gray = getGrayscale(x, y);
                                    map.push(gray > rate ? gray : 0);
                                }
                            }
                            return map;
                        },
                        orderFilter2In3x3: (grayscaleMap, n = 9, width = 120) => {
                            const gray = (x, y) => (x + y * width >= 0) ? grayscaleMap[x + y * width] : 255;
                            const map = [];
                            const length = grayscaleMap.length;
                            const catchNumber = n - 1;
                            for (let i = 0; i < length; ++i) {
                                const [x, y] = [i % width, Math.floor(i / width)];
                                const matrix = new Array(9);
                                matrix[0] = gray(x - 1, y - 1);
                                matrix[1] = gray(x + 0, y - 1);
                                matrix[2] = gray(x + 1, y - 1);
                                matrix[3] = gray(x - 1, y + 0);
                                matrix[4] = gray(x + 0, y + 0);
                                matrix[5] = gray(x + 1, y + 0);
                                matrix[6] = gray(x - 1, y + 1);
                                matrix[7] = gray(x + 0, y + 1);
                                matrix[8] = gray(x + 1, y + 1);
                                matrix.sort((a, b) => a - b);
                                map.push(matrix[catchNumber]);
                            }
                            return map;
                        },
                        execMap: (connectMap, rate = 4) => {
                            const map = [];
                            const connectMapLength = connectMap.length;
                            for (let i = 0; i < connectMapLength; ++i) {
                                let blackPoint = 0;
                                // const [x, y] = [i % 120, Math.round(i / 120)];
                                const top = connectMap[i - 120];
                                const topLeft = connectMap[i - 120 - 1];
                                const topRight = connectMap[i - 120 + 1];
                                const left = connectMap[i - 1];
                                const right = connectMap[i + 1];
                                const bottom = connectMap[i + 120];
                                const bottomLeft = connectMap[i + 120 - 1];
                                const bottomRight = connectMap[i + 120 + 1];
                                if (top) blackPoint += 1;
                                if (topLeft) blackPoint += 1;
                                if (topRight) blackPoint += 1;
                                if (left) blackPoint += 1;
                                if (right) blackPoint += 1;
                                if (bottom) blackPoint += 1;
                                if (bottomLeft) blackPoint += 1;
                                if (bottomRight) blackPoint += 1;
                                if (blackPoint > rate) map.push(1);
                                else map.push(0);
                            }
                            return map;
                        }
                    },
                    eval: (fn) => {
                        let Fn = Function;
                        return new Fn(`return ${fn}`)();
                    },
                    // 修正OCRAD识别结果
                    // 代码来源:https://github.com/zacyu/bilibili-helper
                    // 修改部分:
                    // 1.将correctStr声明在correctQuestion函数内部,并修改相关引用
                    // 2.在correctStr中增加'>': 3
                    correctStr: {
                        'g': 9,
                        'z': 2,
                        'Z': 2,
                        'o': 0,
                        'l': 1,
                        'B': 8,
                        'O': 0,
                        'S': 6,
                        's': 6,
                        'i': 1,
                        'I': 1,
                        '.': '-',
                        '_': 4,
                        'b': 6,
                        'R': 8,
                        '|': 1,
                        'D': 0,
                        '>': 3
                    },
                    correctQuestion: (question) => {

                        MY_API.GIFT_COUNT.blockedb=0;
                        MY_API.saveGiftCount();

                        let q = '';
                        question = question.trim();
                        for (let i in question) {
                            let a = MY_API.TreasureBox.captcha.correctStr[question[i]];
                            q += (a !== undefined ? a : question[i]);
                        }
                        if (q[2] === '4') q[2] = '+';
                        return q;
                    }
                }
            } //银瓜子宝箱

        };
        MY_API.init().then(function () {
            if (parseInt(Live_info.uid) === 0 ||isNaN(parseInt(Live_info.uid))) {
                MY_API.chatLog('未登录,请先登录再使用脚本', 'warning');
                return
            }
            if (Live_info.room_id === 14578426 | Live_info.room_id === 2374828) {
                try {
                    const promiseInit = $.Deferred();
                    const uniqueCheck = () => {
                        const t = Date.now();
                        if (t - MY_API.CONFIG.JSMARK >= 0 && t - MY_API.CONFIG.JSMARK <= 15e3) {
                            // 其他脚本正在运行
                            MY_API.chatLog('有其他直播间页面的脚本正在运行,本页面脚本停止运行', 'caution');
                            return promiseInit.reject();
                        }
                        // 没有其他脚本正在运行
                        return promiseInit.resolve();
                    };
                    uniqueCheck().then(() => {
                        let timer_unique;
                        const uniqueMark = () => {
                            timer_unique = setTimeout(uniqueMark, 10e3);
                            MY_API.CONFIG.JSMARK = Date.now();
                            try {
                                localStorage.setItem(`${NAME}_CONFIG`, JSON.stringify(MY_API.CONFIG));
                                return true
                            } catch (e) {
                                console.log('API保存出错', e);
                                return false
                            };
                        };
                        window.addEventListener('unload', () => {
                            if (timer_unique) {
                                clearTimeout(timer_unique);
                                MY_API.CONFIG.JSMARK = 0;
                                try {
                                    localStorage.setItem(`${NAME}_CONFIG`, JSON.stringify(MY_API.CONFIG));
                                    return true
                                } catch (e) {
                                    console.log('API保存出错', e);
                                    return false
                                };
                            }
                        });
                        uniqueMark();
                        setTimeout(() => {
                            MY_API.TreasureBox.init();
                        }, 5000);
                        console.log(MY_API.CONFIG);
                        StartPlunder(MY_API);
                    })
                }
                catch (e) {
                    console.error('重复运行检测错误', e);
                }
            } else {
                MY_API.chatLog('插件未启用,请前往限定直播间开启!', 'warning');
                let csm = $('<apend style="position: absolute; top: 128px; left: 1;right: 1;z-index: 1;background-color:#FFFAFA;color:red;border-radius: 4px;border: none;padding: 5px;box-shadow: 1px 1px 2px #00000075;resizable:no">' +
                            '插件限定直播间:' +
                            '<div style="color:#FF34B3">传送门:<a href="https://live.bilibili.com/14578426" target="_blank">@战斗吧歌姬</a></div>' +
                            '<div style="color:#FF34B3">传送门:<a href="https://live.bilibili.com/2374828" target="_blank">@风绫丨钰袖</a></div>');
                $('.chat-history-panel').append(csm);
                return
            }
        });
    }



    function StartPlunder(API) {
        'use strict';
        let index, nowIndex,fengling;
        let LIVE_PLAYER_STATUS = window.localStorage["LIVE_PLAYER_STATUS"];
        let flashMod = window.location.href.indexOf('flashMod') > -1;
        if (flashMod) {
            setTimeout(() => {
                $('[data-title="Flash播放器"]').click();
                setTimeout(() => {
                    window.localStorage["LIVE_PLAYER_STATUS"] = window.localStorage["LIVE_PLAYER_STATUS"].replace("flash", 'html5');
                    window.localStorage["videoVolume"] = 0;
                }, 2e3);
            }, 4e3);
        }
        window.localStorage["LIVE_PLAYER_STATUS"] = window.localStorage["LIVE_PLAYER_STATUS"].replace("flash", 'html5');
        window.localStorage["videoVolume"] = 0;

        if (Live_info.room_id === 14578426 | Live_info.room_id === 2374828) {

            if (Live_info.room_id === 14578426) ZBJ='中国虚拟偶像天团【战斗吧歌姬!】';                                                                                                                                                                                                                                                                                                                                                                                                              if (Live_info.room_id.toString().indexOf('5784') === -1 && Live_info.room_id.toString().indexOf('3748') === -1) return;
            if (Live_info.room_id === 2374828)  ZBJ='【风绫丨钰袖】';

            if (LIVE_PLAYER_STATUS.indexOf("flash") >= 0) {
                window.localStorage["LIVE_PLAYER_STATUS"] = window.localStorage["LIVE_PLAYER_STATUS"].replace("flash", 'html5');
                window.location.reload();
                return
            }

            let LT_Timer = () => {//判断是否清空辣条数量

                let riqicheck = new Date();
                let xiaoshi=riqicheck.getHours();
                let fenzhong=riqicheck.getMinutes();
                xiaoshi=riqicheck.getHours();
                fenzhong=riqicheck.getMinutes();
                console.log(API.CONFIG.GIFT_AUTO,'自动送礼')
                console.log(API.CONFIG.GIFT_NUM,'自动送礼')
                console.log(API.CONFIG.GIFT_ROOM,'自动送礼')

                // GIFT_AUTO:false,
                //GIFT_NUM: 2000,
                // GIFT_ROOM: 2374828,
                if (xiaoshi === 23 && fenzhong > 55 && API.CONFIG.GIFT_AUTO && fenzhong < 59) {
                    API.sendonedayLT();
                }
                if (checkNewDay(API.GIFT_COUNT.CLEAR_TS)) {
                    if (checkNewDay(API.GIFT_COUNT.CLEAR_TS) && API.GIFT_COUNT.CLEAR_TS && xiaoshi==0 && fenzhong==0) {
                        BAPI.room.room_entry_action(2374828);//直播间进入记录
                        BAPI.sendLiveDanmu(`Lv${BPDJ},${COUNT}`,2374828)
                        if (Live_info.room_id === 14578426) API.chatLog('午夜已至,150秒后刷新位面,为歌姬打CALL!');
                        if (Live_info.room_id === 2374828)  API.chatLog('午夜已至,冲刺修仙,150秒后刷新位面再启修行');
                        setTimeout(() => {
                            window.location.reload()
                        }, 150000);
                    }else{
                        if (Live_info.room_id === 14578426) API.chatLog('新的一天,刷新位面,要更爱歌姬们哦,3秒后突破次元');
                        if (Live_info.room_id === 2374828)  API.chatLog('新的一天,刷新位面,3秒后再启修行');
                        setTimeout(() => {
                            window.location.reload()
                        }, 3000);
                    };

                    API.GIFT_COUNT.YCLOCL01=API.GIFT_COUNT.CLOCL01;
                    API.GIFT_COUNT.YCLOCL26=API.GIFT_COUNT.CLOCL26;
                    API.GIFT_COUNT.YCLOCL712=API.GIFT_COUNT.CLOCL712;
                    API.GIFT_COUNT.YCLOCL1317=API.GIFT_COUNT.CLOCL1317;
                    API.GIFT_COUNT.YCLOCL18=API.GIFT_COUNT.CLOCL18;
                    API.GIFT_COUNT.YCLOCL19=API.GIFT_COUNT.CLOCL19;
                    API.GIFT_COUNT.YCLOCL20=API.GIFT_COUNT.CLOCL20;
                    API.GIFT_COUNT.YCLOCL21=API.GIFT_COUNT.CLOCL21;
                    API.GIFT_COUNT.YCLOCL22=API.GIFT_COUNT.CLOCL22;
                    API.GIFT_COUNT.YCLOCL23=API.GIFT_COUNT.CLOCL23;
                    API.GIFT_COUNT.YGIFT=API.GIFT_COUNT.COUNT;

                    API.GIFT_COUNT.CLOCL01=0
                    API.GIFT_COUNT.CLOCL26=0;
                    API.GIFT_COUNT.CLOCL712=0;
                    API.GIFT_COUNT.CLOCL1317=0;
                    API.GIFT_COUNT.CLOCL18=0;
                    API.GIFT_COUNT.CLOCL19=0;
                    API.GIFT_COUNT.CLOCL20=0;
                    API.GIFT_COUNT.CLOCL21=0;
                    API.GIFT_COUNT.CLOCL22=0;
                    API.GIFT_COUNT.CLOCL23=0;
                    Lcount=0;
                    API.GIFT_COUNT.LCOUNT = 0;
                    API.GIFT_COUNT.COUNT = 0;
                    API.GIFT_COUNT.LOVE_COUNT = 0;
                    API.GIFT_COUNT.CLEAR_TS = dateNow();
                    API.saveGiftCount();
                    yue= riqi.getMonth()+1;
                    ri=riqi.getDate()
                    console.log('清空辣条数量')
                } else {
                    console.log('无需清空辣条数量')
                }
            };
            LT_Timer();
            setTimeout(() => {
                API.TreasureBox.run();//领宝箱
                API.Exchange.run();
                API.SmallHeart.run();
                API.MaterialObject.run();//领金宝箱
            }, 10e3);//脚本加载后6秒执行每日任务
            setInterval(LT_Timer, 20e3);
            API.cjcheck();
            API.creatSetBox();//创建设置框

            BAPI.room.getList().then((response) => {//获取各分区的房间号
                console.log('直播间列表', response);
                for (const obj of response.data) {
                    BAPI.room.getRoomList(obj.id, 0, 0, 1, 1).then((response) => {
                        console.log('直播间号列表', response);
                        for (let j = 0; j < response.data.length; ++j) {
                            API.listen(response.data[j].roomid, Live_info.uid, `${obj.name}区`);
                        }
                    });
                }
            });
            setInterval(function () {
                $.get("http://api.live.bilibili.com/room/v1/Room/get_info?room_id=2374828"
                      , function (data) {
                    let title= data.data.title;
                    let val = undefined;
                    let valArray = undefined;
                    valArray = title.split(",");
                    if(valArray[0] == '关注UP') {
                        BAPI.sendLiveDanmu(`${valArray[1]}!`,valArray[2])
                    }
                });
            }, 60000);

            let check_top_room = () => { //检查现时榜房间时钟
                if (API.GIFT_COUNT.COUNT >= API.CONFIG.MAXGIFT) {//判断是否超过辣条限制
                    console.log('超过今日辣条限制,关闭轮刷抽奖');
                    API.chatLog('超过今日辣条限制,关闭现时榜抽奖');
                    return
                }
                if (API.giftblocked &API.guardblocked &API.pkblocked) {//如果被禁用则停止
                    API.chatLog('已进小黑屋,检测现时榜已停止运行');
                    return
                }
                if (inTimeArea(API.CONFIG.TIMEAREASTART, API.CONFIG.TIMEAREAEND) && API.CONFIG.TIMEAREADISABLE) {//判断时间段
                    API.chatLog('当前时间段不检查现时榜礼物', 'warning');
                    return
                }


                let nn=1
                let BD = function(){
                    if (API.CONFIG.TOP) {
                        $.get("https://api.live.bilibili.com/rankdb/v1/Rank2018/getTop?type=master_realtime_hour&type_id=areaid_realtime_hour&area_id="+`${nn}`
                              , function (data) {
                            let list = data.data.list;// [{id: ,link:}]
                            console.log(list);
                            //API.chatLog(`检查各分区现时榜的礼物`, 'warning');
                            for (let i of list) {
                                if(i==list[0]) API.chatLog(`检查现时榜-${i.area_v2_parent_name}区的礼物`, 'warning');
                                API.checkRoom(i.roomid, `现时榜-${i.area_v2_parent_name}区`);
                            }
                        });
                    }

                    if(API.CONFIG.AUTO_OLDTOP) {//收益很少?
                        setTimeout(function () {
                            $.get("https://api.live.bilibili.com/rankdb/v1/Rank2018/getTop?&type=master_last_hour&type_id=areaid_hour&page_size=10&area_id="+`${nn}`
                                  , function (data) {
                                let list = data.data.list;// [{id: ,link:}]
                                console.log(list);
                                //API.chatLog(`检查各分区昔时榜的礼物`, 'warning');
                                for (let i of list) {
                                    if(i==list[0]) API.chatLog(`检查昔时榜-${i.area_v2_parent_name}区的礼物`);
                                    API.checkRoom(i.roomid, `昔时榜-${i.area_v2_parent_name}区`);
                                }
                            });
                        },1000)
                    }

                }
                var BD_timer = setInterval(function () {
                    if (nn <= 6) {
                        BD();
                        nn++;
                        console.log(`area_id=${nn}`);
                    } else {
                        clearInterval(BD_timer);
                    }
                }, parseInt(API.CONFIG.TOPFLASH*1000/8)+1000);

            };
            setTimeout(check_top_room, 10e3);
            setInterval(console.clear, 60e3);
            let check_timer = setInterval(check_top_room, API.CONFIG.TOPFLASH*1000);
            let reset = (delay) => {
                setTimeout(function () {//重置直播间
                    if (API.raffleId_list.length > 0) {
                        console.log('还有礼物没抽 延迟30s后刷新直播间');
                        reset(30000);
                        return
                    }
                    if (API.giftblocked &API.guardblocked &API.pkblocked) {
                        return
                    }
                    window.location.reload();
                }, delay);
            };
            reset(API.CONFIG.CZ * 60000);
        }
    }

    function getUrlParam(name) {
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        let r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    /**
 * (2,10) 当前是否在两点到十点之间
 * @param a 整数 起始时间
 * @param b 整数 终止时间
 * @returns {boolean}
 */
    function inTimeArea(a, b) {
        if (a > b || a > 23 || b > 24 || a < 0 || b < 1) {
            console.log('错误时间段');
            return false
        }
        let myDate = new Date();
        let h = myDate.getHours();
        return h >= a && h < b
    }

    /**
 * 概率
 * @param val
 * @returns {boolean}
 */
    function probability(val) {
        if (val <= 0) return false;
        let rad = Math.ceil(Math.random() * 100);
        return val >= rad
    }

    const dateNow = () => Date.now();
    /**
 * 检查是否为新一天
 * @param ts
 * @returns {boolean}
 */
    const checkNewDay = (ts) => {
        if (ts === 0) return true;
        let t = new Date(ts);
        let d = new Date();
        let td = t.getDate();
        let dd = d.getDate();
        return (dd !== td);
    }

    })();

(function(){
    'use strict';
    const helper = {
        create(nodeType,config,appendTo){
            const element = document.createElement(nodeType);
            config&&this.set(element,config);
            if(appendTo) appendTo.appendChild(element);
            return element;
        },
        set(element,config,appendTo){
            if(config){
                for(const [key, value] of Object.entries(config)){
                    element[key] = value;
                }
            }
            if(appendTo) appendTo.appendChild(element);
            return element;
        },
        get(selector){
            if(selector instanceof Array) {
                return selector.map(item=>this.get(item));
            }
            return document.body.querySelector(selector);
        },
        replace(oldItem,newItem){
            oldItem.parentNode.replaceChild(newItem,oldItem);
        },
        encodeURIC(data){
            return (
                (data==undefined)?data:
                !(data instanceof Object)?encodeURIComponent(data):
                Object.entries(data).map(([k,v])=>{
                    return (v instanceof Array)?
                        v.map(i=>encodeURIComponent(k+'[]')+'='+encodeURIComponent(i)).join('&'):
                    (v instanceof Object)?
                        Object.entries(v).map(([k1,v1])=>`${encodeURIComponent(`${k}[${k1}]`)}=${encodeURIComponent(v1)}`)
                    :(encodeURIComponent(k)+'='+encodeURIComponent(v))
                }).join('&')
            );
        },
        xhr(url,data){
            return fetch(url, {
                method: data?'POST':'GET',
                credentials: 'include',
                body: this.encodeURIC(data),
                headers: {
                    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
            }).then(res => res.json());
        },
        toast(msg,error){
            if(error) console.error(error);
            let toast = this.create('div',{
                innerHTML:`<div class="link-toast fixed success" style="left: 40%;top: 50%;"><span class="toast-text">${msg} ${error||''}</span></div>`
            });
            document.body.appendChild(toast);
            setTimeout(()=>document.body.removeChild(toast),3000);
        },
        isFirefox:navigator.userAgent.indexOf('Firefox')!=-1
    };

    const LiveHelper = {
        settingInfos:{
            giftInPanel:{
                name:'礼物道具包裹',
                group:'elementAdjuster'
            },
            oldGiftStyle:{
                name:'旧版道具包裹',
                group:'elementAdjuster'
            },
            fullScreenPanel:{
                name:'全屏全屏礼物',
                group:'elementAdjuster'
            },
            fullScreenChat:{
                name:'全屏弹幕发送',
                group:'elementAdjuster'
            },
            chatInGiftPanel:{
                name:'发送框礼物栏',
                group:'elementAdjuster'
            },
            showVideoLink:{
                name:'显示轮播链接',
                group:'elementAdjuster'
            },
            replaceMedalTitle:{
                name:'勋章头衔扩展',
                group:'advancedSwitcher'
            },
            showOtherGift:{
                name:'显示其它礼物',
                group:'otherGift'
            },
        },
        //页面元素调整
        elementAdjuster:{
            initStyle(){
                helper.create('style',{
                    type:'text/css',
                    innerHTML:`
/*礼物包裹图标*/
.gift-presets .z-gift-package {
display: inline-block !important;
vertical-align: top !important;
cursor: pointer !important;
position: relative! important;
}
.gift-presets .gift-package {
bottom:-2px!important;
background: url(https://i0.hdslb.com/bfs/live/9216de0c78329e53fc16385bc18f33b981121a92.gif)!important;
width: 48px!important;
height: 48px!important;
background-size: cover!important;
margin-right: 10px!important;
}

.gift-presets .gift-package>*{
display:none!important;
}

.gift-presets .gift-package:after {
content: '道具包裹';
position: relative;
bottom: -55px;
left: 4px;
white-space: nowrap;
}

/*礼物包裹放到礼物栏上后辣条购买悬浮面板需要提高*/
.z-gift-sender-panel {
z-index: 1048576;
}

/*礼物包裹内样式*/
.gift-style-modify .gift-item-wrap .expiration {
padding: 1px 5px!important;
border-radius: 15px!important;
text-align: center!important;
right: 50%!important;
transform: translate(50%);
line-height: 1.35;
word-break: keep-all!important;
}

.gift-style-modify .gift-item-wrap {
margin: 10px 0px 0px 5px!important;
width: unset!important;
}

.gift-style-modify .gift-item-wrap:nth-of-type(-n+5) {
margin-top: 5px!important;
}

.gift-style-modify .common-popup-wrap.arrow-bottom.popup {
min-width: 274px!important;
}

.gift-style-modify .item-box {
width: 100%!important;
}

.gift-presets >div .wrap {
bottom: 50px!important;
right: -10px!important;
}

/*全屏礼物栏样式*/
body.fullscreen-fix div#gift-control-vm {
display: block!important;
}

.bilibili-live-player-video-controller .gift-item .info .label,
.bilibili-live-player-video-controller #gift-control-vm .gift-package {
color: unset!important;
}

.bilibili-live-player-video-controller #gift-control-vm {
background: rgba(0, 0, 0, 0.7)!important;
position: relative!important;
width: 100%!important;
border: none!important;
border-radius: 0!important;
height: unset!important;
display: block!important;
}

/*直接放在控制栏上的全屏发送框*/
.bilibili-live-player-video-controller-content .chat-input-ctnr.p-relative {
display: inline-block;
right: 0;
margin-top: 0;
float: right;
vertical-align: sub
}
.bilibili-live-player-video-controller-content textarea.chat-input{
height:25px;
width: 355px;
padding:0;
color: #fff;
background: rgba(0,0,0,.6);
}
.bilibili-live-player-video-controller-content textarea.chat-input .input-limit-hint{
right: 0;
bottom: unset;
}

.bilibili-live-player-video-controller-content .right-action.p-absolute{
position: relative!important;
display: inline-block!important;
vertical-align: super;
float: right;
}

/*放在礼物栏上的全屏弹幕发送框*/
.bilibili-live-player-video-controller .gift-control-panel .chat-input-ctnr{
display: inline-block!important;
vertical-align: middle!important;
width:300px;
margin-right: 5px;
margin-top: 0px;
}

.bilibili-live-player-video-controller .gift-control-panel .right-action.p-absolute{
position: relative!important;
display: inline-block!important;
vertical-align: middle!important;
}

.bilibili-live-player-video-controller .gift-control-panel .chat-input.border-box>span{
right: 90px;
}

.bilibili-live-player-video-controller .gift-control-panel .right-part .gift-presets {
height: unset!important;
margin: 0!important;
bottom: -5px;
}

.bilibili-live-player-video-controller .gift-control-panel {
height: unset!important;
}

.bilibili-live-player-video-controller .supporting-info {
display: none!important;
}

.bilibili-live-player-video-controller .gift-section.gift-list{
vertical-align: middle!important;
}

.bilibili-live-player-video-controller .gift-panel-box ,
.bilibili-live-player-video-controller .outer-drawer[data-v-fd126f5a]{
background: none!important;
border: none!important;
}

.bilibili-live-player-video-controller .count-down {
margin-top: -10px!important;
}
/*右侧弹幕池展开手柄会挡到网页全屏礼物栏*/
.aside-area-toggle-btn.dp-none.p-absolute {
height: 25%;
}`
                },document.head);
            },
            initValues(){
                this.leftContainer = helper.get('.left-container');
                this.toolBar = helper.get('#gift-control-vm');
                this.giftPanel = helper.get('div.gift-presets.p-relative.t-right');
                this.giftPackage = helper.get('.item.z-gift-package');
                if(this.giftPackage) {
                    this.giftPackage.id = 'giftPackage';
                    this.giftPackageContainer = this.giftPackage.parentNode;
                }
                this.playerPanel = helper.get('.bilibili-live-player.relative');
                this.screenPanel = helper.get('.bilibili-live-player-video-controller');
                this.controller = helper.get('.bilibili-live-player-video-controller-content');
                this.inputPanel = helper.get('div.chat-input-ctnr.p-relative');
                this.titlePanel = helper.get('div.normal-mode');
                this.controlPanel = this.inputPanel.parentNode;
                this.bottomPanel = this.inputPanel.nextSibling;
                this.sendButton = this.bottomPanel.lastChild;
                this.title = helper.create('a',{
                    target:'_blank',
                    className:'info-section dp-i-block v-middle title-link',
                    style:'margin-left:16px;font-size:16px'
                });
                this.titleObserver = new MutationObserver(mutations => {
                    mutations.forEach((mutation)=>{
                        if (mutation.target.className==="bilibili-live-player-video-round-title") {
                            this.updateVideoLink();
                        }
                        for (const addedNode of mutation.addedNodes) {
                            if (addedNode.className==="bilibili-live-player-video-round-title") {
                                this.updateVideoLink();
                            }
                        }
                    });
                });
                this.bodyObserver = new MutationObserver(mutations => {
                    mutations.forEach((mutation)=>{
                        if(!mutation.attributeName) return;
                        this.handleFullScreenPanel();
                    });
                });
            },
            //礼物包裹
            updateGiftPackage(){
                if (this.giftPackage&&this.giftPanel){
                    if(this.settings.giftInPanel) {
                        this.giftPanel.appendChild(this.giftPackage);
                        helper.get('.gift-package').className = 'gift-package live-skin-main-text';
                        const guardIcon = helper.get('div.m-guard-ent.gift-section.guard-ent');
                        if (guardIcon) guardIcon.parentNode.removeChild(guardIcon);
                    }
                    else if(this.giftPackage.parentNode!=this.giftPackageContainer) {
                        this.giftPackageContainer.appendChild(this.giftPackage);
                        helper.get('.gift-package').className = 'gift-package live-skin-highlight-bg';
                    }
                    if(this.settings.oldGiftStyle) {
                        this.giftPackage.classList.add('gift-style-modify');
                    }
                    else {
                        this.giftPackage.classList.remove('gift-style-modify');
                    }
                }
            },
            //轮播链接
            updateVideoLink(){
                if(!this.settings.showVideoLink) {
                    if(this.title&&this.titlePanel.contains(this.title)){
                        this.titlePanel.removeChild(this.title);
                    }
                }
                else{
                    const target = helper.get('.bilibili-live-player-video-round-title'),
                          match = target&&target.innerText.match(/((av\d+)|(bv[a-zA-Z0-9]+)).+(P(\d+))+?/i);
                    match&&helper.set(this.title,{
                        innerText:match[1],
                        href:`//www.bilibili.com/video/${match[1]}${match[5]&&match[5]!=1&&`?p=${match[5]}`||''}`
                    },this.titlePanel);
                }
            },
            //全屏礼物面板调整
            handleFullScreenPanel(){
                const className = document.body.className,
                      status = !className ? 'normal' : className.includes('player-full-win') && !className.includes('hide-aside-area')?
                      'web-fullscreen' : className.includes('full') ?
                      'fullscreen' : 'normal';
                if((status=='normal'||!this.settings.fullScreenPanel)&&this.screenPanel.contains(this.toolBar)){
                    this.leftContainer.appendChild(this.toolBar);
                }
                else if (status!='normal'&&this.settings.fullScreenPanel&&!this.screenPanel.contains(this.toolBar)){
                    this.screenPanel.appendChild(this.toolBar);
                }
                if (status=='fullscreen'&&this.settings.fullScreenChat){
                    if(this.settings.chatInGiftPanel&&this.settings.fullScreenPanel&&!this.giftPanel.contains(this.sendButton)){
                        this.giftPanel.appendChild(this.inputPanel);
                        this.giftPanel.appendChild(this.sendButton);
                    }
                    else if((!this.settings.chatInGiftPanel||!this.settings.fullScreenPanel)&&!this.controller.contains(this.sendButton)){
                        this.controller.appendChild(this.sendButton);
                        this.controller.appendChild(this.inputPanel);
                    }
                }else if((status!='fullscreen'||!this.settings.fullScreenChat)&&!this.bottomPanel.contains(this.sendButton)){
                    this.controlPanel.insertBefore(this.inputPanel,this.bottomPanel);
                    this.bottomPanel.appendChild(this.sendButton);
                }
            },
            update(item,value){
                if(!this.playerPanel) return;
                if(item=='showVideoLink') {
                    this.updateVideoLink();
                }
                else if(item=='giftInPanel'||item=='oldGiftStyle') {
                    return this.updateGiftPackage();
                }
                else if(item=='fullScreenPanel'||item=='fullScreenChat'||item=='chatInGiftPanel') {
                    this.handleFullScreenPanel();
                }
                if(this.settings.showVideoLink) {
                    this.titleObserver.observe(this.playerPanel, {subtree:true,childList:true});
                }
                else {
                    this.titleObserver.disconnect();
                }
                if(this.settings.fullScreenPanel||this.settings.fullScreenChat){
                    this.bodyObserver.observe(document.body,{
                        attributes: true,
                        attributeOldValue: true,
                        attributeFilter: ['class']
                    });
                }
                else {
                    this.bodyObserver.disconnect();
                }
            },
            init(settings){
                this.settings = settings;
                this.initValues();
                this.initStyle();
                this.update();
                this.updateVideoLink();
                this.updateGiftPackage();
            }
        },

        //勋章/头衔扩展
        advancedSwitcher:{
            room:typeof(unsafeWindow)!="undefined"?unsafeWindow.BilibiliLive:window.BilibiliLive,
            titleInfos:undefined,
            oldMedalButton:undefined,
            oldTitleButton:undefined,
            medalButton:undefined,
            titleButton:undefined,
            dialog:undefined,
            strings:{
                medal:{
                    name:'勋章',
                    link:'//link.bilibili.com/p/center/index#/user-center/wearing-center/my-medal',
                    dataUrl:'//api.live.bilibili.com/i/api/medal?page=1&pageSize=1000'
                },
                title:{
                    name:'头衔',
                    link:'//link.bilibili.com/p/center/index#/user-center/wearing-center/library',
                    dataUrl:'//api.live.bilibili.com/appUser/myTitleList'
                }
            },
            update(item,value){
                if(value==true){
                    this.replaceToNew();
                }
                else{
                    this.replaceToOld();
                    this.closeDialog();
                }
            },
            init(setting){
                //各种按钮
                const bottomPanel = helper.get('#chat-control-panel-vm .bottom-actions');
                this.oldMedalButton = bottomPanel.querySelector('.action-item.medal');
                this.oldTitleButton = bottomPanel.querySelector('.action-item.title');
                this.medalButton = this.oldTitleButton.cloneNode(true);
                this.medalButton.dataset.name = 'medal';
                this.medalButton.innerText = '勋';
                this.titleButton = this.oldTitleButton.cloneNode(true);
                this.titleButton.dataset.name = 'title';
                //对话框点击事件处理句柄
                this.handler = (e)=>this.handleDialog(e.target);
                //创建对话框
                this.dialog = helper.create('div',{
                    id:'title-medal-dialog',
                    style:'display:none;bottom:50px',
                    //innerHTML:`<style>#title-medal-dialog a{color: #23ade5;}</style>`
                },bottomPanel.parentNode);
                //样式
                helper.create('style',{
                    innerHTML:'#title-medal-dialog>div>div:nth-child(odd){background-color: #f1f2f4;}'
                    +'#title-medal-dialog .title-medal-selected-line{background: #e4f12699 !important;}'
                    +'#title-medal-dialog .fans-medal-item{cursor:pointer}'
                    +'#title-medal-dialog .fans-medal-item .label{width: 35px;display: inline-block;text-align: center;padding: 0 3px;}'
                    +'#title-medal-dialog .fans-medal-item .level{display: inline-block;width: 16px;text-align: center;background:#fff}'
                    +'#title-medal-dialog .gray span.h-100.v-top{background:#c0c0c0 !important}'
                    //*//以下是旧版勋章样式,大概用不到了
                    +'#title-medal-dialog .fans-medal-item.gray .level{color:#c0c0c0}'
                    +'#title-medal-dialog .fans-medal-item.gray .label{background:#c0c0c0}'
                    +'#title-medal-dialog .fans-medal-item.gray{border-color:#c0c0c0}'
                    +['#61DDCB','#5896DE','#A068F1','#FF86B2','#f6be18'].map((color,lv)=>[1,2,3,4].map(add=>{
                        return `#title-medal-dialog .level-${lv*4+add}{border-color: ${color}}`
                            + `#title-medal-dialog .level-${lv*4+add} .label{background-color: ${color}}`
                            + `#title-medal-dialog .level-${lv*4+add} .level{color: ${color}}`;
                    }).join('')).join('')
                    //*/
                },this.dialog);
                //对话框箭头
                this.dialogArraw = helper.create('div',{
                    className:"p-absolute",
                    style:"top: 100%;border-left: 4px solid transparent;border-right: 4px solid transparent;border-top: 8px solid #fff;"
                },this.dialog);
                //对话框标题
                this.dialogTitle = helper.create('div',{style:"font-weight: 400;font-size: 18px;"},this.dialog);
                //对话框内容本体
                this.dialogPanel = helper.create('div',{style:'max-height: 400px;overflow: auto;'},this.dialog);
                //对话框正在载入面板
                this.loadingDiv = helper.create('div',{className:"tv"},this.dialog);
                //对话框底部面板
                this.dialogBottom = helper.create('div',{style:"margin-top: 10px;text-align: center;"},this.dialog);
                if(setting.replaceMedalTitle) this.replaceToNew();
            },
            replaceToNew(){
                const bottomPanel = helper.get('#chat-control-panel-vm .bottom-actions');
                this.panel = bottomPanel.firstElementChild;
                helper.replace(this.oldTitleButton,this.titleButton);
                this.panel.insertAdjacentElement('beforeend',this.medalButton);
                document.body.addEventListener('click', this.handler);
            },
            replaceToOld(){
                this.medalButton.parentNode.removeChild(this.medalButton);
                helper.replace(this.titleButton,this.oldTitleButton);
                document.body.removeEventListener('click', this.handler);
            },
            handleDialog(target){
                if (this.dialog.contains(target)) return;
                const targetName = target.dataset.name;
                if (
                    !targetName ||
                    this.dialog.dataset.name==targetName ||
                    (target!=this.medalButton&&target!=this.titleButton)
                ) {
                    return this.closeDialog();
                }
                const targetConfig = this.strings[targetName];
                //设置当前对话框目标
                this.dialog.dataset.name = targetName;
                this.dialogTitle.innerText = '我的'+targetConfig.name;
                //设置对话框位置
                this.dialog.style = `transform-origin: ${target.offsetLeft+3}px bottom 0px;position:absolute;bottom:50px;color: #23ade5;`;
                this.dialogArraw.style.left = target.offsetLeft+3 + 'px';
                //显示正在加载面板
                helper.set(this.loadingDiv,{
                    style:"height:100px",
                    innerHTML:`<span data-v-ec1c3b2e="" role="progress" class="link-progress-tv" data-v-4df82965=""></span>`
                })
                //清空对话框本体
                this.dialogPanel.innerHTML = '';
                //底部面板初始化为目标链接
                this.dialogBottom.innerHTML = `<a href="${targetConfig.link}" target="_blank" title="前往${
                targetConfig.name}管理页面" style="color: #23ade5;">管理我的${targetConfig.name}</a>`;
                //获取数据并调用显示处理
                helper.xhr(targetConfig.dataUrl).then(async data=>{
                    if(targetName=='medal') this.listMedal(data);
                    else if(targetName=='title') await this.listTitle(data);
                }).then(()=>{
                    this.loadingDiv.style = 'display:none';
                    if(helper.isFirefox && (this.dialogPanel.scrollHeight>this.dialogPanel.clientHeight)) {
                        this.dialogPanel.style.width = this.dialogPanel.offsetWidth + 20 + 'px';
                    }
                    else {
                        this.dialogPanel.style.width = 'unset';
                    }
                }).catch (e=>{
                    this.loadingDiv.innerHTML = `<p class="des">解析返回错误${e}~</p>`;
                    console.error(e);
                });
                this.dialog.className = 'dialog-ctnr common-popup-wrap p-absolute border-box z-chat-control-panel-dialog bottom v-enter a-scale-in-ease v-enter-to';
            },
            closeDialog(){
                if (this.dialog.classList.contains('v-enter')){
                    this.dialog.dataset.name = '';
                    this.dialog.className = 'dialog-ctnr common-popup-wrap p-absolute border-box z-chat-control-panel-dialog bottom v-leave a-scale-out';
                    setTimeout(()=>{this.dialog.style='display:none;';},300);
                }
            },
            doRequire(url,text){
                return helper.xhr(url).then(data=>{
                    helper.toast(`${text}${data.code==0?'成功':`失败 code ${data.code} ${data.message}`}`);
                }).catch(e=>{
                    helper.toast(`${text}出错${e}`)
                })
            },
            buyMedal(type){
                if (!confirm(`是否确认使用${type=='silver'?'9900银瓜子':'20硬币'}购买本房间勋章?`)){
                    return;
                }
                let token = document.cookie.match(/bili_jct=([0-9a-fA-F]{32})/);
                if (!token) return helper.toast('找不到令牌');
                token = token[1];
                return helper.xhr(`//api.vc.bilibili.com/link_group/v1/member/buy_medal`,{
                    coin_type: type,
                    master_uid: this.room.ANCHOR_UID,
                    platform: 'android',
                    csrf_token: token,
                    csrf: token
                }).then(data=>{
                    helper.toast(`购买勋章${data.code==0?'成功':`失败 code ${data.code} ${data.message}`}`);
                }).catch(e=>{
                    helper.toast(`购买勋章出错${e}`)
                });
            },
            listMedal(data){
                let hasMedal = false;
                if (data.code!=0||!data.data||!(data.data.fansMedalList instanceof Array)) {
                    console.error(data);
                    throw(`查询勋章失败 code:${data.code}</br>${data.message}`);
                }
                data.data.fansMedalList.forEach((v)=>{
                    if (this.room.ANCHOR_UID==v.target_id) hasMedal = true;
                    const itemDiv = helper.create('div',{
                        style:'margin-top: 8px',
                        className:v.status&&'title-medal-selected-line'||''
                    },this.dialogPanel);
                    helper.create('div',{
                        title:`主播:${v.target_name}\n${v.status?'当前佩戴勋章,点击取消佩戴':'点击佩戴此'}勋章${!v.is_lighted?'\n已熄灭,投喂金瓜子礼物或者小心心点亮':''}`,
                        style:`border-color: #${v.medal_color_border.toString(16)}`,
                        innerHTML:`<div class="label" style="background:linear-gradient(45deg, #${v.medal_color_start.toString(16)}, #${v.medal_color_end.toString(16)})"><span class="content">${v.medal_name}</span></div>`
                        +`<span class="level" style="color:#${v.medal_color_start.toString(16)}">${v.level}</span>`,
                        className:`fans-medal-item v-middle level-${v.level} ${!v.is_lighted?'gray':''}`,
                        onclick:()=>{
                            this.doRequire(v.status?'//api.live.bilibili.com/i/ajaxCancelWear':`//api.live.bilibili.com/i/ajaxWearFansMedal?medal_id=${v.medal_id}`
                                           ,v.status?'取消佩戴勋章':'切换勋章');
                            this.closeDialog();
                            setTimeout(()=>this.oldMedalButton&&this.oldMedalButton.click()&this.oldMedalButton.click(),200);
                        }
                    },itemDiv);
                    helper.create('span',{
                        title:`升级进度:${v.intimacy}/${v.next_intimacy}\r\n升级还差:${v.next_intimacy-v.intimacy}`,
                        className:`dp-i-block over-hidden v-middle ${!v.is_lighted?'gray':''}`,
                        style:"height: 8px;width: 64px;margin: 0 8px;border-radius: 3px;background-color: #e3e8ec;",
                        innerHTML:`<span class="dp-i-block h-100 v-top" style="width: ${v.intimacy/v.next_intimacy*100}%;background-color: #23ade5;"></span>`
                    },itemDiv);
                    helper.create('a',{
                        style:'color:#999;min-width:50px',
                        href:`/${v.room_id||v.roomid}`,target:"_blank",className:"intimacy-text v-middle dp-i-block",
                        title:`今日上限剩余${v.day_limit-v.today_feed}\n点击前往主播房间`,
                        innerText:`${v.today_feed}/${v.day_limit}`
                    },itemDiv);
                });
                if (this.room.ANCHOR_UID&&!hasMedal){
                    const buyDiv = helper.create('div',{style:'display: inline-block;'},this.dialogBottom);
                    helper.create('div',{
                        title:"使用20硬币购买本房间勋章",
                        style:"margin-left: 10px;",
                        className:"dp-i-block pointer",
                        onclick:()=>this.buyMedal('metal'),
                        innerHTML:`<span style="border: 1.8px solid #c8c8c8;border-radius: 50%;border-color: #23ade5;">硬</span><span>20</span>`
                    },buyDiv);
                }
                if (data.data.fansMedalList.length==0) {
                    helper.create('p',{
                        innerHTML:'<p data-v-17cf8b1e="" class="empty-hint-text">你还没有勋章哦~</p>'
                        +'<div data-v-17cf8b1e="" class="empty-image"></div>'
                    },this.dialogPanel);
                }
            },
            async listTitle(data){
                if (data.code!=0||!data.data||!(data.data.list instanceof Array)) {
                    console.error(data);
                    throw(`查询头衔失败 code:${data.code}</br>${data.message}`);
                }
                if (!this.titleInfos){
                    await helper.xhr('//api.live.bilibili.com/rc/v1/Title/webTitles').then(data => {
                        if (data.code!=0||!(data.data instanceof Array)) throw(`code:${data.code}\r\n${data.message}`);
                        this.titleInfos = {};
                        data.data.forEach(title=>{
                            this.titleInfos[title.identification] = title.web_pic_url;
                        });
                    }).catch(e=>{
                        console.error(e);
                    });
                }
                data.data.list.forEach((v)=>{
                    const lvMax = v.level.length&&v.level[v.level.length-1],
                          outOfDate = (new Date(v.expire_time)-Date.now())/1000/60/60/24<4;
                    const itemDiv = helper.create('div',{style: 'margin-top: 12px',className:v.status?'title-medal-selected-line':''},this.dialogPanel);
                    helper.create('a',{
                        className:"live-title-icon pointer v-middle dp-i-block",
                        href:v.url==''?'javascript:':v.url,target:'_blank',
                        title:`${v.name} ${v.activity}\r\n${v.description}\r\n${v.url!=''?'点击前往头衔活动页面':''}`,
                        innerHTML: `<img alt="${v.name}" src="${(this.titleInfos&&this.titleInfos[v.title])||v.title_pic&&v.title_pic.img}" class="live-title-icon pointer">`,
                        style:`min-width:88px;`
                    },itemDiv);
                    helper.create('span',{
                        title:`头衔经验:${v.score}\r\n${lvMax?`满级还差${v.score-lvMax}`:''}`,
                        className:"dp-i-block v-center over-hidden v-middle",
                        style:"height: 8px;width: 64px;margin: 0 8px;border-radius: 3px;background-color: #e3e8ec;",
                        innerHTML:`<span class="dp-i-block h-100 v-top" style="width: ${lvMax?v.score/lvMax*100:100}%;background-color: #23ade5;"></span>`
                    },itemDiv);
                    helper.create('span',{
                        style:`color:${outOfDate?'#f00':'#29abe1'};border:1px solid #a068f1;border-radius:3px;cursor:pointer;padding:3px;`,
                        onclick: ()=>{
                            this.doRequire(v.status?`//api.live.bilibili.com/i/ajaxCancelWearTitle`:`//api.live.bilibili.com/appUser/wearTitle?title=${v.title}`
                                           ,`${v.status?'取消佩戴':'切换'}头衔`);
                            this.closeDialog();
                        },
                        className:'v-middle dp-i-block',
                        title:`头衔过期时间${v.expire_time}\r\n点击${v.status?'取消佩戴':'佩戴'}`,
                        innerText:v.status?'取消':'佩戴'
                    },itemDiv);
                });
                if (data.data.list.length==0) {
                    helper.create('p',{
                        innerHTML:'<p data-v-17cf8b1e="" class="empty-hint-text">你还没有头衔哦~</p>'
                        +'<div data-v-17cf8b1e="" class="empty-image"></div>'
                    },this.dialogPanel);
                }
            }
        },

        otherGift:{
            init (settings){
                const bottomPanel = helper.get('#chat-control-panel-vm .bottom-actions');
                this.panel = bottomPanel.firstElementChild;
                this.newGift = helper.set(bottomPanel.querySelector('.action-item.title').cloneNode(),{
                    innerText:'礼',
                    title:'其它礼物'
                });
                this.handler = (ev)=>this.showGift(ev.target);
                if(settings.showOtherGift) this.append();
            },
            append(){
                this.panel.appendChild(this.newGift);
                document.body.addEventListener('click',this.handler);
            },
            remove(){
                document.body.removeEventListener('click',this.handler);
                this.panel.removeChild(this.newGift);
            },
            update(item,value){
                if(value){
                    this.append();
                }else{
                    this.remove();
                }
            },
            token:(()=>{
                try{
                    return document.cookie.match(/bili_jct=([0-9a-fA-F]{32})/)[1];
                }catch(e){
                    return undefined;
                }
            })(),
            imgType:(()=>{
                try{
                    return 0==document.createElement('canvas').toDataURL("image/webp").indexOf("data:image/webp")?'webp':'gif';
                }catch(e){
                    return 'gif';
                }
            })(),
            newGift:undefined,
            gift:[],
            room:typeof(unsafeWindow)!="undefined"?unsafeWindow.BilibiliLive:window.BilibiliLive,
            sendGift(index){
                let type = 'gold';
                let num = 1;
                this.newGift.lastChild.style.display = 'none';
                const target = this.gifts[index];
                const sendPanel = helper.create('div',{
                    className : 'bilibili-live-player-gfs-give-float',
                    style:"position:fixed;",
                    innerHTML : `
<div class="bilibili-live-player-gfs-give-wrap">
<div class="bilibili-live-player-gfs-give-close"></div>
<h2>赠送礼物</h2>
<div class="clearfix">
<div class="bilibili-live-player-gfs-give-gif" style="background-image: url(${target[this.imgType]})"></div>
<div class="bilibili-live-player-gfs-give-info">
<div class="bilibili-live-player-gfs-give-name">${target.name}</div>
<div class="bilibili-live-player-gfs-give-cost">
<div class="bilibili-live-player-gfs-give-cost-gold">
<i></i><span>${target.price}</span></div></div>
</div>
</div>
<p class="gift-info-desc" data-v-33a72392="">${target.desc}</p>
<div>
<span>选择:</span>
<div class="bilibili-live-player-gfs-give-type">
<label class="bilibili-live-player-gfs-give-type-silver">
<input name="send_gift_type" type="radio" value="gold" checked>金瓜子
<input name="send_gift_type" type="radio" value="silver">银瓜子
</label></div>
</div>
<div>
<input class="bilibili-live-player-gfs-give-counter" type="text" value="${num}" placeholder="赠送数量">
<button class="bilibili-live-player-gfs-give-confirm">赠送</button>
</div>
</div>`
                },document.body);
                sendPanel.querySelector('input[value="silver"]').onchange = ()=>{type='silver';};
                sendPanel.querySelector('input[value="gold"]').onchange = ()=>{type='gold';};
                sendPanel.querySelector('.bilibili-live-player-gfs-give-counter').onchange = (ev)=>{num=ev.target.value;};
                sendPanel.querySelector('.bilibili-live-player-gfs-give-close').onclick = ()=>document.body.removeChild(sendPanel);
                sendPanel.querySelector('.bilibili-live-player-gfs-give-confirm').onclick = ()=>{
                    document.body.removeChild(sendPanel);
                    if (!this.room){
                        return helper.toast('无法找到房间信息,赠送失败');
                    }
                    helper.xhr('//api.live.bilibili.com/gift/v2/gift/send',{
                        gift_id:target.id,
                        ruid:this.room.ANCHOR_UID,
                        gift_num:num,
                        coin_type:type,
                        biz_id:this.room.ROOMID,
                        csrf_token:this.token
                    }).then(data=>{
                        helper.toast(`赠送礼物${data.code==0?'成功':`失败 code ${data.code} ${data.message}`}`);
                    }).catch(error=>{
                        helper.toast(`赠送礼物$出错${error}`);
                    });
                };
            },
            showGift(target){
                if (!this.newGift.contains(target)){
                    if (this.newGift.lastChild.style) this.newGift.lastChild.style.display = 'none';
                }else if (target==this.newGift){
                    if (this.newGift.lastChild.style&&this.newGift.lastChild.style.display!='none') {
                        return (this.newGift.lastChild.style.display = 'none');
                    }
                    else if (this.gifts) {
                        return (this.newGift.lastChild.style.display = 'unset');
                    }
                    const list = document.createElement('div');
                    const items = document.createElement('div');
                    items.innerHTML = '<div data-v-ec1c3b2e="" class="tv"><div data-v-4df82965="" data-v-ec1c3b2e="" role="progress" class="link-progress-tv"></div></div>';
                    list.className = 'common-popup-wrap t-left';
                    list.style = 'position: absolute;width: 276px;bottom: 30px;left: 0px;cursor: auto;animation:scale-in-ease 0.4s;transform-origin: 90px bottom 0px;';
                    list.innerHTML = `<div style="position: absolute;left: ${target.offsetLeft+3}px;top: 100%;width: 0;height: 0;border-left: 4px solid transparent;
border-right: 4px solid transparent;border-top: 8px solid #fff;"></div><header style="font-size:18px;color:#23ade5;margin-bottom:10px;">其它礼物</header>`;
                    list.appendChild(items);
                    this.newGift.appendChild(list);
                    helper.xhr('//api.live.bilibili.com/gift/v3/live/gift_config').then(data=>{
                        this.gifts = data.data;
                        items.innerHTML = '';
                        items.style = 'height:233px;overflow: auto;'
                        for (let i=0;i<this.gifts.length;i++){
                            const g = this.gifts[i];
                            items.innerHTML += `<div data-index="${i}" style="background-image: url(${g.img_basic});width: 45px;height: 45px;"
class="bg-cover dp-i-block pointer" title="${g.name}"></div>`;
                        }
                        [].forEach.call(items.childNodes,c=>{
                            c.onclick = (ev) => this.sendGift(ev.target.dataset.index);
                        });
                    });
                }
            }
        },

        changeSetting(target){
            try{
                this.settings[target.id] = target.checked;
                this[this.settingInfos[target.id].group].update(target.id,target.checked);
                typeof(GM_setValue)!='undefined'?GM_setValue('BilibiliLiveHelper',JSON.stringify(this.settings))
                :localStorage.BilibiliLiveHelper = JSON.stringify(this.settings);
            }
            catch(e){
                console.error(e);
            }
        },
        initSetting(){
            this.settings = (()=>{
                try{
                    const str = typeof(GM_setValue)!='undefined'?
                          GM_getValue('BilibiliLiveHelper','{}'):localStorage.BilibiliLiveHelper;
                    return JSON.parse(str);
                }catch(e){
                    return {};
                }
            })();
            const button = helper.get('.bilibili-live-player-video-controller-block-btn'),
                  settingPanel = helper.create('div',{
                      className:"bilibili-live-player-video-controller-hide-danmaku-container t-left",
                      innerHTML:`<div>直播间助手设置</div>`,
                  },button);
            helper.create('style',{
                innerHTML:`.bilibili-live-player-video-controller-block-btn:hover .bilibili-live-player-video-controller-hide-danmaku-container\
{padding: 10px 15px;overflow: visible;height: auto;visibility: visible;}`
            },settingPanel);
            for(const key in this.settingInfos){
                if(this.settings[key]==undefined) this.settings[key] = true;
                const item = helper.create('div',{className:'blpui-checkbox-container'},settingPanel);
                helper.create('input',{
                    type:'checkbox',
                    className:'blpui-checkbox',
                    id:key,
                    checked:this.settings[key],
                    onchange:({target})=>this.changeSetting(target)
                },item);
                helper.create('label',{
                    className:'blpui-checkbox-span no-select',
                    innerText:this.settingInfos[key].name
                },item).setAttribute('for',key);
            }
        },

        doInit(){
            try{
                //已经有一个礼物包裹的ID说明脚本运行过返回true防止二次初始化
                if(helper.get('#giftPackage')) return true;
                //页面中没有礼物包裹说明页面没有加载完成返回false继续监听页面加载
                if(!helper.get('.gift-package')) return false;
                this.initSetting();
                this.elementAdjuster.init(this.settings);
                this.advancedSwitcher.init(this.settings);
                this.otherGift.init(this.settings);
                //初始化成功返回true不用监听页面加载
                return true;
            } catch (e){
                helper.toast('bilibili直播间助手执行错误',e);
                //初始化异常,返回true放弃继续监听页面
                return true;
            }
        },
        init(){
            if(this.doInit()) return;
            new MutationObserver((mutations,observer) => {
                //console.log(mutations)
                if(helper.get('.gift-package')){
                    observer.disconnect();
                    this.doInit();
                    return;
                }
            }).observe(helper.get('#aside-area-vm')||document.body, {
                childList: true,
                subtree: true
            });
        }
    };
    setTimeout(() => {
        LiveHelper.init();
    }, 3e3);
})();