帖子随机抽奖脚本,可排除用户重复发帖

基于 贡献一个linux.do帖子内随机抽(跳转)楼层的js代码段,可用于抽奖 - 软件分享 - LINUX DO 进行修改

async function fetchChoujiang() {
    // 使用URL对象处理当前URL
    const currentUrl = new URL(window.location.href);
    // 检查当前URL是否以.json结尾,如果不是,则添加.json扩展名
    const jsonUrl = currentUrl.pathname.endsWith('.json') ? currentUrl.href : currentUrl.href + '.json';

    // 使用fetch获取JSON数据
    const response = await fetch(jsonUrl);
    const data = await response.json();
    if (data && data.post_stream && data.post_stream.stream) {
        const postId = window.location.href.match('t/topic/(\\d+)')[1];
        const postIdToFloor = new Map(data.post_stream.stream.map((id, idx)=>[id,idx]));
        const userIdToFloor = new Map();
        const postIds = data.post_stream.stream.slice(1);
        const batchSize = 20;

        for(let i = 0; i < postIds.length; i+=batchSize){
            const batch = postIds.slice(i, i+batchSize);
            console.log('fetching', batch)
            const postsUrl = '/t/' + postId +'/posts.json?'
            const param = new URLSearchParams();
            param.append('include_suggested', false);
            batch.forEach(id=>param.append('post_ids[]',id));
            const postsResponse = await fetch(postsUrl + param)
            const postsData = await postsResponse.json()
            for (const post of postsData.post_stream.posts) {
                const floor = postIdToFloor[post.id];
                userIdToFloor.set(post.user_id, floor)
            }
        }

        // 生成随机数
        const random_floor = Math.floor(Math.random() * userIdToFloor.size + 1)
        console.log('抽中了',random_floor);

         // 更新URL的最后一部分
         const list1 = currentUrl.pathname.split("/");
         if(list1[list1.length - 2]=="topic"){list1.push(random_floor);};
         if(list1[list1.length - 3]=="topic"){list1[list1.length - 1] = random_floor;};
         

         // 生成新的URL
         const newUrl = list1.join("/");

         // 导航到新的URL
         window.location.assign(newUrl);
    }
};

await fetchChoujiang();
4 个赞

随机因子太敷衍:smile:

坐等始皇内置一个抽奖系统

3 个赞
3 个赞

@neo 抽奖系统是不是该提上日程了,佬友们的抽奖环节蛮多的

3 个赞

666

Mark!

感谢!