Twitter DM 批量并发发送库 (Rust 实现, 提供 Python 绑定)
Project description
Twitter DM Python
基于 Rust 开发的 Twitter 私信批量发送库,提供了单条和批量并发发送私信的功能。
✨ 功能特性
- 🚀 单条私信发送: 向指定用户发送单条私信
- 📦 批量并发发送: 同时向多个用户发送私信,提高效率
- 🔒 安全认证: 基于 cookies 的 Twitter 认证机制
- 📝 详细日志: 完整的发送日志和错误追踪
- ⚡ 高性能: 使用 Tokio 实现真正的并发请求
- 🐍 Python 绑定: 通过 PyO3 提供 Python 接口
📦 安装
从源码构建 Python 扩展
# 安装 maturin (Python 包构建工具)
pip install maturin
# 开发模式安装 (快速测试)
maturin develop
# 或者构建 release wheel
maturin build --release
使用 Rust
在 Cargo.toml 中添加依赖:
[dependencies]
x_dm_python = { path = "." }
tokio = { version = "1", features = ["full"] }
🚀 快速开始
Python 使用示例
import x_dm_python
# 初始化客户端 (需要有效的 cookies)
cookies = "ct0=your_csrf_token; auth_token=your_auth_token; twid=u%3D123456789"
client = x_dm_python.Twitter(cookies)
# 发送单条私信
result = client.send_direct_message("123456789", "Hello from Python!")
if result.success:
print(f"私信发送成功! Event ID: {result.event_id}")
else:
print(f"私信发送失败: {result.error_msg}")
# 批量发送私信
user_ids = ["user_id_1", "user_id_2", "user_id_3"]
message = "这是一条批量测试消息!"
batch_result = client.send_batch_direct_messages(user_ids, message)
print(f"成功: {batch_result.success_count}, 失败: {batch_result.failure_count}")
for res in batch_result.results:
if res.success:
print(f"用户 {res.user_id} 发送成功")
else:
print(f"用户 {res.user_id} 发送失败: {res.error_msg}")
Rust 使用示例
use x_dm_python::Twitter;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 初始化客户端
let cookies = "ct0=your_csrf_token; auth_token=your_auth_token; twid=u%3D123456789";
let client = Twitter::new(cookies.to_string(), None)?;
// 发送单条私信
let result = client.send_direct_message("123456789", "Hello, World!").await?;
if result.success {
println!("私信发送成功!");
}
// 批量发送私信
let user_ids = vec!["123456789".to_string(), "987654321".to_string()];
let results = client.send_batch_direct_messages(user_ids, "批量消息", None).await?;
println!("成功: {}, 失败: {}", results.success_count, results.failure_count);
Ok(())
}
📖 API 文档
Twitter 类
Python API
Twitter(cookies: str, proxy_url: Optional[str] = None): 创建 Twitter 客户端send_direct_message(user_id: str, message: str) -> DMResult: 发送单条私信send_batch_direct_messages(user_ids: List[str], message: str, client_transaction_ids: Optional[List[str]] = None) -> BatchDMResult: 批量发送私信validate_cookies() -> bool: 验证 cookies 是否有效get_cookies() -> str: 获取当前 cookies
Rust API
Twitter::new(cookies: String, proxy_url: Option<String>) -> Result<Self>: 创建 Twitter 客户端async fn send_direct_message(&self, user_id: &str, message: &str) -> Result<DMResult>: 发送单条私信async fn send_batch_direct_messages(&self, user_ids: Vec<String>, message: &str, client_transaction_ids: Option<Vec<String>>) -> Result<BatchDMResult>: 批量发送私信fn validate_cookies(&self) -> bool: 验证 cookies 是否有效
DMResult 结构体
| 字段 | 类型 | 说明 |
|---|---|---|
success |
bool |
发送是否成功 |
user_id |
str/String |
目标用户ID |
message |
str/String |
发送的消息内容 |
error_msg |
str/String |
错误信息(如果有) |
http_status |
int/u16 |
HTTP 状态码 |
event_id |
Optional[str]/Option<String> |
Twitter 响应中的事件ID |
BatchDMResult 结构体
| 字段 | 类型 | 说明 |
|---|---|---|
success_count |
int/usize |
成功发送的数量 |
failure_count |
int/usize |
发送失败的数量 |
results |
List[DMResult]/Vec<DMResult> |
每个私信的详细发送结果 |
🔐 获取 Twitter Cookies
- 在浏览器中登录 Twitter
- 打开开发者工具 (F12)
- 转到 Network 标签页
- 发送一条私信
- 在请求头中找到 Cookie 字段
- 复制完整的 Cookie 值
重要: 请确保 cookies 包含以下必要字段:
ct0: CSRF令牌auth_token: 认证令牌twid: 用户ID
⚠️ 注意事项
安全性
- 🔐 保护 cookies: 不要在代码中硬编码 cookies,使用环境变量或配置文件
- 🚫 避免滥用: 遵守 Twitter 的使用条款,避免发送垃圾信息
- ⏱️ 请求频率: 注意控制请求频率,避免触发反垃圾机制
性能优化
- 📊 并发控制: 批量发送时自动并发,无需手动控制
- ⏰ 超时设置: 默认请求超时 30 秒
- 📝 日志级别: 使用环境变量
RUST_LOG=debug设置日志级别
🏗️ 架构设计
本项目采用组合模式 + Trait 抽象的模块化架构:
模块组织
- common 模块: 认证、HTTP 客户端、错误处理
- dm 模块: 私信发送功能
- tweet 模块: 帖子相关功能(计划中)
- lib.rs: 聚合导出层
使用方式
聚合使用(推荐)
use x_dm_python::Twitter;
let twitter = Twitter::new(cookies, proxy)?;
twitter.dm().send_message("user_id", "message").await?;
独立模块使用
use x_dm_python::dm::{DMClient, DMService};
let dm = DMClient::new(auth, client);
dm.send_message("user_id", "message").await?;
技术栈
- 🚀 并发: Tokio 异步运行时
- 🔌 Python 绑定: PyO3
- 📝 日志: tracing
- 🔒 错误处理: Result<T, E>
- 📦 JSON: serde_json
- 🌐 HTTP: reqwest
📝 开发
构建
# 构建 Rust 库
cargo build
# 构建带 Python 绑定的库
cargo build --features python
# 运行测试
cargo test
# 构建 Python wheel
maturin build --release
测试
# Rust 单元测试
cargo test
# Python 测试 (需先安装)
maturin develop
python -m pytest tests/
📜 许可证
MIT License
🔗 相关链接
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distributions
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file x_dm_python-1.1.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.
File metadata
- Download URL: x_dm_python-1.1.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
- Upload date:
- Size: 2.2 MB
- Tags: CPython 3.8+, manylinux: glibc 2.17+ x86-64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c96ba21c64f53a723fb4450d070b53a3ff4b51b34c99ac76e98ce031d189deb2
|
|
| MD5 |
7dbb050bd67e7ceb60850ed6c1a18edc
|
|
| BLAKE2b-256 |
890faf57c325f35e2afe881cd5be7755293703185b47a2fef56e37ce3f979626
|
Provenance
The following attestation bundles were made for x_dm_python-1.1.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:
Publisher:
build-and-release.yml on Robin528919/x_dm_python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
x_dm_python-1.1.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl -
Subject digest:
c96ba21c64f53a723fb4450d070b53a3ff4b51b34c99ac76e98ce031d189deb2 - Sigstore transparency entry: 598450778
- Sigstore integration time:
-
Permalink:
Robin528919/x_dm_python@c66baaed62f6d43447e355af029e532a6f79cfa3 -
Branch / Tag:
refs/tags/release-v1.1.0 - Owner: https://github.com/Robin528919
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
build-and-release.yml@c66baaed62f6d43447e355af029e532a6f79cfa3 -
Trigger Event:
push
-
Statement type:
File details
Details for the file x_dm_python-1.1.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.
File metadata
- Download URL: x_dm_python-1.1.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
- Upload date:
- Size: 2.1 MB
- Tags: CPython 3.8+, manylinux: glibc 2.17+ ARM64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b6d4e02b42266c869f3e3dd3fde150e08222b8eab46dd3933940615df6d772d2
|
|
| MD5 |
5a811715849e7db0dbef56d557a66699
|
|
| BLAKE2b-256 |
6e84e5d950240758597d7364b3ed3d2418a7a6629b1c25051636fe5b9c541e8a
|
Provenance
The following attestation bundles were made for x_dm_python-1.1.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:
Publisher:
build-and-release.yml on Robin528919/x_dm_python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
x_dm_python-1.1.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl -
Subject digest:
b6d4e02b42266c869f3e3dd3fde150e08222b8eab46dd3933940615df6d772d2 - Sigstore transparency entry: 598450766
- Sigstore integration time:
-
Permalink:
Robin528919/x_dm_python@c66baaed62f6d43447e355af029e532a6f79cfa3 -
Branch / Tag:
refs/tags/release-v1.1.0 - Owner: https://github.com/Robin528919
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
build-and-release.yml@c66baaed62f6d43447e355af029e532a6f79cfa3 -
Trigger Event:
push
-
Statement type:
File details
Details for the file x_dm_python-1.1.0-cp38-abi3-macosx_10_13_x86_64.macosx_11_0_arm64.macosx_10_13_universal2.whl.
File metadata
- Download URL: x_dm_python-1.1.0-cp38-abi3-macosx_10_13_x86_64.macosx_11_0_arm64.macosx_10_13_universal2.whl
- Upload date:
- Size: 3.9 MB
- Tags: CPython 3.8+, macOS 10.13+ universal2 (ARM64, x86-64), macOS 10.13+ x86-64, macOS 11.0+ ARM64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3c1e87f6c52ab6182e58b3d55f60d9457e6d3c67741eae555d4a6bbf6281344d
|
|
| MD5 |
967d0ba44e9a27e426e0cff0f337250e
|
|
| BLAKE2b-256 |
72e4cc851e69a41ed61405686254a4b09474a8feed6aff3deaa8ca2812204d5f
|
Provenance
The following attestation bundles were made for x_dm_python-1.1.0-cp38-abi3-macosx_10_13_x86_64.macosx_11_0_arm64.macosx_10_13_universal2.whl:
Publisher:
build-and-release.yml on Robin528919/x_dm_python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
x_dm_python-1.1.0-cp38-abi3-macosx_10_13_x86_64.macosx_11_0_arm64.macosx_10_13_universal2.whl -
Subject digest:
3c1e87f6c52ab6182e58b3d55f60d9457e6d3c67741eae555d4a6bbf6281344d - Sigstore transparency entry: 598450771
- Sigstore integration time:
-
Permalink:
Robin528919/x_dm_python@c66baaed62f6d43447e355af029e532a6f79cfa3 -
Branch / Tag:
refs/tags/release-v1.1.0 - Owner: https://github.com/Robin528919
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
build-and-release.yml@c66baaed62f6d43447e355af029e532a6f79cfa3 -
Trigger Event:
push
-
Statement type: