Skip to content

archibate/dotfiles-opencode / skills/bilibili-api

bilibili-api

Flagged

This skill should be used when the user asks to "use bilibili API", "download bilibili video", "get bilibili user info", "list bilibili favorites", "send bilibili danmaku", "upload video to bilibili", "monitor bilibili live room", "search bilibili", "get bilibili comments", or needs guidance on the bilibili_api Python library usage, authentication, API endpoints, or workflow patterns.

FileKindSize
SKILL.mdskill md8.3 KB
references/api-modules.mdmarkdown6.4 KB
references/common-patterns.mdmarkdown8.6 KB
references/configuration.mdmarkdown4.8 KB
references/credential-setup.mdmarkdown6.1 KB
references/docs/.gitignoreother13 B
references/docs/.nojekyllother0 B
references/docs/DEPLOY_LOCALHOST.mdmarkdown310 B
references/docs/README.mdmarkdown9.9 KB
references/docs/_sidebar.mdmarkdown4.7 KB
references/docs/b23tv.mdmarkdown448 B
references/docs/configuration.mdmarkdown4.3 KB
references/docs/examples/activity.mdmarkdown960 B
references/docs/examples/app.mdmarkdown127 B
references/docs/examples/article.mdmarkdown918 B
references/docs/examples/article_category.mdmarkdown648 B
references/docs/examples/ass.mdmarkdown727 B
references/docs/examples/audio.mdmarkdown1.8 KB
references/docs/examples/audio_uploader.mdmarkdown975 B
references/docs/examples/bangumi.mdmarkdown3.8 KB
references/docs/examples/black_room.mdmarkdown350 B
references/docs/examples/channel_series.mdmarkdown787 B
references/docs/examples/cheese.mdmarkdown152 B
references/docs/examples/client.mdmarkdown183 B
references/docs/examples/comment.mdmarkdown2.2 KB
references/docs/examples/creative_center.mdmarkdown288 B
references/docs/examples/dynamic.mdmarkdown2.0 KB
references/docs/examples/emoji.mdmarkdown802 B
references/docs/examples/favorite_list.mdmarkdown406 B
references/docs/examples/festival.mdmarkdown3.0 KB
references/docs/examples/game.mdmarkdown1.4 KB
references/docs/examples/garb.mdmarkdown3.2 KB
references/docs/examples/homepage.mdmarkdown127 B
references/docs/examples/hot.mdmarkdown263 B
references/docs/examples/interactive_video.mdmarkdown7.9 KB
references/docs/examples/live.mdmarkdown4.0 KB
references/docs/examples/live_area.mdmarkdown349 B
references/docs/examples/login_v2.mdmarkdown5.1 KB
references/docs/examples/manga.mdmarkdown1.2 KB
references/docs/examples/music.mdmarkdown727 B
references/docs/examples/note.mdmarkdown355 B
references/docs/examples/opus.mdmarkdown1.9 KB
references/docs/examples/rank.mdmarkdown122 B
references/docs/examples/search.mdmarkdown1.3 KB
references/docs/examples/session.mdmarkdown778 B
references/docs/examples/show.mdmarkdown255 B
references/docs/examples/topic.mdmarkdown159 B
references/docs/examples/user.mdmarkdown2.5 KB
references/docs/examples/video.mdmarkdown3.8 KB
references/docs/examples/video_tag.mdmarkdown174 B
references/docs/examples/video_uploader.mdmarkdown2.0 KB
references/docs/examples/video_zone.mdmarkdown279 B
references/docs/examples/vote.mdmarkdown133 B
references/docs/examples/watchroom.mdmarkdown662 B
references/docs/get-credential.mdmarkdown3.2 KB
references/docs/history.htmlother1.5 KB
references/docs/history.mdmarkdown123 B
references/docs/index.htmlother2.2 KB
references/docs/ivifile.mdmarkdown3.9 KB
references/docs/logo-small.pngbinary12.2 KB
references/docs/logo.pngbinary88.6 KB
references/docs/modules/README.mdmarkdown432 B
references/docs/modules/activity.mdmarkdown1.0 KB
references/docs/modules/app.mdmarkdown1.3 KB
references/docs/modules/article.mdmarkdown4.8 KB
references/docs/modules/article_category.mdmarkdown2.1 KB
references/docs/modules/ass.mdmarkdown8.2 KB
references/docs/modules/audio.mdmarkdown3.2 KB
references/docs/modules/audio_uploader.mdmarkdown7.5 KB
references/docs/modules/bangumi.mdmarkdown23.6 KB
references/docs/modules/bilibili_api.mdmarkdown38.4 KB
references/docs/modules/black_room.mdmarkdown6.1 KB
references/docs/modules/channel_series.mdmarkdown4.4 KB
references/docs/modules/cheese.mdmarkdown7.3 KB
references/docs/modules/client.mdmarkdown508 B
references/docs/modules/comment.mdmarkdown7.2 KB
references/docs/modules/creative_center.mdmarkdown14.1 KB
references/docs/modules/dynamic.mdmarkdown13.9 KB
references/docs/modules/emoji.mdmarkdown1.6 KB
references/docs/modules/favorite_list.mdmarkdown10.2 KB
references/docs/modules/festival.mdmarkdown771 B
references/docs/modules/game.mdmarkdown3.1 KB
references/docs/modules/garb.mdmarkdown5.8 KB
references/docs/modules/homepage.mdmarkdown2.2 KB
references/docs/modules/hot.mdmarkdown1.6 KB
references/docs/modules/interactive_video.mdmarkdown13.3 KB
references/docs/modules/live.mdmarkdown20.2 KB
references/docs/modules/live_area.mdmarkdown2.2 KB
references/docs/modules/login_v2.mdmarkdown6.0 KB
references/docs/modules/manga.mdmarkdown4.0 KB
references/docs/modules/music.mdmarkdown3.5 KB
references/docs/modules/note.mdmarkdown4.3 KB
references/docs/modules/opus.mdmarkdown3.3 KB
references/docs/modules/rank.mdmarkdown6.8 KB
references/docs/modules/search.mdmarkdown5.9 KB
references/docs/modules/session.mdmarkdown6.9 KB
references/docs/modules/show.mdmarkdown3.2 KB
references/docs/modules/topic.mdmarkdown2.7 KB
references/docs/modules/user.mdmarkdown25.9 KB
references/docs/modules/video.mdmarkdown28.4 KB
references/docs/modules/video_tag.mdmarkdown1.7 KB
references/docs/modules/video_uploader.mdmarkdown9.9 KB
references/docs/modules/video_zone.mdmarkdown6.8 KB
references/docs/modules/vote.mdmarkdown3.2 KB
references/docs/modules/watchroom.mdmarkdown4.4 KB
references/docs/package-lock.jsonmanifest125.8 KB
references/docs/refresh_cookies.mdmarkdown674 B
references/docs/request_client.mdmarkdown11.1 KB
references/docs/search.jsscript6.4 KB
references/docs/sync-executor.mdmarkdown471 B
references/docs/target/npmlist.jsonconfig268 B
references/docs/theme.cssother15.4 KB
references/docs/vote_id.mdmarkdown2.0 KB
references/docs/vote_source.pngbinary41.8 KB
references/live-guide.mdmarkdown5.1 KB
references/self-update.mdmarkdown5.4 KB
references/upload-guide.mdmarkdown5.9 KB
references/user-guide.mdmarkdown4.7 KB
references/video-guide.mdmarkdown6.0 KB
scripts/credential_check.pyscript3.0 KB
scripts/quickstart.pyscript1.2 KB

