I want to create a script that automatically fetch...
創建於:2025年6月17日
創建於:2025年6月17日
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.
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.
Item | Purpose |
---|---|
Python ≥ 3.10 | Core scripting language |
Telethon | Telegram 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 / pyautogui | UI automation fallback for v2rayN |
v2rayN (portable ZIP) | User-side GUI client with bundled xray-core |
git & VS Code | Dev 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.
api_id
and api_hash
from https://my.telegram.org.TelegramClient('session_name', api_id, api_hash)
..session
file doesn’t exist, prompt the user once for the telephone number and OTP; Telethon stores the session for future runs.Store the target channel usernames or IDs in a list channels = ['@chanA', '@chanB', '@chanC']
.
For each channel run:
pythonasync 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
Decode each URL:
vmess://
links the part after vmess://
is Base64-encoded JSON.vless://
, trojan://
, etc., parse as standard URI (urllib.parse
).Build a Python dict
list with at minimum:
python{ 'host': 'example.com', 'port': 443, 'type': 'vmess', 'uuid': '…', 'raw_url': 'original link', }
Ping test
pythonfrom 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
).
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
.
Record results as {'rtt_ms': 123, 'dl_Mbps': 42, …}
; keep failed pings as None
so they can be filtered out.
pythonviable = [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.
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:
Option | How it works | Effort |
---|---|---|
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.org | Simple, fully headless |
B. Automate v2rayN’s GUI | 1. 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 |
requests.get('https://1.1.1.1/cdn-cgi/trace', timeout=5)
through the proxy.python fetch_and_connect.py
.asyncio.run(main())
and add proper try/except
logging so the task never hangs.Concern | Mitigation |
---|---|
Channel message spike | Cache message IDs and stop once you hit an already-seen one. |
Rate limits | One Telegram request ≈ 200 msgs; keep under 30/sec to avoid flood-waits. |
Multiple configs per post | Regex can grab them all; they’re separated by line breaks. |
JSON template | Keep a template.json with inbound (socks 10808) and routing pre-filled; only swap the outbound section. |
Proxy for the speed test | Re-export ALL_PROXY before running speedtest-cli . |
Log rotation | Write logs to %TEMP%/v2ray_picker.log , rotate weekly. |
fetch_and_connect.py
– the full script encapsulating steps 1-7.template.json
– minimal xray/v2rayN JSON with a placeholder outbound.Hand these specs to the agent and let it implement; every part is deterministic, so the AI can write & test the code autonomously.