Skip to main content

BpiClient

Struct BpiClient 

Source
pub struct BpiClient { /* private fields */ }
Expand description

Bilibili API 客户端。

Implementations§

Source§

impl BpiClient

Source

pub fn new() -> Result<Self, BpiError>

使用默认配置创建自有客户端。

Examples found in repository?
examples/live_room_info.rs (line 24)
22async fn main() -> BpiResult<()> {
23    let room_id = room_id()?;
24    let client = BpiClient::new()?;
25    let info = client.live().room_info(room_id).await?;
26
27    println!("直播间: {} ({})", info.title, info.room_id);
28    println!("主播 mid: {}", info.uid);
29    println!(
30        "状态: live_status={} 分区={}·{}",
31        info.live_status, info.parent_area_name, info.area_name
32    );
33    println!("在线: {} 关注: {}", info.online, info.attention);
34
35    Ok(())
36}
More examples
Hide additional examples
examples/video_info.rs (line 23)
21async fn main() -> BpiResult<()> {
22    let bvid = video_bvid()?;
23    let client = BpiClient::new()?;
24    let video = client.video();
25
26    let view = video.view(VideoViewParams::from_bvid(bvid.clone())).await?;
27    println!(
28        "视频: {} ({}) UP={} 播放={} 点赞={}",
29        view.title, view.bvid, view.owner.name, view.stat.view, view.stat.like
30    );
31
32    let pages = video
33        .page_list(VideoPageListParams::from_bvid(bvid.clone()))
34        .await?;
35    println!("分 P 数: {}", pages.len());
36    for page in pages.iter().take(5) {
37        println!("  P{} cid={} {}", page.page, page.cid, page.part);
38    }
39
40    let desc = video.desc(VideoDescParams::from_bvid(bvid)).await?;
41    let first_line = desc.lines().next().unwrap_or("");
42    println!("简介首行: {first_line}");
43
44    Ok(())
45}
Source

pub fn builder() -> BpiClientBuilder

开始配置客户端。

Examples found in repository?
examples/common/account.rs (line 23)
22pub fn authenticated_client() -> BpiResult<BpiClient> {
23    BpiClient::builder().account(load_account()?).build()
24}
More examples
Hide additional examples
examples/module_clients.rs (line 35)
33fn client_from_env() -> BpiResult<BpiClient> {
34    match env::var("BPI_COOKIE") {
35        Ok(cookie) if !cookie.trim().is_empty() => BpiClient::builder().cookie(cookie).build(),
36        _ => BpiClient::builder().build(),
37    }
38}
Source

pub fn set_account(&self, account: Account) -> Result<(), BpiError>

设置账号信息并更新此客户端的 cookie 状态。

Source

pub fn clear_account(&self)

清除此客户端的账号信息。

从原始 Cookie 请求头字符串设置账号信息。

Source

pub fn has_login_cookies(&self) -> bool

检查此客户端是否有登录 cookie。

Source

pub fn get_account(&self) -> Option<Account>

返回当前账号信息。

Source

pub fn csrf(&self) -> Result<String, BpiError>

从账号信息获取当前 CSRF token。

Source

pub fn get(&self, url: &str) -> RequestBuilder

使用此客户端默认的 Bilibili 请求头创建 GET 请求。

Source

pub fn post(&self, url: &str) -> RequestBuilder

使用此客户端默认的 Bilibili 请求头创建 POST 请求。

Source§

impl BpiClient

Source

pub fn activity(&self) -> ActivityClient<'_>

创建 activity 领域客户端。

Source

pub fn article(&self) -> ArticleClient<'_>

创建 article 领域客户端。

Source

pub fn audio(&self) -> AudioClient<'_>

创建 audio 领域客户端。

Source

pub fn bangumi(&self) -> BangumiClient<'_>

创建 bangumi 领域客户端。

