ig igchat-v2 v3.1.0 ← kryvnix.com
PyPI ↗ GitHub ↗
IGChat-v2 · Documentation

igchat-v2 v3.1.0 — Async Instagram Direct & Polaris API

Thư viện Python asyncio + httpx chuyên biệt cho giao thức Instagram Direct DGW WebSocket, Slide GraphQL và Polaris Web REST API, kết hợp companion Go Bridge (instameow) qua JSON-RPC 2.0 — phát triển bởi Phước Toàn (0xshijn).

$ pip install igchat-v2
LAYER 01Python SDK
IGClient / Bot
LAYER 02Stealth & Export
GhostMode / HTML
LAYER 03Polaris & Rupload
httpx.AsyncClient
LAYER 04Go Bridge RPC
instameow · DGW

Zero-Presence GhostMode

Đọc toàn bộ Direct mà không gửi Read Receipt ("Đã xem"), đồng thời triệt tiêu presence broadcast X-IG-Presence: 0.

Anti-Unsend & Forensic Archive

Hứng sự kiện tin nhắn trước khi bị đối phương thu hồi và xuất nguyên lịch sử kèm media ra file HTML Dark Mode, JSON hoặc Markdown.

Go Bridge JSON-RPC 2.0

Tiến trình igchat-bridge (v3.0.0, Go 1.23+) xử lý DGW WebSocket real-time với generation-fencing và tự kết nối lại theo backoff.

Security Hardened

Kiểm tra SSRF trước khi tải media, Encrypted Vault (PBKDF2), khóa file 0600 và che bí mật tự động trong log.

Cài đặt & Môi trường #

igchat-v2 yêu cầu Python 3.10+ và đã có mặt chính thức trên PyPI. Nếu chỉ gọi API gửi tin, lấy profile, quản trị hội thoại qua Polaris GraphQL/REST thì chỉ cần gói Python; khi chạy listener thời gian thực sẽ dùng kèm binary Go Bridge (build/igchat-bridge).

Terminal · PyPI hoặc Source
# Cách 1: Cài trực tiếp từ PyPI
pip install igchat-v2

# Cách 2: Clone mã nguồn kèm bộ test
git clone https://github.com/0xshijn/igchat-v2.git
cd igchat-v2
pip install -e ".[dev]"

Mô hình Async & IGClient #

IGClient (igchat.client) là cổng thống nhất cho toàn bộ thao tác nhắn tin, media, theme/poll, notes, export và đăng ký bộ lọc sự kiện @client.on(...). Nên bọc trong async with để tự động giải phóng pool kết nối httpx.AsyncClient.

class IGClient(session, *, stealth: bool = False, humanizer: Humanizer | None = None, client: httpx.AsyncClient | None = None)
python · Khởi tạo IGClient với Context Manager
import asyncio
from igchat import IGClient

async def main() -> None:
    cookie = "sessionid=...; ds_user_id=...; csrftoken=...;"
    async with await IGClient.from_cookie(cookie, stealth=True) as client:
        print("Logged in User ID:", client.user_id)
        await client.send_message("17845618319961946", "Hello from IGClient!")

asyncio.run(main())

Session, Cookie & Web Login 2FA #

Bạn có thể nạp phiên trực tiếp từ chuỗi Cookie trình duyệt bằng bootstrap_session hoặc đăng nhập bằng tài khoản/mật khẩu (hỗ trợ mã TOTP / 2FA) qua login_with_credentials. Thư viện còn cung cấp FileSessionStorage và EnvSessionStorage để lưu/nạp session an toàn.

async bootstrap_session(cookie_source, *, client=None, timeout=..., user_agent=...) -> InstagramSession
async login_with_credentials(username, password, *, totp_secret=None, two_factor_code=None, hydrate_session=True, client=None, timeout=..., user_agent=...) -> LoginResult
python · Bootstrap Cookie & Đăng nhập 2FA TOTP
from igchat.auth import bootstrap_session, login_with_credentials, FileSessionStorage

# 1) Từ Cookie Header String hoặc Dict
session = await bootstrap_session("sessionid=...; ds_user_id=...; csrftoken=...;")

# 2) Hoặc đăng nhập Web AJAX có 2FA TOTP
login_res = await login_with_credentials("my_username", "my_password", totp_secret="JBSWY3DPEHPK3PXP")

# Lưu an toàn xuống file quyền 0600
store = FileSessionStorage("ig_session.json")
store.save(session)

