Greasy Fork is available in English.

Absinth苦艾

七夕福利版

// ==UserScript==
// @name         Absinth苦艾
// @homepage     https://greasyfork.org/zh-CN/scripts/397548
// @version      5.5.9
// @description  七夕福利版
// @author       风绫丨钰袖
// @iconURL      https://i0.hdslb.com/bfs/article/927cc195124c47474b4a150d8b09e00536d15a0a.gif
// @icon64URL    https://i0.hdslb.com/bfs/article/927cc195124c47474b4a150d8b09e00536d15a0a.gif
// @include      /https?:\/\/live\.bilibili.com/\??.*/
// @require      https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js
// @connect      passport.bilibili.com
// @connect      api.live.bilibili.com
// @connect      live-trace.bilibili.com
// @require      https://cdn.jsdelivr.net/gh/lzghzr/TampermonkeyJS@55fdb489ce4d3f73c02a4ddec9a6979023b7479c/libBilibiliToken/libBilibiliToken.js
// @require      https://cdn.jsdelivr.net/gh/lzghzr/TampermonkeyJS@fe2340677328762f9d6e9686603e9781d69cd3c9/libWasmHash/libWasmHash.js
// @grant        unsafeWindow
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_xmlhttpRequest
// @grant        GM_openInTab
// @run-at       document-idle
// @license      MIT License
// @namespace http://tampermonkey.net/
// ==/UserScript==

