Greasy Fork

Greasy Fork is available in English.

猫耳迎宾机器人

一个简单的迎宾机器人

当前为 2024-08-28 提交的版本,查看 最新版本

// ==UserScript==
// @name         猫耳迎宾机器人
// @version      1.5
// @description  一个简单的迎宾机器人
// @author       洋子
// @match        https://fm.missevan.com/live/*
// @icon         https://static.maoercdn.com/avatars/202408/25/2bf1715cfc845d8b4da511d8f5345fec210801.jpg?x-oss-process=style/avatar
// @grant        none
// @namespace    http://greasyfork.icu/users/1357490
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/index.js
// ==/UserScript==


(function() {
    'use strict';

    // 提示用户输入房间号
    let roomId = prompt("请输入房间号:", "457623614");
    if (!roomId) {
        alert("房间号不能为空,脚本终止运行!");
        return;
    }

    // 存储已经欢迎过的用户列表
    let welcomedUsers = [];

    // 存储用户名与昵称的映射表 (如果有的话)
    let nameWords = {
        "某用户名": "昵称"
    };

    // 模拟过滤消息中的屏蔽词
    function filterMessage(message, filterWords) {
        filterWords.forEach(word => {
            let regex = new RegExp(word, 'g');
            message = message.replace(regex, '***');
        });
        return message;
    }

    // 屏蔽词数组示例
    let filterWords = ["不良词1", "不良词2"];

    // Function to generate UUID v4
    function generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    // 封装的发送消息函数
    async function sendMessage(message) {
        // 过滤消息中的屏蔽词
        let filteredMessage = filterMessage(message, filterWords);

        // Define the URL of the endpoint where the POST request should be sent
        const url = 'https://fm.missevan.com/api/chatroom/message/send';

        // Define the correct data structure
        const data = {
            room_id: roomId, // 动态房间ID
            message: filteredMessage, // The actual message
            uuid: generateUUID() // Unique identifier for this message
        };

        // Define the request options
        const options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'user-agent': navigator.userAgent, // 动态获取User-Agent
                'cookie': document.cookie, // 动态获取cookie
                'origin': 'missevan.com',
                'referer': `https://fm.missevan.com/live/${roomId}` // 动态使用房间号
            },
            body: JSON.stringify(data)
        };

        // 发送POST请求
        try {
            const response = await fetch(url, options);
            const responseData = await response.json();
            if (responseData.code === 0) {
                console.log('消息发送成功:', responseData);
            } else {
                console.error('发送失败:', responseData);
            }
        } catch (error) {
            console.error('请求错误:', error);
        }
    }

    // 获取礼物信息并发送到聊天室
    let giftCollector = {};
    let giftTimeout = null;

    async function fetchAndSendGiftInfo() {
        const giftUrl = `https://fm.missevan.com/api/v2/chatroom/history/message?room_id=${roomId}`;

        try {
            const response = await fetch(giftUrl);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const data = await response.json();

            if (data && data.info && Array.isArray(data.info.history)) {
                data.info.history.forEach(message => {
                    if (message.type === 'gift') {
                        const gift = message.gift;
                        const user = message.user;
                        const currentTime = Math.floor(Date.now() / 1000);
                        const messageTime = Math.floor(message.create_time / 1000);

                        // 检查礼物消息是否在过去5秒内
                        if (currentTime - messageTime <= 5) {
                            if (!giftCollector[gift.name]) {
                                giftCollector[gift.name] = {
                                    count: 0,
                                    totalValue: 0
                                };
                            }

                            // 确保数量和价格为数字类型
                            let giftCount = Number(gift.gift_num) || 1; // 如果数量不存在,默认数量为1
                            let giftPrice = Number(gift.price) || 0; // 如果价格不存在,默认价格为0

                            // 累加礼物数量和总价值
                            giftCollector[gift.name].count += giftCount;
                            giftCollector[gift.name].totalValue += giftPrice * giftCount;

                            // 如果定时器存在,清除并重置
                            if (giftTimeout) {
                                clearTimeout(giftTimeout);
                            }

                            // 设置延迟三秒后发送礼物信息
                            giftTimeout = setTimeout(() => {
                                let giftMessage = `感谢大佬的礼物打赏!\n`;

                                // 整合礼物信息
                                Object.keys(giftCollector).forEach(giftName => {
                                    const giftInfo = giftCollector[giftName];
                                    giftMessage += `${giftName} * ${giftInfo.count}\n`;
                                });

                                // 计算总价值
                                let totalValue = Object.values(giftCollector).reduce((sum, giftInfo) => sum + giftInfo.totalValue, 0);
                                giftMessage += `总价值:${totalValue}\n`;

                                // 清空礼物收集器
                                giftCollector = {};

                                // 输出礼物信息到控制台
                                console.log('礼物信息发送:', giftMessage);
                                sendMessage(giftMessage);
                            }, 3000);
                        }
                    }
                });
            } else {
                console.error('历史记录字段缺失或不是数组');
            }
        } catch (error) {
            console.error('获取礼物信息时出错:', error);
        }
    }



    // 每秒检测一次新用户加入
    setInterval(() => {
        // 获取 <app> 标签的内容
        const appElement = document.querySelector('app');
        if (appElement) {
            // 获取 <app> 元素的 HTML 内容
            const appContent = appElement.innerHTML;

            // 解析内容并查找 id='ChatBox' 的 div
            const parser = new DOMParser();
            const doc = parser.parseFromString(appContent, 'text/html');

            // 查找 id 为 ChatBox 的 <div>
            const chatboxDiv = doc.querySelector('div#ChatBox');
            if (chatboxDiv) {
                const joinDivs = chatboxDiv.querySelectorAll('div.join-queue-effect.show.clickable');

                if (joinDivs.length > 0) {
                    console.log('检测到新的用户加入!');
                    joinDivs.forEach((userDiv) => {
                        let usernameDiv = userDiv.querySelector('.username');
                        let username = usernameDiv ? usernameDiv.textContent.trim() : '';

                        if (username && !welcomedUsers.includes(username)) {
                            welcomedUsers.push(username);
                            let date = new Date().toISOString().slice(0, 19).replace('T', ' ');

                            // 使用 pinyin-pro 库将用户名转换为拼音
                            let pinyinUsername = pinyinPro.pinyin(username, {
                                style: pinyinPro.STYLE_NORMAL // 普通风格,不带声调
                            });

                            let welcomeMessage = nameWords[username] ?
                                `| 欢迎${nameWords[username]} (${pinyinUsername}) 进入直播间~ | 日期:${date} |` :
                            `| 欢迎${username}\n| 拼音: ${pinyinUsername}\n| 日期: ${date}`;

                            // 调用发送消息函数
                            sendMessage(welcomeMessage);
                            console.log(`用户 ${username} (${pinyinUsername}) 已加入并发送欢迎消息`);
                        }
                    });
                }
            } else {
                console.log('未找到 id 为 ChatBox 的 div');
            }
        } else {
            console.log('未找到 <app> 标签');
        }
    }, 1000); // 每秒检测一次

    // 定期获取和发送礼物信息
    setInterval(fetchAndSendGiftInfo, 3000); // 每3秒获取一次礼物信息

})();