Examples found in repository?
examples/module_clients.rs (line 22)
9async fn main() -> BpiResult<()> {
10    let client = client_from_env()?;
11    let video_params = VideoViewParams::from_bvid("BV1xx411c7mD".parse::<Bvid>()?);
12    let bangumi_params = BangumiInfoParams::new(MediaId::new(28_220_978)?);
13
14    if !run_live_example() {
15        println!("module-client 快速示例已编译;设置 BPI_RUN_EXAMPLE=1 后会发起真实网络请求");
16        return Ok(());
17    }
18
19    let video = client.video().view(video_params).await?;
20    println!("video: {}", video.title);
21
22    let bangumi = client.bangumi().info(bangumi_params).await?;
23    println!("bangumi: {}", bangumi.media.title);
24
25    if env::var_os("BPI_COOKIE").is_some() {
26        let nav = client.login().nav().await?;
27        println!("logged in: {}", nav.is_login);
28    }
29
30    Ok(())
31}
Source

pub fn cheese(&self) -> CheeseClient<'_>

创建 cheese 课程领域客户端。

Source

pub fn clientinfo(&self) -> ClientInfoClient<'_>

创建 client info 领域客户端。

Source

pub fn comment(&self) -> CommentClient<'_>

创建 comment 领域客户端。

Source

pub fn creativecenter(&self) -> CreativeCenterClient<'_>

创建 creative center 领域客户端。

Source

pub fn danmaku(&self) -> DanmakuClient<'_>

创建 danmaku 领域客户端。

Source

pub fn dynamic(&self) -> DynamicClient<'_>

创建 dynamic 领域客户端。

Source

pub fn electric(&self) -> ElectricClient<'_>

创建 electric charging 领域客户端。

Source

pub fn fav(&self) -> FavClient<'_>

创建 favorite 领域客户端。

Source

pub fn historytoview(&self) -> HistoryToViewClient<'_>

创建 history and to-view 领域客户端。

Source

pub fn login(&self) -> LoginClient<'_>

创建 login 领域客户端。

Examples found in repository?
examples/module_clients.rs (line 26)
9async fn main() -> BpiResult<()> {
10    let client = client_from_env()?;
11    let video_params = VideoViewParams::from_bvid("BV1xx411c7mD".parse::<Bvid>()?);
12    let bangumi_params = BangumiInfoParams::new(MediaId::new(28_220_978)?);
13
14    if !run_live_example() {
15        println!("module-client 快速示例已编译;设置 BPI_RUN_EXAMPLE=1 后会发起真实网络请求");
16        return Ok(());
17    }
18
19    let video = client.video().view(video_params).await?;
20    println!("video: {}", video.title);
21
22    let bangumi = client.bangumi().info(bangumi_params).await?;
23    println!("bangumi: {}", bangumi.media.title);
24
25    if env::var_os("BPI_COOKIE").is_some() {
26        let nav = client.login().nav().await?;
27        println!("logged in: {}", nav.is_login);
28    }
29
30    Ok(())
31}
More examples
Hide additional examples
examples/login_status.rs (line 17)
15async fn main() -> BpiResult<()> {
16    let client = account::authenticated_client()?;
17    let login = client.login();
18
19    let nav = login.nav().await?;
20    println!(
21        "登录状态: is_login={} mid={:?} uname={}",
22        nav.is_login,
23        nav.mid,
24        nav.uname.as_deref().unwrap_or("<unknown>")
25    );
26
27    let coin = login.coin().await?;
28    println!("硬币余额: {:.2}", coin.money);
29
30    match login.daily_reward().await {
31        Ok(reward) => println!(
32            "每日奖励: login={} watch={} coins={} share={}",
33            reward.login, reward.watch, reward.coins, reward.share
34        ),
35        Err(err) if err.is_risk_control() => {
36            println!("每日奖励: 当前请求被风控拦截,已跳过 ({err})");
37        }
38        Err(err) => return Err(err),
39    }
40
41    let vip = login.vip_info().await?;
42    println!(
43        "VIP: active={} type={} status={}",
44        vip.is_active(),
45        vip.vip_type,
46        vip.vip_status
47    );
48
49    Ok(())
50}
Source