references/common-patterns.md

View on GitHub
# Common Patterns

## Async/Await Pattern

All API methods are async. Use `asyncio.run()` for the main entry point:

```python
import asyncio
from bilibili_api import video, Credential

async def main():
    v = video.Video(bvid="BV1uv411q7Mv")
    info = await v.get_info()
    print(info["title"])

asyncio.run(main())
```

### Multiple Concurrent Requests

```python
import asyncio
from bilibili_api import video

async def fetch_multiple(bvids):
    tasks = [video.Video(bvid=bv).get_info() for bv in bvids]
    results = await asyncio.gather(*tasks)
    return results

asyncio.run(fetch_multiple(["BV1uv411q7Mv", "BV1GK4y1V7HP"]))
```

## Sync Wrapper

For scripts that don't need async:

```python
from bilibili_api import sync, video

v = video.Video(bvid="BV1uv411q7Mv")
info = sync(v.get_info())
print(info["title"])
```

**Limitations:**
- Cannot use `sync()` inside an already-running event loop
- For nested async calls, use `asyncio.run()` or proper async/await

```python
# WRONG - sync() inside async function
async def main():
    info = sync(v.get_info())  # RuntimeError!

# CORRECT
async def main():
    info = await v.get_info()
```

## Error Handling

### Exception Hierarchy

