Navigation
  • Share
  • Breadcrumb

    My second Bilibili stream

    What started as two comment counts on a screen turned into a full-day livestream, several forced restarts, and 934.3 yuan.


    Table of Contents

    My first Bilibili livestream was me playing Tiny Bunny and trying not to mess up the controls. By the second one, I had stopped waiting for a perfect setup. I saw a burst of activity in a comment section, wrote a small program, and went live with two numbers on a screen.

    Stream dates02.20-02.21Afternoon through early morning
    Single-stream views60,000+Split streams are not deduplicated
    Peak placementTOP 10Popularity chart: No. 61
    Final payout¥934.3Best split showed ¥906.9

    At 01:54, the comment section woke up

    In the early hours of February 20, 2026, I was refreshing the most-commented video on Arknights’ official Bilibili account, the Summer Carnival limited-time event promotional PV for the SideStory “Dossoles Holiday.” New comments were arriving faster than I had ever seen on that page.

    Earlier that night and into the morning, comments tied to a controversy around the Honkai: Star Rail character Phainon’s PV “Corona” began spilling into the video. I never found a complete and reliable account of what set off the controversy. There were too many versions online, and most of them carried a side. So I am only describing what I saw: a PV from 2021 suddenly received waves of new replies.

    Arknights Summer Carnival promotional PV open at 01:54
    At 01:54, a PV published in 2021 was still collecting new comments.

    After another refresh, the discussion had turned into a relay. People kept repeating jokes about “repairing the Great Wall,” “reinforcing the wall,” and “building a cyber wall.” Some treated it as a fandom fight. Others just found it funny that a crowd of strangers was awake and posting together. For me, the change on screen was simpler: an old event page was becoming a live event again.

    Arknights comment section filled with repeated wall-building comments
    The same lines were copied and passed along. The comment section had stopped discussing the event and started acting like a construction site.

    I had no plan for a livestream yet. I posted a short update saying, roughly, “I can’t stop laughing, so many people are repairing the wall.”

    Early update about Arknights players repairing the wall
    The first related post went up in the early hours of February 20 and reached 2,457 views.

    Turn the commotion into a screen

    I remembered seeing YouTube streams that put subscriber, view, or like counts side by side whenever two creators were close in a ranking. People could watch the numbers move without refreshing several pages. Bilibili viewers were already jumping between videos to follow the comment race, and I had not seen a stream built around that comparison in my recommendations.

    That gave me a clear task: show the numbers without explaining the drama or taking a side.

    I asked DeepSeek for a first version of the code. It polled the reply counts for two BV IDs, stored a short history, and sent the result to a page that refreshed on its own. The program was not elegant. The page was little more than a large readout, but it was enough to start.

    Comment count comparison for the Phainon and Dossoles PVs
    The daytime setup compared the reply counts for Phainon's PV 'Corona' and the Dossoles Holiday PV.

    The gap between deciding to do it and going live was short. By the time I had designed a complete interface, the comment section would probably have moved on. The second stream still made me nervous, but at least I knew where the browser window should go.

    Ten viewers, then a recommendation loop

    The start was awkward. My account was small, the page mostly showed numbers, and only about ten people were watching. A stream like this needs viewers to comment, return, and bring other people in. Ten was almost nothing.

    I went to the Dossoles Holiday PV and left a comment pointing to the stream without asking people to watch another channel. I told them the tracker put both reply counts in one place, so they could skip the back-and-forth and keep “repairing the wall.”

    That matched what the comment section was already doing. People who had been spread across different videos now had one page where they could watch the numbers change. Some called friends after they arrived. More people brought faster chat, which made the stream easier to recommend, which brought more people.

    Livestream with 1,232 concurrent viewers and 26,000 total views
    Around 14:52, 1,232 people were watching at once. The interaction earnings shown on the right were 63 yuan at that point.
    Screenshots of the livestream appearing in other Bilibili comment sections
    Later, screenshots of the tracker started appearing under other videos too. Some viewers used the room as a quick way to check the race.

    The stream moved much faster than I expected. It reached No. 10 across all of Bilibili and No. 61 on the popularity chart. One stream page showed more than 60,000 total views, and the recommendation page briefly placed my room next to top streamer Yongchu Taffy. For someone on his second livestream, those screenshots did not feel real.

    Livestream ranked 24th on the Bilibili newcomer chart
    The room also reached No. 24 on the newcomer chart that afternoon.
    Tracker ranked 10th across Bilibili and 61st by popularity
    The stream page showed No. 10 site-wide, No. 61 by popularity, and 60,000 total views.

    Those numbers measure different things. The 1,232 figure was concurrent viewers at one moment. The 60,000 figure was the total for one stream session. The site-wide rank and popularity rank also came from different charts. When Bilibili cut the broadcast into several sessions, each session started counting again. Adding the session totals would not give an accurate count of unique viewers.

    Comment tracker next to Yongchu Taffy in the Bilibili recommendation feed
    For one moment, my tiny number board sat beside Yongchu Taffy in the recommendation feed.

    After a few hours, I was no longer wondering whether anyone would watch, only when the next shutdown would come.

    When Bilibili thought the stream was idle

    A comment counter creates an awkward problem for a live platform. Viewers see the numbers moving. Bilibili may see a mostly static page. During the day, the platform repeatedly flagged the stream for “idle or prerecorded behavior,” cut the broadcast, and removed recommendation access for a period.

    Bilibili live moderation notices for idle and prerecorded behavior
    The backend recorded warnings, broadcast cuts, and temporary loss of recommendation access.

    I reopened the stream, wrote another update to explain what had happened, and waited for viewers to find the room again. Some assumed I had ended on purpose. Others noticed the page return and called their friends back. That is also why the final traffic figures are messy: the demand stayed, but the session kept restarting.

    Song requests, a hot patch, and dark mode

    Once the room filled up, people began requesting songs. I did not know Bilibili’s request tools well and did not want to speak on mic, so I handled everything by hand. I read chat, wrote down titles, changed tracks, and kept checking the reply counts.

    Requests arrived faster than I could process them and became the most tiring part of the day. Music still carried much of the interaction. In a room without a face or a continuous voice, chat, songs, and the two numbers had to hold the attention together.

    Later in the evening, the Arknights PV’s reply count moved close to the count for Genshin Impact’s Natlan Symphony Live. I added the third video to the page as a hot patch. The display changed from a two-way race to three lines moving toward one another.

    Dossoles PV reply count approaching and passing the Natlan Symphony count
    After the hot patch added Natlan Symphony Live, the Dossoles Holiday PV passed it.

    As the night went on, traffic fell and my eyes started to hurt. The screen was too bright for a dark room, so I switched the tracker to a dark theme and shared the updated code. That small change got a warm response.

    Post sharing the dark mode version of the comment tracker source code
    I shared the dark mode source code after 02:15. The screenshot shows the post, not a full recording of the stream.

    The 934.3 yuan

    At one point overnight, the Arknights reply count dropped sharply. I kept watching the line and worried the room would empty if the number stopped moving. The count recovered, and I finally closed the stream at a quieter moment.

    The backend recorded 954.5 yuan in gift revenue. After platform settlement and tax deductions, 934.3 yuan reached my withdrawal account. One split showed 906.9 yuan. Most of the money came from Super Chats around midday.

    Some of those paid messages were designed to provoke fights between anime and game communities. They brought more attention to the room and made up a large share of the earnings. I benefited from that traffic. I also got a clearer look at how easily a public ranking can turn group resentment into money and heat.

    Split stream earnings with one session at 906.9 yuan
    One of the forced splits showed 906.9 yuan in earnings.
    Bilibili earnings backend showing gift revenue
    The backend showed 954.5 yuan in gifts. The final withdrawal after deductions was 934.3 yuan.
    Successful withdrawal of 934.3 yuan
    The 934.3 yuan withdrawal completed early on February 21.

    The code that ran that night

    The version below is the final code I used during the stream. I copied it from the file I have now without changing the two BV IDs, the Chinese interface text, or the parts that only worked because I was in a hurry.

    It is a single Flask application. A background thread fetches the reply counts, keeps the last 30 samples, and exposes them at /api/comment-counts. The browser polls that endpoint and redraws an ECharts line chart. The program assumes there are exactly two videos and uses shared dictionaries for its state.

    Install its dependencies and run it with:

    pip install flask flask-cors bilibili-api-python aiohttp
    python original-monitor.py
    

    The same dependencies are listed in requirements.txt.

    Show the exact code that ran during the stream

    Download original-monitor.py

    from flask import Flask, render_template_string, jsonify
    from flask_cors import CORS
    from bilibili_api import video
    import asyncio
    import threading
    import time
    from datetime import datetime
    
    # ==================== 配置区域 ====================
    # 视频1:崩坏:星穹铁道
    VIDEO_BV_1 = "BV1HfKiz3Ezf"
    VIDEO_NAME_1 = "《崩坏:星穹铁道》白厄角色PV——「日冕」"
    
    # 视频2:明日方舟
    VIDEO_BV_2 = "BV1fy4y1L7Rq"
    VIDEO_NAME_2 = "《明日方舟》夏日嘉年华限时活动宣传PV"
    
    # 更新间隔(秒)——建议调至5秒以上避免风控
    UPDATE_INTERVAL = 5
    # =================================================
    
    app = Flask(__name__)
    CORS(app)
    
    # 全局变量,存储两个视频的数据
    comment_data = {
        'video1': {'count': 0, 'history': []},
        'video2': {'count': 0, 'history': []},
        'last_update': None
    }
    
    async def fetch_comment_count(bvid):
        """获取单个视频评论数"""
        try:
            v = video.Video(bvid=bvid)
            info = await v.get_info()
            return info['stat']['reply']
        except Exception as e:
            print(f"获取视频 {bvid} 数据失败: {e}")
            return None
    
    def update_comment_counts():
        """后台线程:定时更新两个视频的评论数"""
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        while True:
            try:
                tasks = [
                    fetch_comment_count(VIDEO_BV_1),
                    fetch_comment_count(VIDEO_BV_2)
                ]
                results = loop.run_until_complete(asyncio.gather(*tasks))
                count1, count2 = results
                now = datetime.now().strftime("%H:%M:%S")
    
                # 更新视频1
                if count1 is not None:
                    comment_data['video1']['count'] = count1
                    comment_data['video1']['history'].append({'time': now, 'count': count1})
                    if len(comment_data['video1']['history']) > 30:
                        comment_data['video1']['history'] = comment_data['video1']['history'][-30:]
    
                # 更新视频2
                if count2 is not None:
                    comment_data['video2']['count'] = count2
                    comment_data['video2']['history'].append({'time': now, 'count': count2})
                    if len(comment_data['video2']['history']) > 30:
                        comment_data['video2']['history'] = comment_data['video2']['history'][-30:]
    
                comment_data['last_update'] = now
                print(f"数据已更新: {now} - 视频1: {count1}, 视频2: {count2}")
    
            except Exception as e:
                print(f"更新循环出错: {e}")
    
            time.sleep(UPDATE_INTERVAL)
    
    @app.route('/api/comment-counts')
    def get_comment_counts():
        """API接口:返回两个视频的最新数据"""
        return jsonify({
            'video1': {
                'name': VIDEO_NAME_1,
                'bvid': VIDEO_BV_1,
                'current': comment_data['video1']['count'],
                'history': comment_data['video1']['history']
            },
            'video2': {
                'name': VIDEO_NAME_2,
                'bvid': VIDEO_BV_2,
                'current': comment_data['video2']['count'],
                'history': comment_data['video2']['history']
            },
            'last_update': comment_data['last_update']
        })
    
    @app.route('/')
    def index():
        return render_template_string(HTML_TEMPLATE)
    
    # 启动后台线程
    thread = threading.Thread(target=update_comment_counts, daemon=True)
    thread.start()
    
    # ==================== 前端模板(双视频夜间模式版) ====================
    HTML_TEMPLATE = '''
    <!DOCTYPE html>
    <html lang="zh">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>B站双视频评论数实时对比 · 夜间模式</title>
        <script src="https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/echarts.min.js"></script>
        <style>
            body {
                font-family: 'Microsoft YaHei', sans-serif;
                margin: 20px;
                background-color: #121212;
                color: #e0e0e0;
            }
            .container { max-width: 1600px; margin: 0 auto; }
            .header { text-align: center; margin-bottom: 30px; }
            .header h1 { color: #ffffff; }
            .header p { color: #aaa; }
            
            /* 顶部双卡片 */
            .cards { display: flex; gap: 20px; margin-bottom: 30px; }
            .card {
                flex: 1;
                background: #1e1e1e;
                border-radius: 12px;
                padding: 25px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.5);
                transition: transform 0.2s;
            }
            .card:hover { transform: translateY(-5px); box-shadow: 0 6px 16px rgba(0,0,0,0.7); }
            .card h2 { margin: 0 0 10px 0; color: #bbb; font-size: 1.2rem; }
            .card .video-name { font-size: 1.1rem; font-weight: bold; color: #fff; margin-bottom: 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
            .card .bvid { color: #888; font-size: 0.8rem; margin-bottom: 20px; }
            .card .count { font-size: 4rem; font-weight: bold; color: #80cbc4; line-height: 1.2; }
            .card1 { border-top: 5px solid #fb7299; }
            .card2 { border-top: 5px solid #ff9f1c; }
            
            /* 底部:折线图 + 增速面板 */
            .bottom-container { display: flex; gap: 20px; margin-top: 20px; }
            .chart-container {
                flex: 2;
                background: #1e1e1e;
                border-radius: 12px;
                padding: 20px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.5);
            }
            #chart { width: 100%; height: 450px; }
            
            .growth-panel {
                flex: 1;
                background: #1e1e1e;
                border-radius: 12px;
                padding: 20px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.5);
                display: flex;
                flex-direction: column;
                gap: 15px;
            }
            .growth-item {
                background: #2d2d2d;
                border-radius: 10px;
                padding: 15px;
            }
            .growth-item h3 {
                margin: 0 0 10px 0;
                font-size: 1.1rem;
                color: #ccc;
                display: flex;
                align-items: center;
                gap: 8px;
            }
            .growth-current {
                font-size: 2.5rem;
                font-weight: bold;
                margin: 5px 0 10px 0;
            }
            .growth-current.positive { color: #4caf50; }
            .growth-current.negative { color: #f44336; }
            .growth-current.zero { color: #9e9e9e; }
            .history-list {
                list-style: none;
                padding: 0;
                margin: 0;
                max-height: 120px;
                overflow-y: auto;
                font-size: 0.9rem;
                border-top: 1px solid #444;
                padding-top: 8px;
            }
            .history-list li {
                display: flex;
                justify-content: space-between;
                padding: 4px 0;
                border-bottom: 1px dashed #3a3a3a;
            }
            .history-list .time { color: #aaa; }
            .history-list .value.positive { color: #4caf50; font-weight: 500; }
            .history-list .value.negative { color: #f44336; font-weight: 500; }
            .history-list .value.zero { color: #9e9e9e; }
            
            .update-info { text-align: center; margin-top: 20px; color: #888; font-size: 0.9rem; }
            .footer { text-align: center; margin-top: 30px; color: #666; font-size: 0.8rem; }
            
            .color-dot { display: inline-block; width: 12px; height: 12px; border-radius: 50%; }
            .dot-pink { background: #fb7299; }
            .dot-orange { background: #ff9f1c; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>📊 B站双视频评论数实时对比 · 夜间模式</h1>
                <p>数据每 {{ UPDATE_INTERVAL }} 秒自动刷新 | 右侧面板显示实时增速及最近5次变化</p>
            </div>
            
            <!-- 顶部双卡片 -->
            <div class="cards">
                <div class="card card1" id="card1">
                    <h2>🎬 视频 A</h2>
                    <div class="video-name" id="name1">加载中...</div>
                    <div class="bvid" id="bvid1"></div>
                    <div class="count" id="count1">0</div>
                </div>
                <div class="card card2" id="card2">
                    <h2>🎬 视频 B</h2>
                    <div class="video-name" id="name2">加载中...</div>
                    <div class="bvid" id="bvid2"></div>
                    <div class="count" id="count2">0</div>
                </div>
            </div>
            
            <!-- 底部:折线图 + 增速面板 -->
            <div class="bottom-container">
                <!-- 左侧折线图 -->
                <div class="chart-container">
                    <div id="chart"></div>
                </div>
                
                <!-- 右侧增速面板(两个区块) -->
                <div class="growth-panel">
                    <div class="growth-item" id="growthVideo1">
                        <h3><span class="color-dot dot-pink"></span> 视频 A 增速</h3>
                        <div class="growth-current" id="growthCurrent1">--</div>
                        <ul class="history-list" id="growthHistory1"><li>等待数据...</li></ul>
                    </div>
                    <div class="growth-item" id="growthVideo2">
                        <h3><span class="color-dot dot-orange"></span> 视频 B 增速</h3>
                        <div class="growth-current" id="growthCurrent2">--</div>
                        <ul class="history-list" id="growthHistory2"><li>等待数据...</li></ul>
                    </div>
                </div>
            </div>
            
            <div class="update-info" id="updateInfo">上次更新: --</div>
            <div class="footer">数据来源: B站API | 增速为相邻两次评论数差值 | 历史增速显示最近5次</div>
        </div>
    
        <script>
            // 初始化折线图(深色主题)
            const chartDom = document.getElementById('chart');
            const myChart = echarts.init(chartDom);
            
            let option = {
                backgroundColor: 'transparent',
                title: {
                    text: '评论数变化趋势对比',
                    left: 'center',
                    textStyle: { color: '#ccc' }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { type: 'shadow', label: { backgroundColor: '#333' } }
                },
                legend: {
                    data: [],
                    top: 30,
                    textStyle: { color: '#ccc' }
                },
                grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
                xAxis: {
                    type: 'category',
                    data: [],
                    name: '时间',
                    nameTextStyle: { color: '#aaa' },
                    axisLabel: { color: '#aaa' },
                    axisLine: { lineStyle: { color: '#555' } },
                    axisTick: { lineStyle: { color: '#555' } }
                },
                yAxis: {
                    type: 'value',
                    name: '评论数',
                    scale: true,
                    nameTextStyle: { color: '#aaa' },
                    axisLabel: { color: '#aaa' },
                    axisLine: { lineStyle: { color: '#555' } },
                    axisTick: { lineStyle: { color: '#555' } },
                    splitLine: { lineStyle: { color: '#333' } }
                },
                series: [
                    { name: '视频 A', type: 'line', data: [], smooth: true, color: '#fb7299', symbol: 'circle' },
                    { name: '视频 B', type: 'line', data: [], smooth: true, color: '#ff9f1c', symbol: 'diamond' }
                ]
            };
            myChart.setOption(option);
    
            // 增速更新函数
            function updateGrowthPanel(history, currentGrowthEl, historyListEl) {
                if (history.length < 2) {
                    currentGrowthEl.innerText = '--';
                    currentGrowthEl.className = 'growth-current zero';
                } else {
                    const last = history[history.length-1].count;
                    const prev = history[history.length-2].count;
                    const diff = last - prev;
                    let text = (diff > 0 ? '+' : '') + diff;
                    currentGrowthEl.innerText = text;
                    if (diff > 0) currentGrowthEl.className = 'growth-current positive';
                    else if (diff < 0) currentGrowthEl.className = 'growth-current negative';
                    else currentGrowthEl.className = 'growth-current zero';
                }
                
                const listHtml = [];
                if (history.length >= 2) {
                    const start = Math.max(0, history.length - 6);
                    const recentHistory = history.slice(start);
                    for (let i = recentHistory.length - 1; i >= 1; i--) {
                        const current = recentHistory[i];
                        const previous = recentHistory[i-1];
                        const diff = current.count - previous.count;
                        const time = current.time;
                        const sign = diff > 0 ? '+' : '';
                        const valueClass = diff > 0 ? 'positive' : (diff < 0 ? 'negative' : 'zero');
                        listHtml.push(`<li><span class="time">${time}</span><span class="value ${valueClass}">${sign}${diff}</span></li>`);
                    }
                } else {
                    listHtml.push('<li>暂无历史数据</li>');
                }
                historyListEl.innerHTML = listHtml.join('');
            }
    
            async function fetchData() {
                try {
                    const response = await fetch('/api/comment-counts');
                    const data = await response.json();
                    
                    document.getElementById('name1').innerText = data.video1.name;
                    document.getElementById('bvid1').innerText = data.video1.bvid;
                    document.getElementById('count1').innerText = data.video1.current.toLocaleString();
                    
                    document.getElementById('name2').innerText = data.video2.name;
                    document.getElementById('bvid2').innerText = data.video2.bvid;
                    document.getElementById('count2').innerText = data.video2.current.toLocaleString();
                    
                    updateGrowthPanel(data.video1.history, 
                        document.getElementById('growthCurrent1'), 
                        document.getElementById('growthHistory1'));
                    updateGrowthPanel(data.video2.history, 
                        document.getElementById('growthCurrent2'), 
                        document.getElementById('growthHistory2'));
                    
                    document.getElementById('updateInfo').innerText = `上次更新: ${data.last_update || '--'}`;
                    
                    // 准备图表数据,取最小长度对齐
                    const minLen = Math.min(data.video1.history.length, data.video2.history.length);
                    const slicedTimes = data.video1.history.slice(-minLen).map(item => item.time);
                    const series1Sliced = data.video1.history.slice(-minLen).map(item => item.count);
                    const series2Sliced = data.video2.history.slice(-minLen).map(item => item.count);
                    
                    myChart.setOption({
                        legend: { data: [data.video1.name, data.video2.name] },
                        xAxis: { data: slicedTimes },
                        series: [
                            { name: data.video1.name, data: series1Sliced },
                            { name: data.video2.name, data: series2Sliced }
                        ]
                    });
                    
                } catch (error) {
                    console.error('获取数据失败:', error);
                    document.getElementById('updateInfo').innerText = '获取数据失败,请检查后端服务';
                }
            }
            
            fetchData();
            setInterval(fetchData, {{ UPDATE_INTERVAL * 1000 }});
        </script>
    </body>
    </html>
    '''.replace('{{ UPDATE_INTERVAL }}', str(UPDATE_INTERVAL)).replace('{{ UPDATE_INTERVAL * 1000 }}', str(UPDATE_INTERVAL * 1000))
    
    if __name__ == '__main__':
        print(f"🚀 启动B站双视频评论监控程序(夜间模式)")
        print(f"🎯 监控视频1: {VIDEO_NAME_1} ({VIDEO_BV_1})")
        print(f"🎯 监控视频2: {VIDEO_NAME_2} ({VIDEO_BV_2})")
        print(f"⏱️  更新间隔: {UPDATE_INTERVAL} 秒")
        print("🌐 请访问 http://127.0.0.1:5000 查看实时监控面板")
        app.run(debug=False, host='0.0.0.0', port=5000)

    The code worked that night. The BVs are hardcoded, the UI has two fixed cards, every poll reads the same comment field, and concurrent reads and writes to the shared data are not protected by a lock. I would not start a new tracker from this file.

    What I would build now

    The original idea solved a useful problem: collect one public metric from several videos, keep a short history, and make the changes easy to compare.

    A more general version should let me add videos by editing a config file instead of touching Python. It should also track comments and other metrics such as views, likes, favorites, coins, shares, and danmaku. If one fetch fails, the other videos should continue updating, and the page should keep the last good values instead of falling to zero.

    I wrote the general version from the original code without trying to keep every line backward compatible.

    It makes five changes:

    1. A videos list replaces the two fixed BV variables. You can track any number of videos.
    2. A metric setting supports replies, views, danmaku, likes, favorites, coins, and shares.
    3. Each video has its own state and error field. One failed API call does not erase the others.
    4. A lock protects the history while the polling thread and Flask requests access it.
    5. The browser builds cards and chart series from the API response, so adding a video does not require editing the HTML.

    The minimum polling interval is five seconds. Bilibili can rate-limit anonymous clients, and polling faster does not make the comparison more useful. The example defaults to ten seconds.

    Create config.json from the included example:

    cp monitor-config.example.json config.json
    pip install flask flask-cors bilibili-api-python aiohttp
    python generic-monitor.py
    

    The server binds to 127.0.0.1:5000 by default. Set MONITOR_HOST only when you deliberately want the page reachable from another machine on your network.

    Show the general version's example config

    Download monitor-config.example.json

    {
      "metric": "reply",
      "update_interval_seconds": 10,
      "request_timeout_seconds": 15,
      "history_limit": 180,
      "videos": [
        {
          "bvid": "BV1HfKiz3Ezf",
          "name": "Honkai: Star Rail - Phainon character PV “Corona”",
          "color": "#fb7299"
        },
        {
          "bvid": "BV1fy4y1L7Rq",
          "name": "Arknights Summer Carnival promotional PV",
          "color": "#ff9f1c"
        }
      ]
    }
    
    Show the general-purpose tracker

    Download generic-monitor.py

    from __future__ import annotations
    
    import asyncio
    import json
    import logging
    import os
    import threading
    import time
    from collections import deque
    from dataclasses import dataclass, field
    from datetime import datetime
    from pathlib import Path
    from typing import Any
    
    from bilibili_api import video
    from flask import Flask, jsonify, render_template_string
    from flask_cors import CORS
    
    
    logging.basicConfig(
        level=os.getenv("LOG_LEVEL", "INFO"),
        format="%(asctime)s %(levelname)s %(message)s",
    )
    log = logging.getLogger("bili-monitor")
    
    METRIC_LABELS = {
        "reply": "comments",
        "view": "views",
        "danmaku": "danmaku",
        "like": "likes",
        "favorite": "favorites",
        "coin": "coins",
        "share": "shares",
    }
    
    PALETTE = (
        "#fb7299",
        "#ff9f1c",
        "#4cc9a7",
        "#65a9ff",
        "#c792ea",
        "#f2d16b",
    )
    
    
    @dataclass(frozen=True)
    class VideoSpec:
        bvid: str
        name: str
        color: str
    
    
    @dataclass
    class VideoState:
        spec: VideoSpec
        history: deque[dict[str, Any]]
        current: int | None = None
        last_success_at: str | None = None
        last_error: str | None = None
        consecutive_failures: int = 0
    
    
    def load_config(path: Path) -> dict[str, Any]:
        with path.open("r", encoding="utf-8") as handle:
            config = json.load(handle)
    
        metric = str(config.get("metric", "reply"))
        if metric not in METRIC_LABELS:
            supported = ", ".join(sorted(METRIC_LABELS))
            raise ValueError(f"Unsupported metric {metric!r}. Use one of: {supported}")
    
        videos = config.get("videos")
        if not isinstance(videos, list) or not videos:
            raise ValueError("config.json must contain a non-empty 'videos' list")
    
        seen: set[str] = set()
        for index, item in enumerate(videos):
            if not isinstance(item, dict) or not item.get("bvid"):
                raise ValueError(f"videos[{index}] is missing a bvid")
            bvid = str(item["bvid"]).strip()
            if bvid in seen:
                raise ValueError(f"Duplicate bvid: {bvid}")
            seen.add(bvid)
    
        return config
    
    
    def parse_specs(config: dict[str, Any]) -> list[VideoSpec]:
        specs = []
        for index, item in enumerate(config["videos"]):
            bvid = str(item["bvid"]).strip()
            specs.append(
                VideoSpec(
                    bvid=bvid,
                    name=str(item.get("name") or bvid),
                    color=str(item.get("color") or PALETTE[index % len(PALETTE)]),
                )
            )
        return specs
    
    
    class VideoMetricMonitor:
        def __init__(
            self,
            specs: list[VideoSpec],
            metric: str,
            interval_seconds: float,
            history_limit: int,
            request_timeout_seconds: float,
        ) -> None:
            self.metric = metric
            self.interval_seconds = max(5.0, float(interval_seconds))
            self.request_timeout_seconds = max(3.0, float(request_timeout_seconds))
            self.history_limit = max(2, int(history_limit))
            self.states = [
                VideoState(
                    spec=spec,
                    history=deque(maxlen=self.history_limit),
                )
                for spec in specs
            ]
            self.last_update: str | None = None
            self._lock = threading.Lock()
            self._stop = threading.Event()
            self._thread = threading.Thread(
                target=self._run,
                name="bili-metric-poller",
                daemon=True,
            )
    
        def start(self) -> None:
            if not self._thread.is_alive():
                self._thread.start()
    
        def stop(self) -> None:
            self._stop.set()
    
        def is_alive(self) -> bool:
            return self._thread.is_alive()
    
        async def _fetch_one(
            self,
            state: VideoState,
            semaphore: asyncio.Semaphore,
        ) -> int:
            async with semaphore:
                info = await asyncio.wait_for(
                    video.Video(bvid=state.spec.bvid).get_info(),
                    timeout=self.request_timeout_seconds,
                )
                value = info.get("stat", {}).get(self.metric)
                if isinstance(value, bool) or not isinstance(value, int):
                    raise ValueError(
                        f"Bilibili returned no integer '{self.metric}' for {state.spec.bvid}"
                    )
                return value
    
        async def _poll_once(self) -> list[int | BaseException]:
            semaphore = asyncio.Semaphore(min(4, len(self.states)))
            tasks = [
                self._fetch_one(state, semaphore)
                for state in self.states
            ]
            return await asyncio.gather(*tasks, return_exceptions=True)
    
        def _record_success(self, state: VideoState, value: int, now: datetime) -> None:
            label = now.strftime("%H:%M:%S")
            with self._lock:
                state.current = value
                state.last_error = None
                state.consecutive_failures = 0
                state.last_success_at = now.isoformat(timespec="seconds")
                state.history.append(
                    {
                        "timestamp": int(now.timestamp()),
                        "time": label,
                        "count": value,
                    }
                )
    
        def _record_failure(
            self,
            state: VideoState,
            error: BaseException,
        ) -> None:
            message = str(error).splitlines()[0][:240]
            with self._lock:
                state.consecutive_failures += 1
                state.last_error = message
            log.warning("Failed to fetch %s: %s", state.spec.bvid, message)
    
        def _run(self) -> None:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            try:
                while not self._stop.is_set():
                    started = time.monotonic()
                    now = datetime.now().astimezone()
                    try:
                        results = loop.run_until_complete(self._poll_once())
                        successes = 0
                        for state, result in zip(self.states, results):
                            if isinstance(result, BaseException):
                                self._record_failure(state, result)
                            else:
                                self._record_success(state, result, now)
                                successes += 1
    
                        with self._lock:
                            if successes:
                                self.last_update = now.isoformat(timespec="seconds")
                        log.info(
                            "Polled %s/%s videos for %s",
                            successes,
                            len(self.states),
                            self.metric,
                        )
                    except Exception:
                        log.exception("Polling cycle failed")
    
                    elapsed = time.monotonic() - started
                    delay = max(0.5, self.interval_seconds - elapsed)
                    if self._stop.wait(delay):
                        break
            finally:
                loop.close()
    
        def snapshot(self) -> dict[str, Any]:
            with self._lock:
                videos = []
                for state in self.states:
                    videos.append(
                        {
                            "bvid": state.spec.bvid,
                            "name": state.spec.name,
                            "color": state.spec.color,
                            "current": state.current,
                            "history": list(state.history),
                            "last_success_at": state.last_success_at,
                            "last_error": state.last_error,
                            "consecutive_failures": state.consecutive_failures,
                        }
                    )
                return {
                    "metric": self.metric,
                    "metric_label": METRIC_LABELS[self.metric],
                    "last_update": self.last_update,
                    "videos": videos,
                }
    
    
    PAGE_TEMPLATE = """
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Bilibili metric tracker</title>
      <script src="https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/echarts.min.js"></script>
      <style>
        :root {
          color-scheme: dark;
          --page: #101412;
          --panel: #191f1c;
          --panel-2: #222a26;
          --line: #344139;
          --ink: #eff5f1;
          --muted: #99a79f;
          --positive: #68d391;
          --negative: #ff7b72;
        }
        * { box-sizing: border-box; }
        body {
          margin: 0;
          background: radial-gradient(circle at 50% 0, #1b2b23, var(--page) 46%);
          color: var(--ink);
          font-family: Inter, "Microsoft YaHei", system-ui, sans-serif;
        }
        main { width: min(1500px, calc(100% - 32px)); margin: 0 auto; padding: 32px 0 48px; }
        header { display: flex; justify-content: space-between; gap: 24px; align-items: end; margin-bottom: 24px; }
        h1 { margin: 0 0 6px; font-size: clamp(1.8rem, 4vw, 3.1rem); line-height: 1; }
        header p, .status, .error, .meta { color: var(--muted); }
        .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 14px; }
        .card, .chart, .growth {
          border: 1px solid var(--line);
          border-radius: 14px;
          background: color-mix(in srgb, var(--panel) 94%, white);
          box-shadow: 0 16px 44px #0004;
        }
        .card { border-top: 4px solid var(--series); padding: 20px; min-width: 0; }
        .card h2 { margin: 0 0 8px; font-size: 0.93rem; color: var(--muted); }
        .card .name { min-height: 2.7em; font-weight: 650; line-height: 1.35; overflow-wrap: anywhere; }
        .card .bvid { margin-top: 4px; color: var(--muted); font: 0.76rem ui-monospace, monospace; }
        .card .value { margin-top: 20px; color: var(--series); font: 700 clamp(2rem, 4vw, 3.4rem)/1 ui-monospace, monospace; }
        .card .error { margin: 12px 0 0; font-size: 0.72rem; line-height: 1.35; }
        .layout { display: grid; grid-template-columns: minmax(0, 2fr) minmax(260px, 1fr); gap: 14px; margin-top: 14px; }
        .chart { padding: 18px; min-width: 0; }
        #chart { width: 100%; height: min(62vh, 570px); min-height: 360px; }
        .growth { padding: 18px; display: grid; align-content: start; gap: 12px; }
        .growth-card { border-radius: 10px; background: var(--panel-2); padding: 14px; }
        .growth-card h3 { margin: 0; font-size: 0.88rem; color: var(--muted); }
        .delta { margin-top: 8px; font: 700 1.9rem ui-monospace, monospace; }
        .delta.positive { color: var(--positive); }
        .delta.negative { color: var(--negative); }
        .delta.zero { color: var(--muted); }
        .growth-list { margin: 10px 0 0; padding: 8px 0 0; border-top: 1px solid var(--line); list-style: none; }
        .growth-list li { display: flex; justify-content: space-between; padding: 4px 0; color: var(--muted); font-size: 0.76rem; }
        footer { display: flex; justify-content: space-between; gap: 16px; margin-top: 18px; color: var(--muted); font-size: 0.76rem; }
        @media (max-width: 860px) {
          header, footer { align-items: start; flex-direction: column; }
          .layout { grid-template-columns: 1fr; }
          #chart { height: 380px; }
        }
      </style>
    </head>
    <body>
      <main>
        <header>
          <div>
            <h1>Bilibili metric tracker</h1>
            <p>{{ metric_label|capitalize }} / refresh every {{ interval_seconds }} seconds</p>
          </div>
          <div class="status" id="status">Waiting for the first poll...</div>
        </header>
    
        <section class="cards" id="cards" aria-label="Latest values"></section>
    
        <section class="layout">
          <div class="chart">
            <div id="chart" role="img" aria-label="Metric history across tracked videos"></div>
          </div>
          <aside class="growth" id="growth" aria-label="Recent changes"></aside>
        </section>
    
        <footer>
          <span>Source: Bilibili video API</span>
          <span id="updated">Last update: --</span>
        </footer>
      </main>
    
      <script>
        const numberFormat = new Intl.NumberFormat("en-US");
        const chart = echarts.init(document.getElementById("chart"));
        const cards = document.getElementById("cards");
        const growthPanel = document.getElementById("growth");
        const statusNode = document.getElementById("status");
        const updatedNode = document.getElementById("updated");
    
        function formatDelta(value) {
          if (value == null) return "--";
          return (value > 0 ? "+" : "") + numberFormat.format(value);
        }
    
        function deltaClass(value) {
          if (value == null || value === 0) return "zero";
          return value > 0 ? "positive" : "negative";
        }
    
        function makeCard(video) {
          const card = document.createElement("article");
          card.className = "card";
          card.style.setProperty("--series", video.color);
    
          const heading = document.createElement("h2");
          heading.textContent = "Tracked video";
    
          const name = document.createElement("div");
          name.className = "name";
          name.textContent = video.name;
    
          const bvid = document.createElement("div");
          bvid.className = "bvid";
          bvid.textContent = video.bvid;
    
          const value = document.createElement("div");
          value.className = "value";
          value.textContent = video.current == null ? "--" : numberFormat.format(video.current);
    
          card.append(heading, name, bvid, value);
          if (video.last_error) {
            const error = document.createElement("p");
            error.className = "error";
            error.textContent = "Last poll failed: " + video.last_error;
            card.append(error);
          }
          return card;
        }
    
        function makeGrowth(video) {
          const card = document.createElement("section");
          card.className = "growth-card";
    
          const title = document.createElement("h3");
          title.textContent = video.name;
    
          const history = video.history || [];
          const latestDelta = history.length >= 2
            ? history.at(-1).count - history.at(-2).count
            : null;
    
          const delta = document.createElement("div");
          delta.className = "delta " + deltaClass(latestDelta);
          delta.textContent = formatDelta(latestDelta);
    
          const list = document.createElement("ul");
          list.className = "growth-list";
          const pairs = [];
          for (let index = Math.max(1, history.length - 5); index < history.length; index += 1) {
            const item = document.createElement("li");
            const left = document.createElement("span");
            left.textContent = history[index].time;
            const right = document.createElement("span");
            const difference = history[index].count - history[index - 1].count;
            right.textContent = formatDelta(difference);
            right.className = deltaClass(difference);
            item.append(left, right);
            pairs.push(item);
          }
    
          list.append(...pairs.reverse());
          if (!pairs.length) {
            const empty = document.createElement("li");
            empty.textContent = "Waiting for two samples...";
            list.append(empty);
          }
    
          card.append(title, delta, list);
          return card;
        }
    
        function updateChart(videos) {
          const timestamps = new Map();
          for (const video of videos) {
            for (const point of video.history || []) {
              timestamps.set(point.timestamp, point.time);
            }
          }
          const sorted = [...timestamps.keys()].sort((left, right) => left - right);
          const labels = sorted.map((timestamp) => timestamps.get(timestamp));
    
          chart.setOption({
            backgroundColor: "transparent",
            animationDurationUpdate: 350,
            tooltip: { trigger: "axis" },
            legend: {
              top: 4,
              textStyle: { color: "#dbe5df" },
              data: videos.map((video) => video.name),
            },
            grid: { left: 22, right: 26, top: 58, bottom: 22, containLabel: true },
            xAxis: {
              type: "category",
              data: labels,
              axisLabel: { color: "#99a79f" },
              axisLine: { lineStyle: { color: "#344139" } },
            },
            yAxis: {
              type: "value",
              scale: true,
              axisLabel: { color: "#99a79f" },
              splitLine: { lineStyle: { color: "#2a342f" } },
            },
            series: videos.map((video) => {
              const points = new Map(
                (video.history || []).map((point) => [point.timestamp, point.count])
              );
              return {
                name: video.name,
                type: "line",
                smooth: true,
                connectNulls: true,
                showSymbol: false,
                data: sorted.map((timestamp) => points.get(timestamp) ?? null),
                lineStyle: { width: 3, color: video.color },
                itemStyle: { color: video.color },
              };
            }),
          });
        }
    
        async function refresh() {
          try {
            const response = await fetch("/api/series", { cache: "no-store" });
            if (!response.ok) throw new Error("HTTP " + response.status);
            const data = await response.json();
    
            cards.replaceChildren(...data.videos.map(makeCard));
            growthPanel.replaceChildren(...data.videos.map(makeGrowth));
            updateChart(data.videos);
            updatedNode.textContent = "Last update: " + (data.last_update || "--");
            const failed = data.videos.filter((video) => video.last_error).length;
            statusNode.textContent = failed
              ? `${failed} video${failed === 1 ? "" : "s"} failed on the last poll`
              : "All videos responded on the last poll";
          } catch (error) {
            statusNode.textContent = "Could not reach the monitor API: " + error.message;
          }
        }
    
        refresh();
        setInterval(refresh, {{ interval_ms }});
      </script>
    </body>
    </html>
    """
    
    
    def create_app(config_path: Path) -> Flask:
        config = load_config(config_path)
        specs = parse_specs(config)
        monitor = VideoMetricMonitor(
            specs=specs,
            metric=str(config.get("metric", "reply")),
            interval_seconds=float(config.get("update_interval_seconds", 10)),
            history_limit=int(config.get("history_limit", 180)),
            request_timeout_seconds=float(config.get("request_timeout_seconds", 15)),
        )
    
        app = Flask(__name__)
        allowed_origins = config.get("cors_origins")
        if allowed_origins:
            CORS(app, resources={r"/api/*": {"origins": allowed_origins}})
    
        @app.get("/")
        def index() -> str:
            return render_template_string(
                PAGE_TEMPLATE,
                interval_seconds=monitor.interval_seconds,
                interval_ms=int(monitor.interval_seconds * 1000),
                metric_label=METRIC_LABELS[monitor.metric],
            )
    
        @app.get("/api/series")
        def series():
            return jsonify(monitor.snapshot())
    
        @app.get("/api/health")
        def health():
            return jsonify(
                {
                    "status": "ok",
                    "worker_alive": monitor.is_alive(),
                    "last_update": monitor.last_update,
                }
            )
    
        app.extensions["metric_monitor"] = monitor
        monitor.start()
        return app
    
    
    def main() -> None:
        config_path = Path(os.getenv("MONITOR_CONFIG", "config.json"))
        if not config_path.exists():
            raise SystemExit(f"Config file not found: {config_path.resolve()}")
    
        app = create_app(config_path)
        host = os.getenv("MONITOR_HOST", "127.0.0.1")
        port = int(os.getenv("MONITOR_PORT", "5000"))
        app.run(host=host, port=port, debug=False)
    
    
    if __name__ == "__main__":
        main()
    

    This is still a small local tool. History lives in memory and disappears when the process restarts. There is no login or database, and the program cannot send alerts. The page also loads ECharts from a CDN. Those limits are fine for a livestream counter, and they keep the program short enough to understand.

    After the stream

    I posted a summary just after 05:00 on February 21, shared the requested song list, and recommended other people who had started their own comparison streams. The temporary page had found an audience of its own. Viewers made memes and kept the conversation going after the stream.

    Post-stream summary with the song playlist and links to other comparison streams
    The summary thanked everyone who helped 'build the wall,' shared the playlist, and pointed viewers toward other comment trackers.

    One viewer sent me a meme they had made. Others asked the next day when I would go live again. Those replies were the first time I understood that the stream had become a gathering place.

    Viewer-made meme about the two comment counts
    A viewer's meme turned the two climbing numbers into cartoon characters shouting at each other.
    Viewers asking for another stream the following day
    The request for another stream stayed in the replies. That post received 772 views.

    I would still hit Go Live first

    The first stream taught me how to start. The second taught me how much of a livestream happens after you press the button. I had to watch chat, correct the display, explain shutdowns, handle song requests, and decide what to change while people were already watching.

    I cannot turn that day into a formula. The stream depended on a controversy I did not understand, comment counts that had built up for years, and enough people refreshing Bilibili at the right time. Luck did most of the work.

    Opening the stream before the layout was finished was probably my best decision that day.

    If another opportunity appears, I will prepare song requests, moderation, and a better way to keep the tracker from looking idle. I will probably still open the stream first and fix the rest while it runs.

    The screenshots come from my Bilibili dashboard, posts, and livestream. View counts from separate sessions were not deduplicated. Concurrent viewers, cumulative views, and chart rankings use different definitions. I did not find a reliable single account of the controversy around the Phainon PV “Corona,” so this post records the visible comment activity without presenting an unverified explanation as fact.

    DeepSeek conversations from the period: record one and record two.