想法
**哔哩哔哩up直播成长任务:**有效直播6天,直播间内有500条弹幕,奖励40元。
实现思路:
- 编写JavaScript脚本,启用无障碍模式,在Autox.js上运行。
- 编写JavaScript脚本,在Tampermonkey上运行。
- 编写Java或python程序。
最后敲定方法二。
实现
// ==UserScript==
// @name Bilibili Auto Danmu
// @namespace http://tampermonkey.net/
// @version 1.2
// @description 自动发送弹幕
// @author 陈你好
// @match https://live.bilibili.com/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// 日志
function logDebug(message) {
console.log(`[Bilibili Auto Danmu] ${message}`);
}
// 异步睡眠函数,用于等待
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// 获取输入文本域
function getInputBox() {
return document.querySelector('.chat-input-ctnr textarea');
}
// 获取发送按钮
function getSendButton() {
return document.querySelector('.right-action button');
}
// 更新弹幕消息的函数,生成随机消息
function updateMassage() {
const data = [
["天", "地", "人", "生", "家", "国", "爱", "友", "工", "学"],
["文", "历", "法", "心", "情", "健", "康", "时", "间", "年"],
["月", "日", "时", "分", "秒", "早", "晚", "上", "下", "左"],
["右", "前", "后", "内", "外", "高", "低", "长", "短", "大"],
["小", "多", "少", "水", "火", "风", "你", "好", "世", "界"]
];
let massage = "";
for (let i = 0; i < data.length; i++) {
massage += data[Math.floor(Math.random() * 5)][Math.floor(Math.random() * 10)];
}
return massage;
}
// 发送弹幕的函数
function sendDanmu(inputBox, sendButton) {
if (inputBox && sendButton) {
const message = updateMassage();
// 设置文本域内容
inputBox.value = message;
// 触发输入框内容变化的事件
inputBox.dispatchEvent(new Event('input'));
// 模拟点击发送按钮
sendButton.click();
logDebug(`Sent danmu: ${message}`);
} else {
logDebug('Input box or send button not found.');
}
}
// 异步函数,循环发送弹幕
async function example(inputBox, sendButton) {
for(var i = 1; i <= 505; i++) {
sendDanmu(inputBox, sendButton);
logDebug(i);
await sleep(7000);
}
}
// 使用MutationObserver观察DOM变化,确保元素完全加载后执行脚本
const observer = new MutationObserver((mutationsList, observer) => {
const inputBox = getInputBox();
const sendButton = getSendButton();
if (inputBox && sendButton) {
// inputBox && sendButton存在,停止观察
observer.disconnect();
// 开始发送弹幕
example(inputBox, sendButton);
}
});
// 开始观察目标节点和子节点的变化
observer.observe(document.body, { childList: true, subtree: true });
})();
@match:标识脚本使用的网页。
(function(){…}):创建一个立即执行的函数。
‘use strict’: JavaScript 的严格模式声明,它使得 JavaScript 引擎在严格模式下执行代码,提供了更严格的错误检查和更合理的错误报告。将 'use strict';
包含在 IIFE 中确保只在当前函数的作用域内应用严格模式,而不会影响到全局作用域或其他代码段。