```
ApiException (base)
├── ArgsException           — Invalid arguments
├── NetworkException        — HTTP/network errors
├── ResponseException       — Response parsing errors
│   └── ResponseCodeException — API returned error code
├── LoginError              — Login failures
├── GeetestException        — Captcha errors
├── CookiesRefreshException — Cookie refresh failed
├── VideoUploadException    — Video upload errors
├── LiveException           — Live streaming errors
├── DanmakuClosedException  — Danmaku connection closed
├── WbiRetryTimesExceedException — WBI retries exhausted
├── DynamicExceedImagesException — Too many images in dynamic
├── ExClimbWuzhiException   — Anti-spider triggered
└── CredentialNo*Exception  — Missing credential fields
    ├── CredentialNoSessdataException
    ├── CredentialNoBiliJctException
    ├── CredentialNoBuvid3Exception
    ├── CredentialNoBuvid4Exception
    ├── CredentialNoDedeUserIDException
    └── CredentialNoAcTimeValueException
```

### Handling API Errors

```python
from bilibili_api import video, ResponseCodeException, NetworkException

async def safe_get_info(bvid):
    v = video.Video(bvid=bvid)
    try:
        info = await v.get_info()
        return info
    except ResponseCodeException as e:
        # Bilibili API returned error
        print(f"API error {e.code}: {e.msg}")
        # Common codes:
        # -400: Request error
        # -403: Access denied
        # -404: Not found
        # -509: Rate limited
        return None
    except NetworkException as e:
        # HTTP/network failure
        print(f"Network error {e.status}: {e.msg}")
        return None
```

### Credential Validation

```python
from bilibili_api import Credential, CredentialNoSessdataException

async def require_auth(credential):
    if not credential.has_sessdata():
        raise CredentialNoSessdataException()
    # or use the built-in method
    credential.raise_for_no_sessdata()
```

## Event System (AsyncEvent)

Used by `LiveDanmaku`, `VideoOnlineMonitor`, and uploaders for event-driven callbacks.

### Basic Usage

```python
from bilibili_api import live

room = live.LiveDanmaku(room_display_id=123456)

@room.on("DANMU_MSG")
async def on_danmaku(event):
    # event["data"] contains the raw message
    content = event["data"]["info"][1]  # danmaku text
    user = event["data"]["info"][2][1]  # username
    print(f"{user}: {content}")

await room.connect()
```

### Multiple Events

```python
@room.on("DANMU_MSG")
async def on_danmaku(event):
    print(f"Danmaku: {event}")

@room.on("SEND_GIFT")
async def on_gift(event):
    print(f"Gift: {event}")

@room.on("SUPER_CHAT_MESSAGE")
async def on_superchat(event):
    print(f"Super Chat: {event}")
```

### Catch All Events

```python
@room.on("__ALL__")
async def on_all(event):
    print(f"Event: {event}")
```

### Programmatic Listener Management

```python
# Add listener
def handler(event):
    print(event)

room.add_event_listener("DANMU_MSG", handler)

# Remove listener
room.remove_event_listener("DANMU_MSG", handler)
```

## Danmaku

### Sending Danmaku

```python
from bilibili_api import video, Danmaku, DmMode, DmFontSize, Credential

async def send_danmaku():
    cred = Credential(sessdata="...", bili_jct="...")
    v = video.Video(bvid="BVxxxxxxxx", credential=cred)

    dm = Danmaku(
        text="Hello from bilibili-api!",
        dm_time=5.0,           # Time in video (seconds)
        mode=DmMode.FLY,       # Scroll mode
        font_size=DmFontSize.NORMAL,  # Font size
        color=0xFFFFFF,        # White (hex)
    )

    await v.send_danmaku(dm)
```