pub fn live(&self) -> LiveClient<'_>

创建 live 领域客户端。

Examples found in repository?
examples/live_room_info.rs (line 25)
22async fn main() -> BpiResult<()> {
23    let room_id = room_id()?;
24    let client = BpiClient::new()?;
25    let info = client.live().room_info(room_id).await?;
26
27    println!("直播间: {} ({})", info.title, info.room_id);
28    println!("主播 mid: {}", info.uid);
29    println!(
30        "状态: live_status={} 分区={}·{}",
31        info.live_status, info.parent_area_name, info.area_name
32    );
33    println!("在线: {} 关注: {}", info.online, info.attention);
34
35    Ok(())
36}
More examples
Hide additional examples
examples/live_web_start.rs (line 53)
36async fn main() -> BpiResult<()> {
37    let stop_if_live = std::env::args().any(|a| a == "--stop-if-live");
38    let stop_only = std::env::args().any(|a| a == "--stop-only");
39    let room_id: i64 = std::env::var("BILI_ROOM_ID")
40        .ok()
41        .and_then(|s| s.parse().ok())
42        .unwrap_or(DEFAULT_ROOM_ID);
43    let area_id: u64 = std::env::var("BILI_AREA_ID")
44        .ok()
45        .and_then(|s| s.parse().ok())
46        .unwrap_or(DEFAULT_AREA_ID);
47
48    let bpi = account::authenticated_client()?;
49
50    println!("=== Rust 网页自动开播验证 ===");
51    println!("room_id={room_id} area_v2={area_id}");
52
53    let live = bpi.live();
54    let info = live.room_info(room_id).await?;
55    println!(
56        "当前状态: live_status={} title={} area={}·{}",
57        info.live_status, info.title, info.parent_area_name, info.area_name
58    );
59
60    if !mutating_enabled() {
61        println!("{MUTATING_ENV}=1 未设置,只读取直播间状态,不执行开播、关播或获取推流码。");
62        return Ok(());
63    }
64
65    if stop_only {
66        if info.live_status == 1 {
67            println!("执行关播...");
68            let stop = live.live_stop(room_id as u64, "pc").await?;
69            println!("关播结果: status={}", stop.status);
70            tokio::time::sleep(std::time::Duration::from_secs(3)).await;
71        } else {
72            println!("当前未开播,跳过关播接口。");
73        }
74
75        let after = live.room_info(room_id).await?;
76        println!(
77            "验证: live_status={} ({})",
78            after.live_status,
79            if after.live_status == 0 {
80                "关播成功"
81            } else {
82                "仍在直播中"
83            }
84        );
85        return Ok(());
86    }
87
88    if info.live_status == 1 {
89        if stop_if_live {
90            println!("已在直播,--stop-if-live:先关播...");
91            let stop = live.live_stop(room_id as u64, "pc").await?;
92            println!("关播结果: status={}", stop.status);
93            tokio::time::sleep(std::time::Duration::from_secs(2)).await;
94        } else {
95            println!("已在直播中。若要完整验证开播链路,请加 --stop-if-live 或先手动关播。");
96            println!("仍尝试 FetchWebUpStreamAddr(只读)...");
97            let stream = live.live_fetch_web_up_stream_addr().await?;
98            println!("推流地址: {}{}", stream.addr.addr, mask(&stream.addr.code));
99            return Ok(());
100        }
101    }
102
103    println!("\n[1/2] FetchWebUpStreamAddr...");
104    let stream = live.live_fetch_web_up_stream_addr().await?;
105    println!("  rtmp: {}{}", stream.addr.addr, mask(&stream.addr.code));
106
107    println!("\n[2/2] WebLiveCenterStartLive (WBI)...");
108    let start = live.live_web_center_start(room_id as u64, area_id).await?;
109    println!("  status={} live_key={}", start.status, start.live_key);
110    if let Some(rtmp) = &start.rtmp {
111        println!("  rtmp(响应): {}{}", rtmp.addr, mask(&rtmp.code));
112    } else {
113        println!("  rtmp(响应): null(正常,推流码以 Fetch 为准)");
114    }
115
116    tokio::time::sleep(std::time::Duration::from_secs(2)).await;
117    let after = live.room_info(room_id).await?;
118    println!(
119        "\n验证: live_status={} ({})",
120        after.live_status,
121        if after.live_status == 1 {
122            "开播成功"
123        } else {
124            "未变为直播中(可能需 OBS 推流)"
125        }
126    );
127
128    Ok(())
129}
Source