Encrypted Vault (PBKDF2) #

Tránh lưu cookie thuần dạng plaintext trên đĩa bằng export_vault_session và load_vault_session (dẫn xuất khóa bằng PBKDF2 kèm stream cipher xác thực). Có thể mở client trực tiếp bằng IGClient.from_vault.

python · Mã hóa & Khôi phục Session Vault
from igchat import IGClient
from igchat.auth import bootstrap_session, export_vault_session

session = await bootstrap_session("sessionid=...; ds_user_id=...; csrftoken=...;")
vault_json = export_vault_session(session, passphrase="strong-passphrase")

# Khởi tạo trực tiếp từ file vault hoặc chuỗi JSON vault
async with IGClient.from_vault(vault_json, "strong-passphrase", stealth=True) as client:
    print("Vault user:", client.user_id)

GhostMode & Humanizer #

igchat.stealth cung cấp 2 lớp bảo vệ danh tính tài khoản: GhostMode (chặn header/receipt "Đã xem") và Humanizer (tính toán thời gian đọc/gõ phím theo phân phối chuẩn Gaussian).

Thành phầnTham số / Thuộc tínhChức năng
GhostMode(enabled=True).enable(), .disable(), .build_stealth_headers(), .should_suppress_receipt(thread_id)Trả về header X-IG-Presence: 0 & X-IG-Disable-Read-Receipt: 1, chặn read receipt.
Humanizer(...)reading_wpm=240.0, typing_wpm=65.0, min_typing_sec=0.8, max_typing_sec=6.0Tính độ trễ đọc (calculate_reading_delay), gõ (calculate_typing_delay), hoặc chờ thực tế với simulate_human_pacing.

Gửi, Sửa, Thu hồi & React Tin Nhắn #

Hệ thống nhắn tin hỗ trợ cả 2 giao diện: phương thức bất đồng bộ trên IGClient (có sẵn human pacing & chế độ silent=True) và các hàm low-level trong igchat.direct.messages.

await client.send_message(thread_id, text, *, reply_to_id=None, silent=False, simulate_human=False) -> dict
await send_text_message(session, thread_id, text, *, reply_to_id=None, client=None, timeout=...)
Tham số / HàmKiểuMô tả chi tiết
thread_idint | strID cuộc trò chuyện Instagram Direct (inbox cá nhân hoặc group thread).
textstrNội dung tin nhắn văn bản (UTF-8, emoji).
reply_to_idstr | Nonemessage_id gốc nếu muốn trích dẫn / trả lời (Quote Reply).
silentboolKhi True, tự động định dạng @silent qua format_silent_message(text) để gửi không chuông thông báo.
simulate_humanboolTạm dừng theo tốc độ gõ phím thực của Humanizer trước khi gửi gói tin.
python · Gửi tin thường, Reply, @silent, Sửa, Thu hồi & React
import asyncio
from igchat import IGClient

async def main() -> None:
    async with await IGClient.from_cookie("sessionid=...; ds_user_id=...; csrftoken=...;") as client:
        tid = "17845618319961946"

        # 1. Gửi tin nhắn thường kèm mô phỏng gõ phím
        sent = await client.send_message(tid, "Chào bro 👋", simulate_human=True)
        msg_id = sent.get("item_id") or sent.get("message_id")

        # 2. Reply một tin nhắn cũ + chế độ @silent không rung chuông
        await client.send_message(tid, "Nhắn khẽ lúc nửa đêm", reply_to_id=msg_id, silent=True)

        # 3. Thả cảm xúc emoji (React)
        await client.react(tid, msg_id, emoji="🔥")

        # 4. Sửa nội dung tin đã gửi (trong cửa sổ chỉnh sửa của IG)
        await client.edit_message(tid, msg_id, "Chào bro (đã sửa)!")

        # 5. Thu hồi tin nhắn (Unsend)
        await client.unsend_message(tid, msg_id)

asyncio.run(main())
Low-level Polaris Functions (igchat.direct) Nếu không dùng IGClient, có thể gọi trực tiếp send_text_message, edit_text_message, unsend_text_message và react_to_message bằng InstagramSession.

Upload Ảnh, Video Rupload & Voice #

Hỗ trợ đẩy binary ảnh/video trực tiếp lên hạ tầng Instagram Rupload qua client.send_photo / client.send_video hoặc hàm chi tiết trong igchat.direct.media, kèm tạo waveform voice 64 peaks từ audio raw.