### Danmaku Enums

```python
from bilibili_api import DmMode, DmFontSize

# DmMode
DmMode.FLY      # 1 - Scroll
DmMode.TOP      # 2 - Top fixed
DmMode.BOTTOM   # 3 - Bottom fixed
DmMode.REVERSE  # 4 - Reverse scroll

# DmFontSize
DmFontSize.SMALL   # 18px
DmFontSize.NORMAL  # 25px
DmFontSize.BIG     # 36px
```

### Getting Danmaku

```python
async def get_danmaku():
    v = video.Video(bvid="BVxxxxxxxx")
    danmakus = await v.get_danmakus(page_index=0)
    for dm in danmakus:
        print(f"{dm.dm_time}s: {dm.text}")
```

## Video Download Pattern

```python
import asyncio
from bilibili_api import video, get_client, HEADERS

async def download_video(bvid, output="video.mp4"):
    v = video.Video(bvid=bvid)

    # Get download URLs
    urls = await v.get_download_url(page_index=0)

    # Use VideoDownloadURLDataDetecter to parse
    from bilibili_api import video
    detecter = video.VideoDownloadURLDataDetecter(urls)

    # Detect best streams
    streams = detecter.detect_best_streams()
    video_url = streams[0].url  # Video stream
    audio_url = streams[1].url  # Audio stream (may be None for some videos)

    # Download using client
    client = get_client()

    # Download video
    dwn_id = await client.download_create(video_url, HEADERS)
    total = client.download_content_length(dwn_id)

    with open(output, "wb") as f:
        downloaded = 0
        while True:
            chunk = await client.download_chunk(dwn_id)
            if not chunk:
                break
            f.write(chunk)
            downloaded += len(chunk)
            print(f"Downloaded: {downloaded}/{total} bytes", end="\r")

    print(f"\nSaved to {output}")

# For dash videos (separate video/audio), use ffmpeg to merge:
# ffmpeg -i video.mp4 -i audio.m4a -c copy output.mp4
```

## ID Conversion

```python
from bilibili_api import aid2bvid, bvid2aid

# AV to BV
bvid = aid2bvid(170001)        # "BV17x411w7KC"

# BV to AV
aid = bvid2aid("BV17x411w7KC") # 170001
```

## Link Utilities

### Parse Any Bilibili Link

```python
from bilibili_api import parse_link, ResourceType

async def parse(url):
    result = await parse_link(url)
    print(result.resource_type)  # ResourceType enum
    print(result.id)             # Resource ID
    print(result.obj)            # Corresponding object instance
```

### Resolve Short URLs

```python
from bilibili_api import get_real_url

async def resolve():
    real_url = await get_real_url("https://b23.tv/BV1uv411q7Mv")
    print(real_url)  # Full bilibili URL
```

## Picture Class

```python
from bilibili_api import Picture

# From file
pic = Picture.from_file("./image.png")

# From URL
pic = await Picture.from_url("https://example.com/image.png")

# From content
pic = Picture.from_content(content_bytes, format="png")

# Convert format
pic_jpg = pic.convert_format("jpeg")

# Use in dynamic, comment, etc.
```

## Pagination Pattern

Many APIs return paginated results. Use `pn` (page number) or `offset`:

```python
from bilibili_api import user

async def get_all_videos(uid):
    u = user.User(uid=uid)
    page = 1
    all_videos = []

    while True:
        result = await u.get_videos(pn=page, ps=30)
        videos = result["list"]["vlist"]
        if not videos:
            break
        all_videos.extend(videos)
        page += 1

        # Stop if we've seen all videos
        if len(all_videos) >= result["page"]["count"]:
            break

    return all_videos
```

### Offset-Based (Dynamics)

```python
async def get_dynamics(uid):
    u = user.User(uid=uid)
    offset = None
    all_dynamics = []

    for _ in range(5):  # Get 5 pages
        result = await u.get_dynamics_new(offset=offset)
        if not result:
            break
        all_dynamics.extend(result["items"])
        offset = result.get("offset")
        if not offset:
            break

    return all_dynamics
```
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 467kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 319kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 319kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 319kUpdated Claude CodeCodexVerifiedInstall