pub fn manga(&self) -> MangaClient<'_>

创建 manga 领域客户端。

Source

pub fn misc(&self) -> MiscClient<'_>

创建 misc 领域客户端。

Source

pub fn message(&self) -> MessageClient<'_>

创建 message 领域客户端。

Source

pub fn note(&self) -> NoteClient<'_>

创建 note 领域客户端。

Source

pub fn opus(&self) -> OpusClient<'_>

创建 opus 领域客户端。

Source

pub fn search(&self) -> SearchClient<'_>

创建 search 领域客户端。

Source

pub fn video(&self) -> VideoClient<'_>

创建 video 领域客户端。

Examples found in repository?
examples/module_clients.rs (line 19)
9async fn main() -> BpiResult<()> {
10    let client = client_from_env()?;
11    let video_params = VideoViewParams::from_bvid("BV1xx411c7mD".parse::<Bvid>()?);
12    let bangumi_params = BangumiInfoParams::new(MediaId::new(28_220_978)?);
13
14    if !run_live_example() {
15        println!("module-client 快速示例已编译;设置 BPI_RUN_EXAMPLE=1 后会发起真实网络请求");
16        return Ok(());
17    }
18
19    let video = client.video().view(video_params).await?;
20    println!("video: {}", video.title);
21
22    let bangumi = client.bangumi().info(bangumi_params).await?;
23    println!("bangumi: {}", bangumi.media.title);
24
25    if env::var_os("BPI_COOKIE").is_some() {
26        let nav = client.login().nav().await?;
27        println!("logged in: {}", nav.is_login);
28    }
29
30    Ok(())
31}
More examples
Hide additional examples
examples/video_info.rs (line 24)
21async fn main() -> BpiResult<()> {
22    let bvid = video_bvid()?;
23    let client = BpiClient::new()?;
24    let video = client.video();
25
26    let view = video.view(VideoViewParams::from_bvid(bvid.clone())).await?;
27    println!(
28        "视频: {} ({}) UP={} 播放={} 点赞={}",
29        view.title, view.bvid, view.owner.name, view.stat.view, view.stat.like
30    );
31
32    let pages = video
33        .page_list(VideoPageListParams::from_bvid(bvid.clone()))
34        .await?;
35    println!("分 P 数: {}", pages.len());
36    for page in pages.iter().take(5) {
37        println!("  P{} cid={} {}", page.page, page.cid, page.part);
38    }
39
40    let desc = video.desc(VideoDescParams::from_bvid(bvid)).await?;
41    let first_line = desc.lines().next().unwrap_or("");
42    println!("简介首行: {first_line}");
43
44    Ok(())
45}
Source

pub fn video_ranking(&self) -> VideoRankingClient<'_>

创建 video ranking 领域客户端。

Source

pub fn vip(&self) -> VipClient<'_>

创建 VIP 领域客户端。

Source

pub fn wallet(&self) -> WalletClient<'_>

创建 wallet 领域客户端。

Source

pub fn user(&self) -> UserClient<'_>

创建 user 领域客户端。

Source

pub fn web_widget(&self) -> WebWidgetClient<'_>

创建 web widget 领域客户端。

Source

pub fn from_config(config: &Account) -> Result<Self, BpiError>

从结构化账号配置创建客户端。

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more