python · Gửi ảnh, video Rupload & Voice Waveform
from pathlib import Path
from igchat.direct import (
    upload_photo_rupload,
    upload_video_rupload,
    generate_waveform_peaks,
    format_voice_note_metadata,
)

# Đẩy ảnh hoặc video bytes qua IGClient
await client.send_photo("17845618319961946", Path("demo.jpg").read_bytes())
await client.send_video("17845618319961946", Path("clip.mp4").read_bytes())

# Hoặc gọi trực tiếp kèm upload_id tùy chỉnh
res = await upload_photo_rupload(client.session, image_bytes=Path("demo.jpg").read_bytes())

# Tạo waveform 64 peaks cho Voice Note
peaks = generate_waveform_peaks(audio_bytes, num_peaks=64)
meta = format_voice_note_metadata(duration_ms=4200, waveform=peaks)

DirectListener Thời Gian Thực #

DirectListener kết nối qua Go Bridge (BridgeProcess) tới DGW WebSocket của Instagram, phát sinh các sự kiện realtime bao gồm tin nhắn mới (on_message), sửa tin (on_edit) và thu hồi tin (on_unsend — phục vụ Anti-Unsend).

python · Echo Bot thời gian thực (examples/echo_bot.py)
import asyncio
from igchat.auth import bootstrap_session
from igchat.direct import DirectListener

async def main() -> None:
    session = await bootstrap_session("sessionid=...; ds_user_id=...; csrftoken=...;")
    listener = DirectListener(session=session)

    async def on_message_received(event: dict) -> None:
        data = event.get("data", {})
        thread_id = data.get("threadId") or data.get("thread_id")
        sender_id = str(data.get("senderId") or data.get("sender_id") or "")
        text = str(data.get("text") or "").strip()

        if sender_id == str(session.ig_user_id):
            return
        if text.startswith("!echo ") and thread_id:
            await listener.actions.send_message(thread_id=thread_id, text=f"Echo: {text[6:]}")

    listener.on_message(on_message_received)
    listener.on_unsend(lambda ev: print("[ANTI-UNSEND]", ev))

    try:
        await listener.start()
    finally:
        await listener.aclose()

asyncio.run(main())

Go Bridge & JSON-RPC 2.0 Contract #

Tiến trình companion viết bằng Go (bridge/main.go, igchat-bridge v3.0.0, thư viện instameow) nhận lệnh qua stdin và đẩy event/kết quả từng dòng stdout theo chuẩn JSON-RPC 2.0, hỗ trợ chính sách tự kết nối lại ReconnectPolicy và cảnh báo ConnectionStatus.

RPC MethodTham số chínhChức năng
ping / health / status{}Kiểm tra heartbeat, memory/uptime và trạng thái DGW (connected / disconnected).
connect / disconnect{"cookies", "proxy"}Khởi chạy hoặc ngắt kết nối WebSocket DGW Instagram Direct.
send_message / edit_message / unsend_message{"thread_id", "text", "message_id", "reply_to"}Thao tác tin nhắn Direct trực tiếp qua Go bridge với độ trễ thấp.
react_message / send_typing / mark_read{"thread_id", "emoji", "is_typing", "message_id"}Thả reaction, gửi trạng thái đang nhập và đánh dấu đã đọc.
fetch_inbox / fetch_thread{"limit", "cursor", "thread_id"}Tải danh sách hộp thư và lịch sử chi tiết từng hội thoại.
create_group / set_title / add_participants / remove_participant / leave_thread{"thread_id", "title", "user_ids"}Quản trị nhóm Direct đầy đủ (tạo nhóm, đổi tên, thêm/xóa thành viên, rời nhóm).
set_theme / set_emoji / upload_media{"thread_id", "theme_id", "url"}Đổi giao diện chat, custom emoji và đường ống upload media đã qua SSRF guard.
bash · Tự biên dịch Go Bridge từ thư mục bridge/
cd bridge
go test -v ./...
go build -trimpath -ldflags="-s -w -X main.bridgeVersion=3.0.0" -o ../build/igchat-bridge .

Quản trị Hội thoại, Polls, Themes & Notes #

Đầy đủ API lấy danh sách hộp thư, duyệt tin nhắn chờ, đổi tên nhóm, phân quyền Admin nhóm, tạo bình chọn Direct Poll, đổi Theme (ChatTheme) và đăng/xóa Instagram Notes (hỗ trợ tìm nhạc đính kèm).

