I want to create a script that automatically fetch...

생성일: 2025년 6월 17일

답변에 사용된 모델 O3 by Chat01

질문

I want to create a script that automatically fetches configs from 3 Telegram channels (these 3 channels post a number of v2ray configs daily), then pings each one and creates a list showing the best ones based on ping. Then it should automatically connect to the best config in terms of ping and speed. This connection should be made using the v2rayN software.
I want you to write a step-by-step plan that I can give to an AI so it can do this task for me.
To access the Telegram channels, the Telethon library must be used.

사고

Evaluating possible solutions

I need to research if "importSubFromFile" is a valid command for v2rayN, but it seems the official CLI isn't available based on user reports. So, I might need to explore using UI automation or rely on the xray core. Another approach could be manipulating the v2rayN config files directly (like config.vmess.json), followed by restarting the application. I also need to consider automating clipboard interactions with methods like AutoHotkey. I’ll make sure to offer multiple options with notes—still referencing sources for clarity.

Plan for automating v2rayN setup

I'll base my plan on information like the Telethon docs for message fetching and GitHub issues regarding v2rayN's lack of CLI. The steps involve setting up the environment (Python 3, Telethon, etc.), using Telethon for login and message retrieval, then filtering specific configuration strings such as "vmess://" and parsing them. Nodes will be tested via ping and speed, sorted, and the best node will be selected. After that, I’ll either update v2rayN’s config via file, directly manipulate its config, or bypass v2rayN entirely using v2ray core.

Thought for 32 seconds

답변

Below is a high-level, step-by-step blueprint you can hand to an AI agent (or follow yourself) to build the requested “daily best-node picker” around Telethon + v2rayN. Each stage tells the agent what to do, why it matters, and what libraries / APIs to use.


0 | Prerequisites & environment

ItemPurpose
Python ≥ 3.10Core scripting language
TelethonTelegram client SDK
ping3 (or asyncio + raw sockets)ICMP / TCP ping tests
speedtest-cli (optional but useful)Quick throughput check through the proxy
pywin32 or python-mss / pyautoguiUI automation fallback for v2rayN
v2rayN (portable ZIP)User-side GUI client with bundled xray-core
git & VS CodeDev workflow (optional)

Tip – Keep the script and v2rayN in the same top-level folder so the script can find v2rayN/core/xray.exe without hunting for paths.


1 | Log in to Telegram via Telethon

  1. Obtain api_id and api_hash from https://my.telegram.org.
  2. Start a Telethon TelegramClient('session_name', api_id, api_hash).
  3. If the .session file doesn’t exist, prompt the user once for the telephone number and OTP; Telethon stores the session for future runs.
    docs.telethon.dev

2 | Fetch & parse fresh configs from the three channels

  1. Store the target channel usernames or IDs in a list channels = ['@chanA', '@chanB', '@chanC'].

  2. For each channel run:

    python
    async for msg in client.iter_messages(channel, limit=200): for proto in ('vmess://', 'vless://', 'trojan://', 'ss://'): if proto in msg.raw_text: extract each line that starts with proto add to raw_config_strings
  3. Decode each URL:

    • For vmess:// links the part after vmess:// is Base64-encoded JSON.
    • For vless://, trojan://, etc., parse as standard URI (urllib.parse).
  4. Build a Python dict list with at minimum:

    python
    { 'host': 'example.com', 'port': 443, 'type': 'vmess', 'uuid': '…', 'raw_url': 'original link', }

3 | Latency & speed benchmarking

  1. Ping test

    python
    from ping3 import ping rtt = ping(host, unit='ms', timeout=1)

    If ICMP is blocked, open a TCP socket to (host, port) and time the handshake (asyncio.open_connection).

  2. Throughput test (optional / slow)
    Set environment variables ALL_PROXY=socks5://127.0.0.1:port after spinning up each node (see next step) and call speedtest-cli --simple.

  3. Record results as {'rtt_ms': 123, 'dl_Mbps': 42, …}; keep failed pings as None so they can be filtered out.


4 | Choose the best node

python
viable = [n for n in nodes if n['rtt_ms'] is not None] best = sorted(viable, key=lambda n: (n['rtt_ms'], -n.get('dl_Mbps', 0)))[0]

Break ties by download speed or simply lowest latency.


5 | Feed the winner into v2rayN

Problem: v2rayN itself offers no documented CLI switcher — confirmed by the project maintainers. github.com
Work-around: use the bundled xray-core directly or automate the GUI. Two clean options are below; pick whichever your environment tolerates:

OptionHow it worksEffort
A. Drive xray.exe directly (recommended)1. Dump the chosen node into a tiny config.json template.<br>2. Spawn v2rayN\\core\\xray.exe -config config.json as a detached process.<br>3. (Optional) use the gRPC API in xray to tear down / replace the node without killing the process. v2fly.orgSimple, fully headless
B. Automate v2rayN’s GUI1. Start v2rayN if not running.<br>2. Put the raw URL into the clipboard (pyperclip).<br>3. Use pywin32 or pyautogui to send:<br> • Tray-icon right-click → Import from clipboard<br> • Right-click on the imported node → Set as active server.<br>4. Toggle System proxy → Set system proxy.Works but brittle; UI changes break it

6 | Verify connectivity

  1. Sleep 3–5 s.
  2. requests.get('https://1.1.1.1/cdn-cgi/trace', timeout=5) through the proxy.
    Verify the public IP is not your ISP’s.

7 | Schedule & loop

  • Windows Task Scheduler: create a daily task at, e.g., 06:00 with python fetch_and_connect.py.
  • Inside the script wrap everything in asyncio.run(main()) and add proper try/except logging so the task never hangs.

8 | Hardening & polish (nice-to-have)

ConcernMitigation
Channel message spikeCache message IDs and stop once you hit an already-seen one.
Rate limitsOne Telegram request ≈ 200 msgs; keep under 30/sec to avoid flood-waits.
Multiple configs per postRegex can grab them all; they’re separated by line breaks.
JSON templateKeep a template.json with inbound (socks 10808) and routing pre-filled; only swap the outbound section.
Proxy for the speed testRe-export ALL_PROXY before running speedtest-cli.
Log rotationWrite logs to %TEMP%/v2ray_picker.log, rotate weekly.

Deliverables for the AI

  1. fetch_and_connect.py – the full script encapsulating steps 1-7.
  2. template.json – minimal xray/v2rayN JSON with a placeholder outbound.
  3. README.md – one-pager instructions + screenshots if you go the GUI-automation route.

Hand these specs to the agent and let it implement; every part is deterministic, so the AI can write & test the code autonomously.

이 Q&A 공유하기