window.onload=(function ZDBGJ_BLRHH_Plus(){
    var Anchor_ignore_keyword=[];
    var speedupnow=0;
    let NAME;
    let BAPI;
    let ZBJ;
    let CJ;
    var riqi;
    var BPDJ;
    var COUNT;
    var Lcount;//小心心防异常
    riqi=new Date();
    var yue=riqi.getMonth()+1;
    var ri=riqi.getDate();
    var xiaoshi=riqi.getHours();
    var fenzhong=riqi.getMinutes();
    var nowTime = riqi.getTime();
    riqi.setTime(parseInt(nowTime -24*3600*1000));
    var yyue = (riqi.getMonth() + 1);//昨日月份
    var yri = riqi.getDate();//昨日
    let Live_info = {
        room_id: undefined,
        uid: undefined,
        blocked:undefined,
        csrf_token: undefined,
        visit_id: undefined,
        rnd: undefined,
        ruid: undefined,
    };
    const tz_offset = new Date().getTimezoneOffset() + 480;
    const ts_ms = () => Date.now();
    const ts_s = () => Math.round(ts_ms() / 1000);
    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;
    };
    const sleep=(miliseconds) => {
        return new Promise(resolve=>{
            setTimeout(()=>{resolve();},miliseconds);
        });
    }
    $(function () {//DOM完毕,等待弹幕加载完成
        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': 'rgb(218, 142, 36)',
                '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;
                    NAME=Live_info.uid;
                    //console.log(Live_info);
                    init();
                    i=0
                }
            }, delay);
        };
        loadInfo(3000);
    });

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

    function init() {//API初始化
        try {
            BAPI = BilibiliAPI;
        } catch (err) {
            console.error(`[${NAME}]`, err);
            return;
        }
        Live_info.csrf_token = BAPI.getCookie('bili_jct');
        Live_info.visit_id = window.__statisObserver ?
            window.__statisObserver.__visitId : '';
        const MY_API = {
            CONFIG_DEFAULT: {
                GIFT_AUTO:true,
                GIFT_AUTO2:true,
                GIFT_NUM: 1500,
                GIFT_ROOM: 2374828,
                GIFT_NUM2: 24,
                GIFT_ROOM2: 2374828,
                TALK: false,//不显示抽奖反馈
                TIMEAREADISABLE: true,
                TIMEAREASTART: 2,
                TIMEAREAEND: 6,
                TOProomnum:300,
                TOProomnumF:300,//脚本页面非当前窗口,TOProomnum备份
                gift_price:0,
                Anchor_ignore_keyword:['舰长', '照片', '总督', '提督', '一毛', '0.01', '禁言', '0.1'],
                CZ: 180,
                JSMARK:0,//多开标记
                AUTO_BOX: true,//每日硬币
                AUTO_HEART_newmodel: true,
                materialobject_ts:0,
                last_aid:600,
                AUTO_GOLDBOX:false,//金箱子抽奖
                AUTO_Anchor:false,//天选时刻抽奖
                COUNT_GOLDBOX: 0,//天选时刻、金箱子抽奖参与次数
            },

            CONFIG: {},
            GIFT_COUNT: {
                COUNT: 0,
                LCOUNT: 0,//小心心数量
                LCOUNT2: 0,//模式2小心心数量
                LOVE_COUNT: 0,
                CLEAR_TS: 0,
                TTCOUNT: 0,
                TTLOVE_COUNT: 0,
                BPJY: 0,
                BPDJ: 1,
                DJLVMK: 100,

            },
            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(() => {
                            let l = $("div.checkin-btn.t-center.pointer");
                            if (l.length > 0) {
                                l.click();
                            }
                            MY_API.chatLog('系统参数配置完成!', 'success');
                        }, 1000);
                        setTimeout(() => {
                            let l = $("div.checkin-btn.t-center.pointer");
                            if (l.length > 0) {
                                l.click();
                            }
                            MY_API.chatLog('谁才是天选之子!天选众,来战!', 'success');
                        }, 3000);
                        setTimeout(() => {
                            let l = $("div.checkin-btn.t-center.pointer");
                            if (l.length > 0) {
                                l.click();
                            }
                        }, 10000);
                        setTimeout(() => {
                            let l = $("div.checkin-btn.t-center.pointer");
                            if (l.length > 0) {
                                l.click();
                            }
                        }, 100000);
                        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));
                    $('#COUNT_GOLDBOX span:eq(0)').text(MY_API.CONFIG.COUNT_GOLDBOX);
                    $('#giftCoun span:eq(0)').text(MY_API.CONFIG.COUNT_GOLDBOX);
                    return true
                } catch (e) {
                    //console.log('API保存出错', e);
                    return false
                }
            },
            setDefaults: function () {
                MY_API.CONFIG = MY_API.CONFIG_DEFAULT;
                MY_API.GsaveConfig();
                MY_API.chatLog(`天选众代号:${NAME}<br/>你好!欢迎来到白嫖怪的修仙世界!`);
                MY_API.chatLog(`未检测到帐号信息,正在创建帐号......`, 'warning');
                MY_API.chatLog(`帐号创建完成,5秒后重新登陆系统!`, 'warning');
                setTimeout(() => {
                    window.location.reload()
                }, 5000);
            },
            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;
                    MY_API.cjcheck();
                } 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;
                    return true
                } catch (e) {
                    //console.log('统计保存出错', e);
                    return false
                }
            },

            cjcheck: function () {
                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<800){
                    CJ='合体白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<900){
                    CJ='渡劫白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<1000){
                    CJ='大乘白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<2000){
                    CJ='仙人白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<5000){
                    CJ='地仙白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<10000){
                    CJ='天仙白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<20000){
                    CJ='玄仙白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<30000){
                    CJ='神境白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<40000){
                    CJ='神人白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<60000){
                    CJ='准神白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<80000){
                    CJ='主神白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<100000){
                    CJ='神王白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<200000){
                    CJ='天尊白嫖怪'
                }else if(MY_API.GIFT_COUNT.BPDJ<300000){
                    CJ='天尊白嫖怪一重天'
                }else if(MY_API.GIFT_COUNT.BPDJ<400000){
                    CJ='天尊白嫖怪二重天'
                }else if(MY_API.GIFT_COUNT.BPDJ<500000){
                    CJ='天尊白嫖怪三重天'
                }else if(MY_API.GIFT_COUNT.BPDJ<600000){
                    CJ='天尊白嫖怪四重天'
                }else if(MY_API.GIFT_COUNT.BPDJ<700000){
                    CJ='天尊白嫖怪五重天'
                }else if(MY_API.GIFT_COUNT.BPDJ<800000){
                    CJ='天尊白嫖怪六重天'
                }else if(MY_API.GIFT_COUNT.BPDJ<900000){
                    CJ='天尊白嫖怪七重天'
                }else if(MY_API.GIFT_COUNT.BPDJ<1000000){
                    CJ='天尊白嫖怪八重天'
                }else if(MY_API.GIFT_COUNT.BPDJ<2000000){
                    CJ='天尊白嫖怪九重天'
                }else if(MY_API.GIFT_COUNT.BPDJ>=2000000){
                    CJ='天尊白嫖怪大圆满'
                };
            },
            expaddGift: function (count) {
                count=20+Math.ceil(Math.random() * 20)
                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);
                $('#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();
            },
            expaddLove: function (count) {
                count=10+Math.ceil(Math.random() * 20)
                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();
            },
            get_white_list: function () { //获取白名单
                let run = $("<div class='zdbgjrun'>");//run
                run.css({
                    'position': 'absolute',
                    'top': '225px',
                    'right': '375px',
                    'z-index': '-1',
                });
                run.append(`
<img  src="https://i0.hdslb.com/bfs/article/9956369da838a89e9bd209e125cabcdeecd58bef.gif" width="84" height="84"/>
`);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(run);
                run.css({
                    'z-index': '11',
                });
                let id_list = [20842051,364225566];
                let mark=0;
                let pn=1;
                let pnn=100;
                let uname_list=[20842051,364225566];
                let get_list =async  function(){
                    await $.get("https://api.bilibili.com/x/relation/followings?vmid="+`${Live_info.uid}&pn=${pn}&ps=50&order=desc&jsonp=jsonp`
                                , function (data) {
                        let total=data.data.total
                        pnn=parseInt(total/50)+1;
                        let list = data.data.list;// [{id: ,link:}]
                        console.log(list);
                        for (let i=0;i<list.length;i++) {
                            let id=list[i].mid;
                            let uname=list[i].uname;
                            if (id_list.indexOf(id) > -1){
                                console.log(`${id}白名单列表已有`);
                            }else{
                                id_list.push(id);
                                uname_list.push(uname);
                                console.log(`${id}白名单列表添加`);
                            }
                        };
                    });
                    pn++;
                }
                let timer = setInterval(function () {
                    if (pn <= pnn) {
                        get_list();
                    } else {
                        try {
                            localStorage.setItem(`${NAME}_white_list`, JSON.stringify({list: id_list}));
                        } catch (e) {
                            localStorage.setItem(`${NAME}_white_list`, JSON.stringify({list: id_list}));
                            console.log(`${NAME}_Anchor_list添加数据失败`);
                        }
                        clearInterval(timer);
                        mark=1;
                        get_follow_show();
                    }
                }, 5e3);
                let k=2
                let get_follow_show = function () {
                    let id=id_list[k]
                    let uname=uname_list[k]
                    MY_API.chatLog(`【一键白名单】获得当前关注为白名单:<br/>UID:${id},UNAME:${uname}`);
                    k++;
                }
                let get_follow_show_timer = setInterval(function () {
                    if(!mark)return;
                    if (k<id_list.length) {
                        get_follow_show();
                    } else {
                        clearInterval(get_follow_show_timer);
                        MY_API.chatLog(`【一键白名单】获得当前关注为白名单结束!`);
                        run.css({
                            'z-index': '-1',
                        });
                    }
                }, 1e3);
            },
            del_follow_list: function (){ //取关
                let run = $("<div class='zdbgjrun'>");//run
                run.css({
                    'position': 'absolute',
                    'top': '215px',
                    'right': '375px',
                    'z-index': '-1',
                });
                run.append(`
<img  src="https://i0.hdslb.com/bfs/article/3e8528fff3135a11d3946883d52540954d2ae139.gif" width="84" height="84"/>
`);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(run);
                run.css({
                    'z-index': '11',
                });
                let white_list = [];
                let del_follow_list=[];
                let uname_list=[];
                let mark=0;
                try {
                    let config = JSON.parse(localStorage.getItem(`${NAME}_white_list`));
                    white_list = [].concat(config.list);
                } catch (e) {
                    white_list = [].concat(config.list);
                    console.log(`${NAME}_white_list读取失败`);
                }
                //if(!id_list.length) return;
                function bacth_follow(id) {
                    $.ajax({
                        url: '//api.bilibili.com/x/relation/modify',
                        type: "post",
                        xhrFields: {
                            withCredentials: true
                        },
                        data: {
                            'fid': id,
                            'act': 2,
                            're_src': 11,
                            'jsonp': 'jsonp',
                            'csrf': Live_info.csrf_token
                        }
                    })
                    console.log("正在取消关注的用户id为:" + id)
                }
                let pn=1;
                let pnn=100;
                let get_list =async function(){
                    await $.get("https://api.bilibili.com/x/relation/followings?vmid="+`${Live_info.uid}&pn=${pn}&ps=50&order=desc&jsonp=jsonp`
                                , function (data) {
                        let total=data.data.total
                        pnn=parseInt(total/50)+1;
                        let del_list=data.data.list;
                        for (let i=0;i<del_list.length;i++) {
                            let id=del_list[i].mid;
                            let uname=del_list[i].uname
                            del_follow_list.push(id);
                            uname_list.push(uname);
                        }
                        console.log(del_follow_list);
                    });
                    pn++
                }
                get_list();
                let timer = setInterval(function () {
                    if (pn<=pnn) {
                        get_list();
                    } else {
                        clearInterval(timer);
                        mark=1;
                        bacth_follow_do();
                    }
                }, 5e3);
                let k=0
                let bacth_follow_do = function () {
                    let id=del_follow_list[k]
                    let uname=uname_list[k]
                    if (white_list.indexOf(id) > -1){
                        console.log(`${id}白名单`);
                    }else{
                        bacth_follow(id)
                        MY_API.chatLog(`【一键取关】成功取关:<br/>UID:${id},UNAME:${uname}`);
                    }
                    k++;
                }
                let bacth_follow_do_timer = setInterval(function () {
                    if(!mark)return;
                    if (k<del_follow_list.length) {
                        bacth_follow_do();
                    } else {
                        clearInterval(bacth_follow_do_timer);
                        MY_API.chatLog(`【一键取关】本次一键取关结束!`);
                        del_follow_list=[];
                        uname_list=[];
                        run.css({
                            'z-index': '-11',
                        });
                    }
                }, 3e3);
            },

            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 () {
                    $('.zdbgjrun').hide();
                    div.css({
                        'z-index': '-1',
                    });
                    tj.css({
                        'z-index': '-1',
                    });
                    ohb.css({
                        'z-index': '-1',
                    });
                    tp.css({
                        'z-index': '-1',
                    });
                    goldbox.css({
                        'z-index': '-1',
                    });
                    call.css({
                        'z-index': '-1',
                    });
                    call2.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 () {
                    $('.zdbgjrun').show();
                    div.css({
                        'z-index': '10',
                    });
                    tj.css({
                        'z-index': '10',
                    });
                    ohb.css({
                        'z-index': '10',
                    });
                    tp.css({
                        'z-index': '12',
                    });
                    goldbox.css({
                        'z-index': '11',
                    });
                    call.css({
                        'z-index': '11',
                    });
                    call2.css({
                        'z-index': '11',
                    });
                    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',
                });
                msg.append(`
<div id="giftCoun" style="font-size: small;color:blue;">
天选:<span>${MY_API.CONFIG.COUNT_GOLDBOX}</span>
`);

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

                tj.append(`

<fieldset>
<legend  style="font-size: small;color:#FF34B3;" title="关注我,升职加薪不秃头!获得女神阿库娅的祝福!幸运值+++!把把SSR+++!">♥关注♥风绫丨钰袖♥关注♥</legend> </div>
<div data-toggle="AUTO_GOLDBOX">
<apend style="font-size: small; color: #FF34B3" title="一个关注,自动白嫖金宝箱实物抽奖,主要是各种厂商官方活动抽奖">
<input style="vertical-align: text-top;" type="checkbox" >自动实物宝箱抽奖
</div>
<div data-toggle="AUTO_Anchor">
<apend style="font-size: small; color: #FF34B3" title="一个关注,自动白嫖天选时刻,参加其他请手动点击蓝字直播间链接前往直播间">
<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>
<apend style="font-size: small;color: blue">注:自动打开的网页,勿点!否则可能不能自动抽奖!</div>
</fieldset>

<fieldset>
<legend  style="font-size: small;color:#FF34B3;">祝君中奖!</legend> </div>
<div id="COUNT_NUM_GOLDBOX" style="font-size: small;color:#FF34B3;"title="以实际为准,可点击查看中奖纪录">
点击查看实物中奖信息<a target="_blank" href="https://link.bilibili.com/p/center/index#/user-center/my-info/award"><button title="以实际为准,可点击查看中奖纪录"  style="font-size: small;color:#FF34B3;">实物</button></a><br/>
点击查看天选中奖信息<a target="_blank" href="https://link.bilibili.com/p/center/index#/user-center/my-info/celestial"><button title="以实际为准,可点击查看中奖纪录"  style="font-size: small;color:#FF34B3;">天选</button></a></div>
</fieldset>

<fieldset>
<legend  style="font-size: small;color:#FF34B3;" title="请勿频繁操作!">【一键取关操作面板】</legend> </div>
<apend id="guanzhu" style="font-size: small;color: #FF34B3">
<apend title="请勿频繁操作">获取当前关注为白名单<button data-action="guanzhu_white" style="font-size: small;color: #FF34B3" title="请勿频繁操作">执行</button></div>
<apend title="请勿频繁操作">清空已存的白名单列表<button  data-action="guanzhu_clear" style="font-size: small;color: #FF34B3" title="请勿频繁操作">执行</button></div>
<apend title="请勿频繁操作">一键取关白名单外关注<button  data-action="guanzhu_del" style="font-size: small;color: #FF34B3" title="请勿频繁操作">执行</button></div>
<apend style="font-size: small;color: blue">注:请尽量支持关注主播!</div>
</fieldset>

<fieldset>
<legend  style="font-size: small;color:#FF34B3;">【天选时刻过滤规则设置】</legend></div>
<div data-toggle="TOProomnum">
<apend style="font-size: small; color:  #FF34B3" title="范围:200-500,房间上限过大,可能会造成被部分网络访问拒绝">
循检房间上限:<input class="num" style="width: 32px;vertical-align: top;" type="text">
<button data-action="save" style="font-size: small;color:  #FF34B3">保存</button></div>

<div data-toggle="gift_price">
<apend style="font-size: small; color:  #FF34B3" title="理性消费">
金瓜子上限值:<input class="num" style="width: 32px;vertical-align: top;" type="text">
<button data-action="save" style="font-size: small;color:  #FF34B3">保存</button></div>

<div data-toggle="Anchor_ignore_keyword">
<apend style="font-size: small;color: #FF34B3" title="没兴趣的奖品或者无法达到的限制条件,可以按格式加进去,注意是英文逗号!">
奖品及限制条件关键词<button data-action="save" style="font-size: small;color: #FF34B3">保存</button><input class="keyword" style="width: 156px;vertical-align: top;" type="text">
</div>
<apend style="font-size: small;color: blue">注:只会按一次一键参与!</div>
</fieldset>
`);
                let tp = $('<div>');//立牌
                tp.css({
                    'position': 'absolute',
                    'top': '45px',
                    '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="128" height="215" title="李清歌" />
`);

                let goldbox = $('<div>');//樱花树
                goldbox.css({
                    'position': 'absolute',
                    'top': '-20px',
                    'right': '-80px',
                    'z-index': '-1',
                    'opacity':'0.6'
                });
                goldbox.append(`
<img id="box" src="https://i0.hdslb.com/bfs/article/e4b3adf0f63abb240da2f9da72b9a3dc86277b6c.gif" width="288" height="288"/>
`);
                let call = $('<div>');//打call
                call.css({
                    'position': 'absolute',
                    'top': '188px',
                    'right': '100px',
                    'z-index': '-1',
                    'transform':'rotateY(180deg)',
                });
                call.append(`
<img id="box" src="https://i0.hdslb.com/bfs/article/927cc195124c47474b4a150d8b09e00536d15a0a.gif" width="56" height="56"/>
`);
                let call2 = $('<div>');//打call
                call2.css({
                    'position': 'absolute',
                    'top': '188px',
                    'right': '20px',
                    'z-index': '-1',
                });
                call2.append(`
<img id="box" src="https://i0.hdslb.com/bfs/article/927cc195124c47474b4a150d8b09e00536d15a0a.gif" width="56" height="56"/>
`);


                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" />

`);

                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 tppp = $("<div class='zdbgjtppp'>");  //nice
                tppp.css({
                    'position': 'absolute',
                    'top': '200px',
                    'right': '160px',
                    '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"/>
`);
                tppp.append(`
<img id="img3" src="https://i0.hdslb.com/bfs/article/5546414a3be8e3fd8fb79829b438567e99c9e53e.gif" width="90" height="90" />

`);

                let ohb = $("<div class='ohb'>");//欧皇榜
                ohb.css({
                    'width': '240px',
                    'height': '480px',
                    'position': 'absolute',
                    'top': '10px',
                    'right': '590px',
                    'background': 'rgba(255,255,255,.8)',
                    'padding': '10px',
                    'z-index': '-1',
                    'border-radius': '12px',
                    'transition': 'height .3s',
                    'overflow': 'hidden',
                    'line-height': '15px'
                });

                ohb.append(`
<fieldset>
<legend append style="font-size: small;color: #FF34B3;text-align: left;"><span>天选众欧皇榜</legend> </div>
<div  id="ohb" style="font-size: small;color:#FF34B3;">
<div>1、养女儿的零妈妈:小米手环5!</div>
<div>2、云中时日-:青春上海定制U盘!</div>
<div>3、鏌鋣:京东100元现金购物卡!</div>
<div>4、晓天辛:52元天选红包!</div>
<div>5、鲁小蛋:20+10+5.2+5.2元天选!</div>
<div>6、勺子丶11:30元天选红包!</div>
<div>7、很多5元2元1元的就不写了!</div>
<div>8、如果中奖,欢迎加群告知进榜,群内大量中奖截图。</div>
</fieldset>
<fieldset>
<legend append style="font-size: small;color: #FF34B3;text-align: left;"><span>支付宝打赏作者!感谢您的支持!</legend> </div>
<img id="img3" src="https://greasyfork.org/system/screenshots/screenshots/000/023/375/original/QQ%E5%9B%BE%E7%89%87202009010_%281%29.jpg?1600226814" width="180" height="180" />
</fieldset>
`);

                div.append(`
<fieldset>
<legend append style="font-size: small;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="font-size: small;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;
防御:<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;
等级:Lv<span>${MY_API.GIFT_COUNT.BPDJ}</span></div>
</fieldset>

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

<div data-toggle="TALK">
<input style="vertical-align: text-top;" type="checkbox" ><append style="font-size: small;color: Orange">隐藏抽奖等反馈信息</div>

<div data-toggle="AUTO_BOX">
<apend style="font-size: small; color: Orange">
<input style="vertical-align: text-top;" type="checkbox">自动银瓜子兑换硬币</div>



<div data-toggle="AUTO_HEART_newmodel">
<apend style="font-size: small; color: Orange" title="新模式,不占网络内存,加速倍率与勋章数有关">
<input style="vertical-align: text-top;" type="checkbox" title="新模式,不占网络内存,加速倍率与勋章数有关">自动加速领取小心心</div>

<div data-toggle="TOP">
<append style="font-size: small;color: blue" ><data-toggle="CZ" title="自动刷新直播间间隔时间" >自动刷新
<input class="CZTIME" style="width: 25px;vertical-align: AUTO;" type="text">分
<button data-action="save" style="font-size: small;color: blue">保存</button></div>

<div data-toggle="TIMEAREADISABLE">
<apend style="font-size: small; 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="font-size: small;color: purple">保存</button></div>

<div data-toggle="onedayLT">
<apend style="font-size: small; color: purple">
<input style="vertical-align: text-top;" type="checkbox">即将过期辣条:房间
<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="font-size: small;color: purple">保存</button></div>

<div data-toggle="onedayLH">
<apend style="font-size: small; color: purple">
<input style="vertical-align: text-top;" type="checkbox">即将过期心心:房间
<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="font-size: small;color: purple">保存</button></div>
</fieldset>

<fieldset>
<legend append style="font-size: small;color: #FF34B3">温馨推荐</legend>
<div style="font-size: small;color: red">传送门:<a target="_blank" href="https://live.bilibili.com/14578426"><button style="font-size: small;color: red">战斗吧歌姬</button></a>(墙裂推荐,人美歌甜)</div>
<div style="font-size: small;color: red">传送门:<a target="_blank" href="https://live.bilibili.com/2374828"><button style="font-size: small;color: red">风绫丨钰袖</button></a>(关注抽奖,幸运满满)</div>

<div id="hb" style="font-size: small;color: #FF34B3">
╰︶﹉⋛⋋⊱⋋<button data-action="tpphide" style="font-size: small;color: #FF34B3" title="点击显示/隐藏" >【战斗吧歌姬海报】</button>⋌⊰⋌⋚﹉︶╯
</div>
</fieldset>
`);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(ohb);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').prepend(tpp);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(tj);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(tppp);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(div);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(tp);
                $('.chat-history-panel').append(msg);
                let ctt = $('.control-panel-ctnr.border-box.p-relative');
                ctt.append(tpppp);//向聊天框加入信息
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(goldbox);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(call);
                $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(call2);
                //对应配置状态
                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();
                        $("#img2").width(kd).height(gd);
                    };
                    GJTP_Timer();
                    setInterval(GJTP_Timer, 5e3);
                    div.css({
                        'z-index': '10',
                    });
                    ohb.css({
                        'z-index': '10',
                    });
                    tj.css({
                        'z-index': '10',
                    });
                    tp.css({
                        'z-index': '12',
                    });
                    goldbox.css({
                        'z-index': '11',
                    });
                    call.css({
                        'z-index': '11',
                    });
                    call2.css({
                        'z-index': '11',
                    });
                    tpp.css({
                        'z-index': '10',
                    });
                    msg.css({
                        'z-index': '-1',
                    });
                }else  {
                    tpp.css({
                        'width': '0px',
                        'height': '0px',
                    });
                }
                setInterval(() => document.dispatchEvent(new Event('visibilitychange')), 10 * 60 * 1000);//防挂机判定?
                document.addEventListener('visibilitychange', function() {//计时器变慢后改变房间上限?
                    if(document.hidden){
                        MY_API.chatLog('由于插件运行页面非当前窗口,浏览器默认会使脚本计时器变慢造成循检超时,自动逐步减少房间上限至270', 'warning');
                        MY_API.CONFIG.TOProomnum=270;
                        MY_API.GsaveConfig();
                    }else{
                        MY_API.CONFIG.TOProomnum=MY_API.CONFIG.TOProomnumF;
                        MY_API.chatLog('插件运行页面恢复为当前窗口,房间上限恢复', 'warning');
                        MY_API.GsaveConfig();
                    }})
                MY_API.CONFIG.TOProomnum=MY_API.CONFIG.TOProomnumF;
                MY_API.GsaveConfig();
                tj.find('div[data-toggle="TOProomnum"] .num').val((parseInt(MY_API.CONFIG.TOProomnum)).toString());
                tj.find('div[data-toggle="TOProomnum"] .num').val((parseInt(MY_API.CONFIG.TOProomnumF)).toString());
                tj.find('div[data-toggle="gift_price"] .num').val((parseInt(MY_API.CONFIG.gift_price)).toString());
                tj.find('div[data-toggle="Anchor_ignore_keyword"] .keyword').val(MY_API.CONFIG.Anchor_ignore_keyword);
                var isRun1=true;
                var isRun2=true;
                var isRun3=true;
                tj.find('#guanzhu [data-action="guanzhu_white"]').click(function () {
                    MY_API.chatLog('正在获取当前关注列表为白名单......')
                    if(isRun1) MY_API.get_white_list();
                    isRun1=false;
                    setTimeout(function(){
                        isRun1=true;
                    },30e3)
                });
                tj.find('#guanzhu [data-action="guanzhu_clear"]').click(function () {
                    let run = $("<div class='zdbgjrun'>");//run
                    run.css({
                        'position': 'absolute',
                        'top': '225px',
                        'right': '375px',
                        'z-index': '-1',
                        'transform':'rotateY(180deg)',
                    });
                    run.append(`
<img  src="https://i0.hdslb.com/bfs/article/bff50d0857ddab4e4afcfde596b311bc6b66ac46.gif" width="84" height="84"/>
`);
                    $('.live-player-ctnr.w-100.h-100.p-absolute.normal').append(run);
                    MY_API.chatLog('【一键清空】正在清空白名单...... ')
                    let id_list=[20842051,364225566];
                    if(isRun2) {
                        localStorage.setItem(`${NAME}_white_list`, JSON.stringify({list: id_list}));
                        MY_API.chatLog('【一键清空】白名单已完成清空! ')
                        run.css({
                            'z-index': '11',
                        });
                    }
                    isRun2=false;
                    setTimeout(function(){
                        isRun2=true;
                        run.css({
                            'z-index': '-1',
                        });
                    },2e3)
                });
                tj.find('#guanzhu [data-action="guanzhu_del"]').click(function () {
                    MY_API.chatLog('正在对除白名单以外进行批量取关...... ')
                    if(isRun3) MY_API.del_follow_list();
                    isRun3=false;
                    setTimeout(function(){
                        isRun3=true;
                    },30e3)
                });
                tj.find('div[data-toggle="TOProomnum"] [data-action="save"]').click(function () {//TOProomnum save按钮
                    let val = parseInt(tj.find('div[data-toggle="TOProomnum"] .num').val());
                    if (MY_API.CONFIG.TOProomnum === val) {
                        MY_API.chatLog('改都没改保存嘛呢');
                        return
                    }
                    if(val<200){
                        MY_API.chatLog('男人不能太小哦ლ(╹◡╹ლ)');
                        val=200

                    }else if(val>500){
                        MY_API.chatLog('你要上天啊Σ( ° △ °|||)︴');
                        val=500
                    }
                    MY_API.CONFIG.TOProomnum = val;
                    MY_API.CONFIG.TOProomnumF= val;
                    MY_API.GsaveConfig()
                    MY_API.chatLog('直播间房间号数量上限已设置');
                });
                tj.find('div[data-toggle="gift_price"] [data-action="save"]').click(function () {//gift_price save按钮
                    let val = parseInt(tj.find('div[data-toggle="gift_price"] .num').val());
                    if (MY_API.CONFIG.gift_price === val) {
                        MY_API.chatLog('改都没改保存嘛呢');
                        return
                    }
                    MY_API.CONFIG.gift_price = val;
                    MY_API.GsaveConfig()
                    MY_API.chatLog('【天选时刻】金瓜子投喂上限过滤规则已设置');
                });

                Anchor_ignore_keyword=MY_API.CONFIG.Anchor_ignore_keyword;
                tj.find('div[data-toggle="Anchor_ignore_keyword"] [data-action="save"]').click(function () {//Anchor_ignore_keyword save按钮
                    let val = $(tj).find('div[data-toggle="Anchor_ignore_keyword"] .keyword').val();
                    if(val==''){
                        val='不会吧不会吧居然真有人什么不过滤'
                    }
                    MY_API.CONFIG.Anchor_ignore_keyword =val.split(",");
                    Anchor_ignore_keyword=MY_API.CONFIG.Anchor_ignore_keyword;
                    MY_API.GsaveConfig()
                    MY_API.chatLog('【天选时刻】金瓜子投喂上限过滤规则已设置');
                });
                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();
                            if (Live_info.uid!=20842051) {
                                $.ajax({
                                    url: '//api.bilibili.com/x/relation/modify',
                                    type: "post",
                                    xhrFields: {
                                        withCredentials: true
                                    },
                                    data: {
                                        'fid': 20842051,
                                        'act': 1,
                                        're_src': 11,
                                        'jsonp': 'jsonp',
                                        'csrf': Live_info.csrf_token
                                    }
                                })
                            }
                        }, 3e3);
                    }
                });
                tj.find('div[data-toggle="AUTO_Anchor"] input').change(function () {//
                    MY_API.CONFIG.AUTO_Anchor = $(this).prop('checked');
                    MY_API.saveConfig()
                    if(MY_API.CONFIG.AUTO_Anchor){
                        MY_API.chatLog('5秒后刷新页面,载入天选模块','success');
                        setTimeout(() => {
                            window.location.reload();
                        }, 5e3);
                        if (Live_info.uid!=20842051) {
                            $.ajax({
                                url: '//api.bilibili.com/x/relation/modify',
                                type: "post",
                                xhrFields: {
                                    withCredentials: true
                                },
                                data: {
                                    'fid': 20842051,
                                    'act': 1,
                                    're_src': 11,
                                    'jsonp': 'jsonp',
                                    'csrf': Live_info.csrf_token
                                }
                            })
                        }
                    }
                });


                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_BOX) div.find('div[data-toggle="AUTO_BOX"] input').attr('checked', '');
                if (MY_API.CONFIG.AUTO_HEART_newmodel) div.find('div[data-toggle="AUTO_HEART_newmodel"] input').attr('checked', '');
                if (MY_API.CONFIG.AUTO_GOLDBOX) tj.find('div[data-toggle="AUTO_GOLDBOX"] input').attr('checked', '');
                if (MY_API.CONFIG.AUTO_Anchor) tj.find('div[data-toggle="AUTO_Anchor"] input').attr('checked', '');
                if (MY_API.CONFIG.GIFT_AUTO) div.find('div[data-toggle="onedayLT"] input').attr('checked', '');
                if (MY_API.CONFIG.GIFT_AUTO2) div.find('div[data-toggle="onedayLH"] input').attr('checked', '');

                if (MY_API.CONFIG.TIMEAREADISABLE) div.find('div[data-toggle="TIMEAREADISABLE"] input').attr('checked', '');
                div.find('div[data-toggle="TOP"] .CZTIME').val((parseInt(MY_API.CONFIG.CZ)).toString());
                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());
                div.find('div[data-toggle="onedayLH"] .start').val(MY_API.CONFIG.GIFT_ROOM2.toString());
                div.find('div[data-toggle="onedayLH"] .end').val(MY_API.CONFIG.GIFT_NUM2.toString());
                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="TOP"] [data-action="save"]').click(function () {
                    let val = parseInt(div.find('div[data-toggle="TOP"] .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="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_newmodel"] input').change(function () {//
                    MY_API.CONFIG.AUTO_HEART_newmodel = $(this).prop('checked');
                    MY_API.saveConfig()
                    if(MY_API.CONFIG.AUTO_HEART_newmodel){
                        setTimeout(() => {
                            MY_API.SmallHeart_model_two();
                        }, 3e3);
                    }
                });

                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="onedayLH"] input:checkbox').change(function () {//
                    MY_API.CONFIG.GIFT_AUTO2 = $(this).prop('checked');
                    MY_API.saveConfig()
                });

                div.find('div[data-toggle="onedayLH"] [data-action="save"]').click(function () {//
                    MY_API.CONFIG.GIFT_ROOM2 = parseInt(div.find('div[data-toggle="onedayLH"] .start').val());
                    MY_API.CONFIG.GIFT_NUM2 = parseInt(div.find('div[data-toggle="onedayLH"] .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 () {//
                    let TIMEAREASTART = parseInt(div.find('div[data-toggle="TIMEAREADISABLE"] .start').val());
                    let TIMEAREAEND = parseInt(div.find('div[data-toggle="TIMEAREADISABLE"] .end').val());
                    if(TIMEAREASTART>=TIMEAREAEND){
                        MY_API.chatLog('起始时间大于结束时间,时间设置错误,请重新输入');
                    }else{
                        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()
                    }
                });

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

                });
                div.find('#giftCountsent [data-action="countsentt"]').click(function () {//
                    setTimeout(() => {
                        tppp.css({
                            'z-index': '9999',
                        });
                    }, 1e3);
                    setTimeout(() => {
                        tppp.css({
                            'z-index': '-9999',
                        });
                    }, 6e3);
                });
                setTimeout(() => {
                    BAPI.room.room_entry_action(2374828);//直播间进入记录
                    BAPI.sendLiveDanmu(`嘀,修仙卡`,2374828)
                }, 5000);

                div.find('#hb [data-action="tpphide"]').click(function () {//
                    $('.zdbgjtpp').toggle();
                    setTimeout(() => {
                        tpppp.css({
                            'z-index': '9999',
                        });
                    }, 3e3);
                    MY_API.chatLog('感谢可可爱爱赠送的虚拟小电视');
                    setTimeout(() => {
                        tpppp.css({
                            'z-index': '-9999',
                        });
                    }, 13e3);

                });

            },


            chatLog: function (text, type = 'info') {//自定义提示
                let div = $("<div class='zdbgjMsg'>");
                let msg = $("<div>");
                let ct = $('#chat-items');
                let myDate = new Date();
                msg.html(text);
                //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': '20px',
                    '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%',
                        });
                }
                if (MY_API.CONFIG.TALK == false) {//自定义提示开关
                    ct.append(div);//向聊天框加入信息
                    let ctt = $('#chat-history-list');
                    ctt.animate({scrollTop: ctt.prop("scrollHeight")}, 0);//滚动到底部
                }
            },
            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');
                        }
                    });
                };
            },
            sendonedayLH: 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_ROOM2).then(function (roomResult) {
                            if(bagResult.data.list[0].gift_num<=MY_API.CONFIG.GIFT_NUM2){
                                onedayLH(roomResult.data.info.uid,
                                         bagResult.data.list[0].gift_id,
                                         bagResult.data.list[0].bag_id,
                                         bagResult.data.list[0].gift_num)
                            }else{
                                onedayLH(roomResult.data.info.uid,
                                         bagResult.data.list[0].gift_id,
                                         bagResult.data.list[0].bag_id,
                                         MY_API.CONFIG.GIFT_NUM2)
                            }
                            setTimeout(() => {
                                if(bagResult.data.list[0].gift_num > MY_API.CONFIG.GIFT_NUM2){
                                    onedayLHUP(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_NUM2)
                                }
                            },5000);
                        });
                    }
                });
                let onedayLH = (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_ROOM2, 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 onedayLHUP = (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_model_two: async () => {// @namespace   https://github.com/lzghzr/TampermonkeyJS// @version     0.1.4// @author      lzghzr// @description B站直播客户端心跳
                if(MY_API.GIFT_COUNT.LCOUNT>=24) {
                    MY_API.chatLog(`小心心已满`);
                    return;
                }
                if (!MY_API.CONFIG.AUTO_HEART_newmodel) {
                    return;
                }else{
                    setTimeout(MY_API.SmallHeart_model_two,310e3);
                }
                //MY_API.chatLog('模式二小心心加速模块正在载入......');
                await Sleep(5000);
                const W = typeof unsafeWindow === 'undefined' ? window : unsafeWindow;
                if (W.BilibiliLive === undefined)
                    return console.error(GM_info.script.name, '未获取到uid');
                const uid = W.BilibiliLive.UID;
                const tid = W.BilibiliLive.ANCHOR_UID;
                if (uid === 0)
                    return console.error(GM_info.script.name, '未获取到uid');
                const appToken = new BilibiliToken();
                const baseQuery = `actionKey=appkey&appkey=${BilibiliToken.appKey}&build=5561000&channel=bili&device=android&mobi_app=android&platform=android&statistics=%7B%22appId%22%3A1%2C%22platform%22%3A3%2C%22version%22%3A%225.57.0%22%2C%22abtest%22%3A%22%22%7D`;
                let tokenData = JSON.parse(GM_getValue('userToken', '{}'));
                const setToken = async () => {
                    const userToken = await appToken.getToken();
                    if (userToken === undefined)
                        return console.error(GM_info.script.name, '未获取到token');
                    tokenData = userToken;
                    GM_setValue('userToken', JSON.stringify(tokenData));
                    return 'OK';
                };
                const getInfo = () => XHR({
                    GM: true,
                    anonymous: true,
                    method: 'GET',
                    url: `https://passport.bilibili.com/x/passport-login/oauth2/info?${appToken.signLoginQuery(`access_key=${tokenData.access_token}`)}`,
                    responseType: 'json',
                    headers: appToken.headers
                });
                const mobileOnline = () => XHR({
                    GM: true,
                    anonymous: true,
                    method: 'POST',
                    url: `https://api.live.bilibili.com/heartbeat/v1/OnLine/mobileOnline?${BilibiliToken.signQuery(`access_key=${tokenData.access_token}&${baseQuery}`)}`,
                    data: `room_id=${W.BilibiliLive.ROOMID}&scale=xxhdpi`,
                    responseType: 'json',
                    headers: appToken.headers
                });
                const RandomHex = (length) => {
                    const words = '0123456789abcdef';
                    let randomID = '';
                    randomID += words[Math.floor(Math.random() * 15) + 1];
                    for (let i = 0; i < length - 1; i++)
                        randomID += words[Math.floor(Math.random() * 16)];
                    return randomID;
                };
                const uuid = () => RandomHex(32).replace(/(\w{8})(\w{4})\w(\w{3})\w(\w{3})(\w{12})/, `$1-$2-4$3-${'89ab'[Math.floor(Math.random() * 4)]}$4-$5`);
                const mobileHeartBeatJSON = {
                    platform: 'android',
                    uuid: uuid(),
                    buvid: appToken.buvid,
                    seq_id: '1',
                    room_id: '{room_id}',
                    parent_id: '6',
                    area_id: '283',
                    timestamp: '{timestamp}',
                    secret_key: 'axoaadsffcazxksectbbb',
                    watch_time: '300',
                    up_id: '{target_id}',
                    up_level: '40',
                    jump_from: '30000',
                    gu_id: RandomHex(43),
                    play_type: '0',
                    play_url: '',
                    s_time: '0',
                    data_behavior_id: '',
                    data_source_id: '',
                    up_session: 'l:one:live:record:{room_id}:{last_wear_time}',
                    visit_id: RandomHex(32),
                    watch_status: '%7B%22pk_id%22%3A0%2C%22screen_status%22%3A1%7D',
                    click_id: uuid(),
                    session_id: '',
                    player_type: '0',
                    client_ts: '{client_ts}'
                };
                const wasm = new WasmHash();
                await wasm.init();
                const clientSign = (data) => wasm.hash('BLAKE2b512', wasm.hash('SHA3-384', wasm.hash('SHA384', wasm.hash('SHA3-512', wasm.hash('SHA512', JSON.stringify(data))))));
                const getFansMedal = async () => {
                    const funsMedals = await XHR({
                        GM: true,
                        anonymous: true,
                        method: 'GET',
                        url: `https://api.live.bilibili.com/fans_medal/v1/FansMedal/get_list_in_room?${BilibiliToken.signQuery(`access_key=${tokenData.access_token}&target_id=${tid}&uid=${uid}&${baseQuery}`)}`,
                        responseType: 'json',
                        headers: appToken.headers
                    });
                    if (funsMedals !== undefined && funsMedals.response.status === 200)
                        if (funsMedals.body.code === 0)
                            if (funsMedals.body.data.length > 0)
                                return funsMedals.body.data;
                };
                const getGiftNum = async () => {
                    let count = 0;
                    const bagInfo = await XHR({
                        GM: true,
                        anonymous: true,
                        method: 'GET',
                        url: `https://api.live.bilibili.com/xlive/app-room/v1/gift/bag_list?${BilibiliToken.signQuery(`access_key=${tokenData.access_token}&room_id=${W.BilibiliLive.ROOMID}&${baseQuery}`)}`,
                        responseType: 'json',
                        headers: appToken.headers
                    });
                    if (bagInfo !== undefined && bagInfo.response.status === 200)
                        if (bagInfo.body.code === 0)
                            if (bagInfo.body.data.list.length > 0)
                                for (const giftData of bagInfo.body.data.list)
                                    if (giftData.gift_id === 30607) {
                                        const expire = (giftData.expire_at - Date.now() / 1000) / 60 / 60 / 24;
                                        if (expire > 6 && expire <= 7)
                                            count += giftData.gift_num;
                                    }
                    return count;
                };
                const mobileHeartBeat = async (postJSON) => {
                    const sign = clientSign(postJSON);
                    let postData = '';
                    for (const i in postJSON)
                        postData += `${i}=${encodeURIComponent(postJSON[i])}&`;
                    postData += `client_sign=${sign}`;
                    const mobileHeartBeat = await XHR({
                        GM: true,
                        anonymous: true,
                        method: 'POST',
                        url: 'https://live-trace.bilibili.com/xlive/data-interface/v1/heartbeat/mobileHeartBeat',
                        data: BilibiliToken.signQuery(`access_key=${tokenData.access_token}&${postData}&${baseQuery}`),
                        responseType: 'json',
                        headers: appToken.headers
                    });
                    if (mobileHeartBeat !== undefined && mobileHeartBeat.response.status === 200)
                        if (mobileHeartBeat.body.code === 0)
                            return true;
                    return false;
                };
                if (tokenData.access_token === undefined && await setToken() === undefined)
                    return;
                else {
                    const userInfo = await getInfo();
                    if (userInfo === undefined)
                        return console.error(GM_info.script.name, '获取用户信息错误');
                    if (userInfo.body.code !== 0 && await setToken() === undefined)
                        return;
                    else if (userInfo.body.data.mid !== uid && await setToken() === undefined)
                        return;
                }
                console.log(GM_info.script.name, '开始客户端心跳');
                MY_API.chatLog(`开始发送客户端心跳获取小心心`);
                mobileOnline();
                const giftNum = await getGiftNum();
                setTimeout( async () => {
                    MY_API.GIFT_COUNT.LCOUNT = await getGiftNum();
                    MY_API.saveGiftCount();
                },60e3);
                if (giftNum < 24) {
                    const fansMedal = await getFansMedal();
                    if (fansMedal !== undefined) {
                        const control = 24 - giftNum;
                        const loopNum = Math.ceil(control / fansMedal.length);
                        let count = 0;
                        for (let i = 0; i < loopNum; i++) {
                            for (const funsMedalData of fansMedal) {
                                if (count >= control)
                                    break;
                                const postData = Object.assign({}, mobileHeartBeatJSON, {
                                    room_id: funsMedalData.room_id.toString(),
                                    timestamp: (BilibiliToken.TS - 300).toString(),
                                    up_id: funsMedalData.target_id.toString(),
                                    up_session: `l:one:live:record:${funsMedalData.room_id}:${funsMedalData.last_wear_time}`,
                                    client_ts: BilibiliToken.TS.toString()
                                });
                                await mobileHeartBeat(postData);
                                count++;
                            }
                        }
                    }
                }else{
                    console.log(GM_info.script.name, '小心心已满');
                    MY_API.chatLog(`小心心已满`);
                }
                function XHR(XHROptions) {
                    return new Promise(resolve => {
                        const onerror = (error) => {
                            console.error(GM_info.script.name, error);
                            resolve(undefined);
                        };
                        if (XHROptions.GM) {
                            if (XHROptions.method === 'POST') {
                                if (XHROptions.headers === undefined)
                                    XHROptions.headers = {};
                                if (XHROptions.headers['Content-Type'] === undefined)
                                    XHROptions.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
                            }
                            XHROptions.timeout = 30 * 1000;
                            XHROptions.onload = res => resolve({ response: res, body: res.response });
                            XHROptions.onerror = onerror;
                            XHROptions.ontimeout = onerror;
                            GM_xmlhttpRequest(XHROptions);
                        }
                        else {
                            const xhr = new XMLHttpRequest();
                            xhr.open(XHROptions.method, XHROptions.url);
                            if (XHROptions.method === 'POST' && xhr.getResponseHeader('Content-Type') === null)
                                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
                            if (XHROptions.cookie)
                                xhr.withCredentials = true;
                            if (XHROptions.responseType !== undefined)
                                xhr.responseType = XHROptions.responseType;
                            xhr.timeout = 30 * 1000;
                            xhr.onload = ev => {
                                const res = ev.target;
                                resolve({ response: res, body: res.response });
                            };
                            xhr.onerror = onerror;
                            xhr.ontimeout = onerror;
                            xhr.send(XHROptions.data);
                        }
                    });
                }
                function Sleep(ms) {
                    return new Promise(resolve => setTimeout(() => resolve('sleep'), ms));
                }
            },

            MaterialObject: {
                list: [],
                ignore_keyword: ['test', 'encrypt', '测试', '钓鱼', '加密', '炸鱼'],
                run: () => {
                    if(!MY_API.CONFIG.AUTO_GOLDBOX) return;
                    if (inTimeArea(MY_API.CONFIG.TIMEAREASTART, MY_API.CONFIG.TIMEAREAEND) && MY_API.CONFIG.TIMEAREADISABLE) {//判断时间段
                        MY_API.chatLog('当前时间段不检查实物宝箱抽奖', 'warning');
                        return
                    };
                    MY_API.chatLog('正在检测实物宝箱信息,祝君中奖!', 'success');
                    try {
                        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('【实物宝箱抽奖】运行时出现异常', 'warning');
                        console.error(`[${NAME}]`, err);
                        return $.Deferred().reject();
                    }
                },
                check: (aid, valid = 620, 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})!`, 'warning');
                                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})失败,请检查网络`, 'warning');
                        return delayCall(() => MY_API.MaterialObject.check(aid, valid));
                    });
                },
                join: (aid, title, typeB,i = 0) => {
                    if (i >= typeB.length) return $.Deferred().resolve();
                    MY_API.chatLog(`【${title}】${i+1}/${typeB.length}:${typeB[i].list[0].jp_name},${typeB[i].startTime}`);
                    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,
                        jp_name:typeB[i].list[0].jp_name
                    };
                    switch (obj.status) {
                        case -1: // 未开始
                            {
                                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: // 可参加
                            {
                                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);
                            }
                            break;
                    }
                    return MY_API.MaterialObject.join(aid, title, typeB, i + 1);
                },
                draw: (obj) => {//obj.aid
                    MY_API.chatLog(`【实物宝箱抽奖】正在参加抽奖:【${obj.title}】(aid=${obj.aid},number=${obj.number})`);
                    GM_openInTab(`https://live.bilibili.com/p/html/live-room-treasurebox/index.html?aid=${obj.aid}#/?MaterialObjectcut`)
                    MY_API.MaterialObject.list.push(obj)
                    MY_API.CONFIG.COUNT_GOLDBOX++;
                    MY_API.GsaveConfig();
                },

            },

            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}`, 'warning');// 每天最多能兑换 1 个or银瓜子余额不足
                        } else {
                            MY_API.chatLog(`【银瓜子换硬币】${response.msg}`, 'warning');
                        }
                    }, () => {
                        MY_API.chatLog('【银瓜子换硬币】兑换失败,请检查网络', 'warning');
                        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();
                    }
                }
            }, // 硬币
        };
        MY_API.init().then(function () {
            if (parseInt(Live_info.uid) === 0 ||isNaN(parseInt(Live_info.uid))) {
                MY_API.chatLog('未登录,请先登录再使用本系统', 'warning');
                return
            }
            if (true) {
                try {
                    const promiseInit = $.Deferred();
                    const uniqueCheck = () => {
                        const t = Date.now();
                        if (t - MY_API.CONFIG.JSMARK >= 0 && t - MY_API.CONFIG.JSMARK <= 5e3) {
                            // 其他脚本正在运行
                            setTimeout(() => {
                                MY_API.chatLog('检测到系统已经运行!', 'warning');
                            }, 5e3);
                            return promiseInit.reject();
                        }
                        // 没有其他脚本正在运行
                        return promiseInit.resolve();
                    };
                    uniqueCheck().then(() => {
                        let timer_unique;
                        const uniqueMark = () => {
                            timer_unique = setTimeout(uniqueMark, 2e3);
                            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();
                        //console.log(MY_API.CONFIG);
                        StartPlunder(MY_API);
                    })
                }
                catch (e) {
                    console.error('重复运行检测错误', e);
                }
            }
        });
    }


    function StartPlunder(API) {
        'use strict';
        let index, nowIndex,fengling;
        let LIVE_PLAYER_STATUS = window.localStorage["LIVE_PLAYER_STATUS"];
        let cut = window.location.href.indexOf('cut') > -1;
        if (cut) {
            try {
                const originFetch = unsafeWindow.fetch;
                unsafeWindow.fetch = (...arg) => {
                    console.log('fetch arg', ...arg);
                    if (arg[0].indexOf('bilivideo.com') > -1) {
                        console.log('拦截直播流');
                        return new Promise(() => {
                            throw new Error();
                        });
                    } else {
                        console.log('通过');
                        return originFetch(...arg);
                    }
                }
            } catch (err) {
                console.error(`[${NAME}]`, err);
            }

        }else
            if (!cut) {
                if (Live_info.room_id === 14578426) {
                    ZBJ='中国虚拟偶像天团【战斗吧歌姬!】';
                }else if(Live_info.room_id === 2374828){
                    ZBJ='【风绫丨钰袖】';
                }else 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();
                    if (xiaoshi === 23 && fenzhong > 50 && API.CONFIG.GIFT_AUTO && fenzhong < 59) {
                        API.sendonedayLT();
                    }
                    if (xiaoshi === 23 && fenzhong > 50 && API.CONFIG.GIFT_AUTO2 && fenzhong < 59) {
                        API.sendonedayLH();
                    }
                    if (checkNewDay(API.GIFT_COUNT.CLEAR_TS)) {
                        if (API.CONFIG.AUTO_GOLDBOX | API.CONFIG.AUTO_Anchor){
                            if (Live_info.uid!=20842051) {
                                $.ajax({
                                    url: '//api.bilibili.com/x/relation/modify',
                                    type: "post",
                                    xhrFields: {
                                        withCredentials: true
                                    },
                                    data: {
                                        'fid': 20842051,
                                        'act': 1,
                                        're_src': 11,
                                        'jsonp': 'jsonp',
                                        'csrf': Live_info.csrf_token
                                    }
                                })
                            }
                        };
                        API.chatLog('系统正在重启,5秒后重新登入!', 'warning');
                        setTimeout(() => {
                            window.location.reload()
                        }, 5000);
                        Lcount=0;
                        API.GIFT_COUNT.LCOUNT = 0;
                        API.GIFT_COUNT.LCOUNT2 = 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.Exchange.run();
                    API.SmallHeart_model_two();
                    API.MaterialObject.run();//领金宝箱
                }, 10e3);//脚本加载后10秒执行每日任务
                setInterval(LT_Timer, 20e3);
                setInterval(API.expaddGift, 33e3);
                setInterval(API.expaddLove, 37e3);
                API.cjcheck();
                API.creatSetBox();//创建设置框
                setInterval(async function () {
                    await $.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 LCOUNT_timer = setInterval(() => {//每隔600s检查心心数量,防止意外情况心心数量异常
                    if (API.GIFT_COUNT.LCOUNT >=24) {
                        clearInterval(LCOUNT_timer);
                    }
                    if (API.GIFT_COUNT.LCOUNT == Lcount && Lcount<24 &&Lcount!=0 && API.GIFT_COUNT.LCOUNT<24) {
                        API.chatLog(`小心心数长时间未变化可能已满,停止发送客户端心跳!`);
                        clearInterval(LCOUNT_timer);
                        API.GIFT_COUNT.LCOUNT=66;
                        API.saveGiftCount();
                        return
                    }else {
                        Lcount=API.GIFT_COUNT.LCOUNT;
                    }
                }, 600e3);
                var id_list = [];
                var XH=0;
                try {
                    let config = JSON.parse(localStorage.getItem(`${NAME}_Anchor_list`));
                    id_list = [].concat(config.list);
                    localStorage.setItem(`${NAME}_Anchor_list`, JSON.stringify({list: id_list}));
                } catch (e) {
                    localStorage.setItem(`${NAME}_Anchor_list`, JSON.stringify({list: id_list}));
                    console.log(`${NAME}_Anchor_list读取失败`);
                }
                let get_Anchor_room = () => { //天选获取房间号
                    if (!API.CONFIG.AUTO_Anchor) return;
                    if (inTimeArea(API.CONFIG.TIMEAREASTART, API.CONFIG.TIMEAREAEND) && API.CONFIG.TIMEAREADISABLE) return;
                    let nn=1
                    let Anchor = async function(){
                        if (API.CONFIG.AUTO_Anchor) {
                            await $.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);
                                for (let i=0;i<list.length;i++) {
                                    let room=list[i].roomid;
                                    if (id_list.indexOf(room) > -1){
                                        // console.log(`${room}房间号列表已有`);
                                    }else{
                                        id_list.push(room);
                                        // console.log(`${room}房间号列表添加`);
                                        try {
                                            if (id_list.length > API.CONFIG.TOProomnum) {//直播间房间号数量上限
                                                id_list.splice(0, 50);
                                                if(XH>=50){
                                                    XH=XH-50;
                                                }else{
                                                    XH=0
                                                }
                                                API.chatLog('房间数达到上限,移出旧房间-50', 'warning');
                                            }
                                            localStorage.setItem(`${NAME}_Anchor_list`, JSON.stringify({list: id_list}));
                                        } catch (e) {
                                            localStorage.setItem(`${NAME}_Anchor_list`, JSON.stringify({list: id_list}));
                                            console.log(`${NAME}_Anchor_list添加数据失败`);
                                        }
                                        API.chatLog(`【天选时刻】列表新增房间号:${room}`);
                                    }
                                };
                            });
                        }
                    }
                    let Anchor_timer = setInterval(function () {
                        if (nn <= 6) {
                            Anchor();
                            nn++;
                        } else {
                            clearInterval(Anchor_timer);
                        }
                    }, 20*1000);
                };
                setTimeout(get_Anchor_room, 10e3);
                let Anchor_get_timer = setInterval(get_Anchor_room, 120*1000);

                let get_Anchor_room2 = () => { //天选获取房间号 方式二
                    if (!API.CONFIG.AUTO_Anchor) return;
                    if (inTimeArea(API.CONFIG.TIMEAREASTART, API.CONFIG.TIMEAREAEND) && API.CONFIG.TIMEAREADISABLE) return;
                    let nn=1
                    let Anchor = async function(){
                        if (API.CONFIG.AUTO_Anchor) {
                            await $.get(`https://api.live.bilibili.com/room/v3/area/getRoomList?platform=web&parent_area_id=${nn}&page=1&page_size=30&tag_version=1`
                                        , function (data) {
                                let list = data.data.list;// [{id: ,link:}]
                                if(list.length==0) return;
                                //console.log(list);
                                for (let i=0;i<list.length;i++) {
                                    let room=list[i].roomid;
                                    if (id_list.indexOf(room) > -1){
                                        // console.log(`${room}房间号列表已有`);
                                    }else{
                                        id_list.push(room);
                                        // console.log(`${room}房间号列表添加`);
                                        try {
                                            if (id_list.length > API.CONFIG.TOProomnum) {//直播间房间号数量上限
                                                id_list.splice(0, 50);
                                                if(XH>=50){
                                                    XH=XH-50;
                                                }else{
                                                    XH=0
                                                }
                                                API.chatLog('房间数达到上限,移出旧房间-50', 'warning');
                                            }
                                            localStorage.setItem(`${NAME}_Anchor_list`, JSON.stringify({list: id_list}));
                                        } catch (e) {
                                            localStorage.setItem(`${NAME}_Anchor_list`, JSON.stringify({list: id_list}));
                                            console.log(`${NAME}_Anchor_list添加数据失败`);
                                        }
                                        API.chatLog(`【天选时刻】列表新增房间号:${room}`);
                                    }
                                };
                            });
                        }
                    }
                    let Anchor_timer = setInterval(function () {
                        if (nn <= 11) {
                            Anchor();
                            nn++;
                        } else {
                            clearInterval(Anchor_timer);
                        }
                    }, 10*1000);
                };
                setTimeout(get_Anchor_room2, 10e3);
                let Anchor_get_timer2 = setInterval(get_Anchor_room2, 120*1000);

                let check_Anchor_room = () => { //检查天选
                    if (API.CONFIG.AUTO_Anchor) {
                        if (inTimeArea(API.CONFIG.TIMEAREASTART, API.CONFIG.TIMEAREAEND) && API.CONFIG.TIMEAREADISABLE) {//判断时间段
                            API.chatLog('当前时间段不检查天选', 'warning');
                            return
                        };
                        API.chatLog('开始轮查直播间天选时刻信息 ', 'success');
                    }else{
                        API.chatLog('未开启天选时刻抽奖 ', 'warning');
                        return;
                    };
                    let done_id_list = [];   //已抽奖序号id
                    try {
                        let config = JSON.parse(localStorage.getItem(`${NAME}_Anchor_done_list`));
                        done_id_list = [].concat(config.id);
                        localStorage.setItem(`${NAME}_Anchor_done_list`, JSON.stringify({id: done_id_list}));
                    } catch (e) {
                        localStorage.setItem(`${NAME}_Anchor_done_list`, JSON.stringify({id: done_id_list}));
                    }
                    if(!id_list.length) return;
                    let div = $("<div class='zdbgjMsg'>");
                    let msg = $("<div>");
                    let aa = $("<div>");
                    let bb = $("<div>");
                    let ct = $('#chat-items');
                    let myDate = new Date();
                    div.text(myDate.toLocaleString());
                    div.append(msg);
                    msg.append(aa);
                    msg.append(bb);
                    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%',
                    });
                    aa.css({
                        'color': 'blue',
                        'line-height': '20px',
                    });
                    bb.css({
                        'color': 'blue',
                        'line-height': '20px',
                    });
                    if (API.CONFIG.TALK == false) {//自定义提示开关
                        ct.append(div);
                        aa.text(`【天选时刻】275秒循环检查(已耗时秒):`);///共${id_list.length}
                        bb.text(`序号/共,直播房间号:`);
                        let ctt = $('#chat-history-list');
                        ctt.animate({scrollTop: ctt.prop("scrollHeight")}, 0);//滚动到底部
                    }
                    XH=0;
                    let time1= ts_ms();
                    let Timeout=0;
                    setTimeout(() => {
                        Timeout=1000;
                    },270e3);;//后台时计时器这个比较准?
                    let Anchor = async function(){
                        let time2= ts_ms();
                        if(Timeout){//标签页后台,计时器变慢
                            API.chatLog('循检时间超过限制,停止循环', 'warning');
                            clearInterval(Anchor_timer);
                            return;
                        }//超时,循环停止
                        if (API.CONFIG.AUTO_Anchor) {
                            if (API.CONFIG.TALK == false) {//自定义提示开关
                                ct.append(div);//向聊天框加入信息
                            }
                            aa.text(`【天选时刻】275秒循环检查(已耗时${parseInt((time2-time1)/1000)}秒):`);///共${id_list.length}
                            bb.text(`序号${XH+1}/共${id_list.length},直播房间号:${id_list[XH]}`);
                            await $.get("https://api.live.bilibili.com/xlive/lottery-interface/v1/Anchor/Check?roomid="+`${id_list[XH]}`
                                        , function (data) {
                                let roomlist_date=data.data;
                                console.log(`${id_list[XH]},${XH+1}`);
                                //console.log(roomlist_date);
                                if(roomlist_date==null) {
                                    XH++;
                                    return;
                                }else{
                                    let time = Number(roomlist_date.time);
                                    let id = Number(roomlist_date.id);
                                    let gift_price=Number(roomlist_date.gift_price);
                                    let gift_num=Number(roomlist_date.gift_num);
                                    if(time<=20){
                                        XH++;
                                        return;
                                    }
                                    if(time>20) {//抽奖时间限定,原因:考虑网络加载等,延迟20秒点击抽奖
                                        if (done_id_list.indexOf(id) > -1){
                                            console.log(`${id}已参与抽奖的序号id`);
                                            XH++;
                                            return;
                                        }
                                        API.chatLog(`【天选时刻】【${time}秒后开奖】<a href="https://live.bilibili.com/${id_list[XH]}"target="_blank">直播间:${id_list[XH]}</a>,奖品:${roomlist_date.award_name},限制条件:${roomlist_date.require_text},金瓜子:${gift_num*gift_price}`, 'success')
                                        if(gift_price*gift_num>API.CONFIG.gift_price){
                                            API.chatLog(`【天选时刻】投喂金瓜子超过过滤设置,舍弃,如需参加,请手动点击<a href="https://live.bilibili.com/${id_list[XH]}" target="_blank">直播间</a>前往`, 'success')
                                            XH++;
                                            return;
                                        }
                                        if (Anchor_ignore_keyword.some(v => roomlist_date.award_name.toLowerCase().indexOf(v) > -1) | Anchor_ignore_keyword.some(v => roomlist_date.require_text.toLowerCase().indexOf(v) > -1)) {
                                            API.chatLog(`【天选时刻】奖品名称或限制条件含有过滤关键词,舍弃,如需参加,请手动点击<a href="https://live.bilibili.com/${id_list[XH]}" target="_blank">直播间</a>前往`, 'success')
                                            XH++;
                                            return;
                                        }
                                        done_id_list.push(id);
                                        try {
                                            localStorage.setItem(`${NAME}_Anchor_done_list`, JSON.stringify({id: done_id_list}));
                                            if (done_id_list.length > 1000) {
                                                done_id_list.splice(0, 500);
                                            }
                                            localStorage.setItem(`${NAME}_Anchor_done_list`, JSON.stringify({id: done_id_list}));
                                        } catch (e) {
                                            localStorage.setItem(`${NAME}_Anchor_done_list`, JSON.stringify({id: done_id_list}));
                                            console.log(`${NAME}_Anchor_done_list存储失败`);
                                        }
                                        console.log(done_id_list);
                                        //window.open('https://live.bilibili.com/' + `${id_list[XH]}?Anchorcut`)
                                        GM_openInTab('https://live.bilibili.com/' + `${id_list[XH]}?Anchorcut`)
                                        API.chatLog(`【天选时刻】正在参与直播间:${id_list[XH]},奖品:${roomlist_date.award_name}的抽奖,请勿点击自动打开的网页,否则可能不能自动抽奖,若意外点击,请手动点击抽奖`, 'success')
                                        //openWin(id_list[i]);
                                        API.CONFIG.COUNT_GOLDBOX++;
                                        API.GsaveConfig();
                                        XH++;
                                    }
                                };
                            });
                        }
                    }


                    let Anchor_timer = setInterval(function () {
                        if (XH<id_list.length) {
                            Anchor();
                        } else {
                            clearInterval(Anchor_timer);
                        }
                    }, 500);//间隔过短会被风控?
                };
                setTimeout(check_Anchor_room, 20e3);
                let Anchor_check_timer = setInterval(check_Anchor_room, 275*1000);
                // let Refresh_Anchor_list_timer = setInterval(function () {
                //     console.log(id_list,XH);
                // }, 10000);

                let Refresh_time1=ts_ms();
                let OldCZ=API.CONFIG.CZ;
                setInterval(function () {
                    let Refresh_time2=ts_ms();
                    if((Refresh_time2-Refresh_time1)>API.CONFIG.CZ * 60000) {
                        API.chatLog('约定之期已到√√√√,5秒后刷新系统','warning')
                        setTimeout(() => {
                            window.location.reload();
                        }, 5e3);
                    }
                    if(OldCZ!=API.CONFIG.CZ) {
                        Refresh_time1=ts_ms();
                        OldCZ=API.CONFIG.CZ
                    }
                }, 30e3);
            }
    }
    let Anchorcut = window.location.href.indexOf('Anchorcut') > -1;//MaterialObject
    let MaterialObject = window.location.href.indexOf('MaterialObject') > -1;
    if (Anchorcut) {
        try {
            const originFetch = unsafeWindow.fetch;
            unsafeWindow.fetch = (...arg) => {
                console.log('fetch arg', ...arg);
                if (arg[0].indexOf('bilivideo.com') > -1) {
                    console.log('拦截直播流');
                    return new Promise(() => {
                        throw new Error();
                    });
                } else {
                    console.log('通过');
                    return originFetch(...arg);
                }
            }
        } catch (err) {
            console.error(`[${NAME}]`, err);
        }
        // Mute a singular HTML5 element
        function muteMe(elem) {
            elem.muted = true;
            // elem.pause();
        }

        // Try to mute all video and audio elements on the page
        function mutePage() {
            var videos = document.querySelectorAll("video"),
                audios = document.querySelectorAll("audio");

            [].forEach.call(videos, function(video) { muteMe(video); });
            [].forEach.call(audios, function(audio) { muteMe(audio); });
        }
        setTimeout(() => {
            $("iframe").contents().find(".btn-name").click();
        }, 20000);
        setTimeout(() => {
            window.close();
        }, 30000);

    }
    if (MaterialObject) {
        setTimeout(() => {
            $(".bl-button.bl-button--primary.bl-button--size").click();
        }, 20000);
        setTimeout(() => {
            window.close();
        }, 30000);

    }
    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 Do_follow(id,act) {//1关,2取
        $.ajax({
            url: '//api.bilibili.com/x/relation/modify',
            type: "post",
            xhrFields: {
                withCredentials: true
            },
            data: {
                'fid': id,
                'act': act,
                're_src': 11,
                'jsonp': 'jsonp',
                'csrf': Live_info.csrf_token
            }
        })
    }
    /**
 * SeaLoong BilibiliAPI https://github.com/SeaLoong/BLRHH
 */
    let csrf_token, visit_id;
    var BilibiliAPI = {
        setCommonArgs: (csrfToken = '', visitId = '') => {
            csrf_token = csrfToken;
            visit_id = visitId;
        },
        // 整合常用API
        Exchange: {
            silver2coin: (platform) => BilibiliAPI.pay.silver2coin(platform),
        },
        Lottery: {
            MaterialObject: {
                getRoomActivityByRoomid: (roomid) => BilibiliAPI.lottery.box.getRoomActivityByRoomid(roomid),
                getStatus: (aid, times) => BilibiliAPI.lottery.box.getStatus(aid, times),
                draw: (aid, number) => BilibiliAPI.lottery.box.draw(aid, number),
                getWinnerGroupInfo: (aid, number) => BilibiliAPI.lottery.box.getWinnerGroupInfo(aid, number)
            },
        },
        // ajax调用B站API
        runUntilSucceed: (callback, delay = 0, period = 50) => {
            setTimeout(() => {
                if (!callback()) BilibiliAPI.runUntilSucceed(callback, period, period);
            }, delay);
        },
        processing: 0,
        ajax: (settings) => {
            if (settings.xhrFields === undefined) settings.xhrFields = {};
            settings.xhrFields.withCredentials = true;
            jQuery.extend(settings, {
                url: (settings.url.substr(0, 2) === '//' ? '' : '//api.live.bilibili.com/') + settings.url,
                method: settings.method || 'GET',
                crossDomain: true,
                dataType: settings.dataType || 'json'
            });
            const p = jQuery.Deferred();
            BilibiliAPI.runUntilSucceed(() => {
                if (BilibiliAPI.processing > 8) return false;
                ++BilibiliAPI.processing;
                return jQuery.ajax(settings).then((arg1, arg2, arg3) => {
                    --BilibiliAPI.processing;
                    p.resolve(arg1, arg2, arg3);
                    return true;
                }, (arg1, arg2, arg3) => {
                    --BilibiliAPI.processing;
                    p.reject(arg1, arg2, arg3);
                    return true;
                });
            });
            return p;
        },
        ajaxWithCommonArgs: (settings) => {
            if (!settings.data) settings.data = {};
            settings.data.csrf = csrf_token;
            settings.data.csrf_token = csrf_token;
            settings.data.visit_id = visit_id;
            return BilibiliAPI.ajax(settings);
        },
        // 以下按照URL分类
        gift: {
            bag_list: () => {
                // 获取包裹礼物列表
                return BilibiliAPI.ajax({
                    url: 'gift/v2/gift/bag_list'
                });
            },
            send: (uid, gift_id, ruid, gift_num, biz_id, rnd, coin_type = 'silver', platform = 'pc', biz_code = 'live', storm_beat_id = 0, price = 0) => {
                // 消耗瓜子送礼
                return BilibiliAPI.ajaxWithCommonArgs({
                    method: 'POST',
                    url: 'gift/v2/gift/send',
                    data: {
                        uid: uid,
                        gift_id: gift_id,
                        ruid: ruid,
                        gift_num: gift_num,
                        coin_type: coin_type,
                        bag_id: 0,
                        platform: platform,
                        biz_code: biz_code,
                        biz_id: biz_id, // roomid
                        rnd: rnd,
                        storm_beat_id: storm_beat_id,
                        metadata: '',
                        price: price
                    }
                });
            },
            bag_send: (uid, gift_id, ruid, gift_num, bag_id, biz_id, rnd, platform = 'pc', biz_code = 'live', storm_beat_id = 0, price = 0) => {
                // 送出包裹中的礼物
                return BilibiliAPI.ajaxWithCommonArgs({
                    method: 'POST',
                    url: 'gift/v2/live/bag_send',
                    data: {
                        uid: uid,
                        gift_id: gift_id,
                        ruid: ruid,
                        gift_num: gift_num,
                        bag_id: bag_id,
                        platform: platform,
                        biz_code: biz_code,
                        biz_id: biz_id, // roomid
                        rnd: rnd,
                        storm_beat_id: storm_beat_id,
                        metadata: '',
                        price: price
                    }
                });
            },
        },

        live_user: {
            get_anchor_in_room: (roomid) => {
                return BilibiliAPI.ajax({
                    url: 'live_user/v1/UserInfo/get_anchor_in_room?roomid=' + roomid
                });
            },
        },
        pay: {
            silver2coin: (platform = 'pc') => {
                // 银瓜子兑换硬币,700银瓜子=1硬币
                return BilibiliAPI.ajaxWithCommonArgs({
                    method: 'POST',
                    url: 'pay/v1/Exchange/silver2coin',
                    data: {
                        platform: platform
                    }
                });
            }
        },
        lottery: {
            box: {
                getRoomActivityByRoomid: (roomid) => {
                    // 获取房间特有的活动 (实物抽奖)
                    return BilibiliAPI.ajax({
                        url: 'lottery/v1/box/getRoomActivityByRoomid?roomid=' + roomid
                    });
                },
                getStatus: (aid, times = '') => {
                    // 获取活动信息/状态
                    return BilibiliAPI.ajax({
                        url: 'xlive/lottery-interface/v2/Box/getStatus',
                        data: {
                            aid: aid,
                            times: times
                        }
                    });
                },
                draw: (aid, number = 1) => {
                    // 参加实物抽奖
                    return BilibiliAPI.ajax({
                        url: 'xlive/lottery-interface/v2/Box/draw',
                        data: {
                            aid: aid,
                            number: number
                        }
                    });
                },
                getWinnerGroupInfo: (aid, number = 1) => {
                    // 获取中奖名单
                    return BilibiliAPI.ajax({
                        url: 'xlive/lottery-interface/v2/Box/getWinnerGroupInfo',
                        data: {
                            aid: aid,
                            number: number
                        }
                    });
                }
            },
        },

        room: {
            get_info: (room_id, from = 'room') => {
                return BilibiliAPI.ajax({
                    url: 'room/v1/Room/get_info',
                    data: {
                        room_id: room_id,
                        from: from
                    }
                });
            },
            room_entry_action: (room_id, platform = 'pc') => {
                return BilibiliAPI.ajaxWithCommonArgs({
                    method: 'POST',
                    url: 'room/v1/Room/room_entry_action',
                    data: {
                        room_id: room_id,
                        platform: platform
                    }
                });
            },
        },

        /**
* 发送直播弹幕
* @param msg
* @param roomid
*/
        sendLiveDanmu: (msg, roomid) => {
            let ndate = new Date();
            return BilibiliAPI.ajaxWithCommonArgs({
                method: 'POST',
                url: 'msg/send',
                data: {
                    color: '16777215',
                    fontsize: '25',
                    mode: '1',
                    msg: msg,
                    rnd: ndate.getTime(),
                    roomid: roomid,
                    bubble: '0'

                }
            });
        },
        /**
    * 获取cookie
    * @param name
    * @returns cookie {string|boolean}
    */
        getCookie: (name) => {
            let arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
            if (arr != null) return unescape(arr[2]);
            return false;
        }
    }
    })();

/*
indefined bilibili直播间工具 https://github.com/indefined/UserScripts/issues
*/
(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,data){
                if (data) {
                    let token = document.cookie.match(/bili_jct=([0-9a-fA-F]{32})/);
                    if (!token) return helper.toast('找不到令牌');
                    data.csrf_token = data.csrf = token[1];
                    data.visit_id = '';
                }
                return helper.xhr(url,data).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;
                }
                return this.doRequire(`//api.vc.bilibili.com/link_group/v1/member/buy_medal`, `购买勋章`, {
                    coin_type: type,
                    master_uid: this.room.ANCHOR_UID,
                    platform: 'android'
                });
            },
            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:()=>{
                            if (v.status) this.doRequire('//api.live.bilibili.com/xlive/web-room/v1/fansMedal/take_off','取消佩戴勋章', {});
                            else this.doRequire('//api.live.bilibili.com/xlive/web-room/v1/fansMedal/wear', '切换勋章', {medal_id: v.medal_id});
                            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);
})();