python · Threads, Polls, Themes & Instagram Notes
from igchat.direct import (
    fetch_inbox_threads, fetch_thread_detail, accept_message_request,
    rename_thread, promote_admin, demote_admin, mute_thread_rest,
    create_note, search_note_music,
)

inbox = await fetch_inbox_threads(session, limit=20)
await rename_thread(session, thread_id="...", new_title="0xShiinn Squad")
await promote_admin(session, thread_id="...", target_user_id="123456")

# Poll & Theme qua IGClient
await client.create_poll(tid, "Chốt kèo CTF tối nay?", ["Ok chiến", "Mai nha"])
await client.set_theme(tid, "cyberpunk")

# Instagram Notes kèm nhạc
music = await search_note_music(session, "Khi 22")
await client.post_note("Đang debug Ring-0")

Social API, Profile & Follower Analytics #

Module igchat.social xử lý tra cứu người dùng, sửa bio, tương tác bài viết (like/save/comment/đăng ảnh), quản lý Close Friends, xem Story Viewers và thống kê quan hệ Follow qua FollowerAnalytics.

python · Phân tích Unfollowers, Profile & Tương tác Post
from igchat.social import (
    get_user_profile, search_users, change_bio,
    analyze_relationships, fetch_close_friends, fetch_notifications,
    shortcode_to_media_id, publish_photo,
)

user = await get_user_profile(session, "0xshijn")
stats = analyze_relationships(following_list, followers_list)
print("Không follow lại:", stats.total_unrequited, "| Mutual:", stats.total_mutual)

# Qua IGClient: like, comment, save, follow, block
await client.like("C8xyz123Abc")
await client.comment("C8xyz123Abc", "Clean research!")

Forensic Archiver & Xuất Hội Thoại #

Module igchat.export hỗ trợ xuất lịch sử tin nhắn đã tải ra 3 định dạng độc lập: HTML Dark Mode (tự chứa, hiển thị đúng bố cục chat), JSON và Markdown.

python · Xuất HTML Dark Mode, Markdown & JSON
# Xuất nhanh bằng IGClient (phân trang tự động theo message_limit)
html_doc = await client.export_thread("17845618319961946", format="html", message_limit=200)
md_doc   = await client.export_thread("17845618319961946", format="markdown", message_limit=200)
json_doc = await client.export_thread("17845618319961946", format="json", message_limit=200)

Composable Event Filters #

Bộ lọc sự kiện khai báo trong igchat.filters cho phép kết hợp tự nhiên bằng toán tử bit của Python: & (AND), | (OR), ~ (NOT), ^ (XOR).

FilterLoạiĐiều kiện khớp sự kiện
filters.all / filters.textSingletonMọi event / Event chứa nội dung chữ khác rỗng.
filters.command(cmds, prefixes=("/","!"))FactoryKhớp lệnh mở đầu bằng tiền tố (vd: /ping, !echo).
filters.regex(pattern)FactoryTìm kiếm khớp biểu thức chính quy trong nội dung tin nhắn.
filters.media / .photo / .video / .voiceSingletonTin nhắn đính kèm media nói chung hoặc theo từng định dạng.
filters.private (.dm) / filters.groupSingletonPhân biệt chat riêng 1-1 và cuộc trò chuyện nhóm.
filters.story_reply / .reaction / .silentSingletonPhản hồi Story, thả emoji reaction hoặc tin nhắn @silent.
filters.sender(*ids) / filters.thread(*ids)FactoryGiới hạn theo ID người gửi hoặc Thread ID cụ thể.
python · Kết hợp Filters với @client.on(...)
from igchat import filters

@client.on((filters.command("ban") & filters.group) | filters.sender("123456789"))
async def handle_mod(event: dict) -> None:
    ...

@client.on(filters.photo & ~filters.silent)
async def handle_loud_photo(event: dict) -> None:
    ...

Bot Framework & PerUserRateLimiter #

igchat.bot đóng gói sẵn khung chạy bot 24/7: InstagramBot (hỗ trợ is_admin, reply, handle_event), bộ chống flood PerUserRateLimiter, nạp cấu hình từ JSON qua load_bot_config(config_path) và hàm khởi chạy run_bot / main_blocking.

python · Khởi chạy Bot Framework
from igchat.bot import main_blocking

# Nạp config.json, khởi tạo session + Go Bridge + rate limiter tự động
main_blocking("config.json")

Bảng Tra Cứu Nhanh Toàn Bộ API #

Ký hiệu / APIModuleMục đích
IGClient.from_cookie / from_vaultigchat.clientKhởi tạo Async SDK thống nhất
client.send_message / send_text_messageigchat.direct.messagesGửi tin nhắn Direct, reply, @silent
client.edit_message / edit_text_messageigchat.direct.messagesChỉnh sửa tin nhắn đã gửi
client.unsend_message / unsend_text_messageigchat.direct.messagesThu hồi (unsend) tin nhắn
client.react / react_to_messageigchat.direct.messagesThả / gỡ cảm xúc emoji
upload_photo_rupload / upload_video_ruploadigchat.direct.mediaTải ảnh/video lên Rupload CDN
generate_waveform_peaksigchat.direct.voiceTạo 64 peaks waveform voice note
DirectListenerigchat.direct.listenerNhận event message / edit / unsend realtime
BridgeProcess / BridgeActions / ReconnectPolicyigchat.bridgeQuản lý tiến trình Go JSON-RPC 2.0
fetch_inbox_threads / fetch_thread_detail / rename_threadigchat.direct.threadsĐọc hộp thư, đổi tên, admin nhóm
create_direct_poll / set_thread_theme / create_noteigchat.directBình chọn, đổi theme & Instagram Notes
bootstrap_session / login_with_credentialsigchat.authKhởi tạo phiên cookie & web login 2FA
export_vault_session / load_vault_sessionigchat.auth.vaultMã hóa/giải mã session vault PBKDF2
GhostMode / Humanizerigchat.stealthChế độ tàng hình & gõ phím Gaussian
get_user_profile / analyze_relationships / like_mediaigchat.socialHồ sơ, phân tích unfollower & post
export_thread_to_html / json / markdownigchat.exportXuất lịch sử hội thoại offline
filters.command / regex / media / private / groupigchat.filtersLọc sự kiện tổ hợp (&, |, ~, ^)
InstagramBot / PerUserRateLimiter / run_botigchat.botKhung bot đa người dùng kèm giới hạn

Xử lý Ngoại lệ (Exception Hierarchy) #

Tất cả lỗi đều kế thừa từ lớp gốc IGChatError (igchat.core.errors) giúp bắt ngoại lệ rõ ràng theo từng tầng:

Exception ClassKế thừa từNguyên nhân & Thông tin thêm
IGChatErrorExceptionNgoại lệ gốc của toàn bộ thư viện.
SecurityViolationErrorIGChatError, ValueErrorVi phạm biên SSRF, đường dẫn hoặc tham số không an toàn.
SessionError / SessionCookieErrorIGChatErrorKhông thể khởi tạo/refresh session, hoặc thiếu cookie bắt buộc.
AuthenticationErrorIGChatErrorInstagram từ chối đăng nhập hoặc vô hiệu hóa phiên hiện tại.
CheckpointRequiredErrorAuthenticationErrorTài khoản vướng challenge/checkpoint (.checkpoint_path).
BridgeError / BridgeProtocolErrorIGChatErrorGo Bridge RPC thất bại hoặc sai hợp đồng JSON-RPC (.error_code, .retryable).

Bảo mật & SSRF Guard #

Nguyên tắc vận hành Thư viện dùng cookie/phiên tài khoản Instagram cá nhân: tuyệt đối không commit config.json hoặc in thẳng sessionid lên stdout/stderr công cộng.
  • SSRF Guard (validate_public_http_url & download_public_bytes): Phân giải DNS và chặn truy cập IP loopback, link-local, RFC 1918 trước khi tải media.
  • Log Redaction (redact_sensitive_data & sanitize_log_message): Tự động che dấu cookie, token và chữ ký URL nhạy cảm.
  • Private Storage Permissions (set_private_file_permissions): Khóa quyền tệp cookie/vault chỉ cho người dùng sở hữu (POSIX 0600 / Windows ACLs).

Kiểm thử & Bản quyền #

Bộ kiểm thử tự động trong tests/ (14 module test auth, bot, bridge, client, direct, export, filters, social, stealth, vault, voice) vượt qua 50/50 unit tests:

bash · Kiểm thử toàn bộ thư viện
pytest tests/
# ============================= 50 passed in 1.98s =============================

Phát triển bởi Phước Toàn (0xshijn) · Python SDK cấp phép Apache-2.0 · Go Bridge companion cấp phép GPL-3.0-or-later.