From 1f4154a897023ccd34002432532ae9930b80f3bd Mon Sep 17 00:00:00 2001 From: Panniantong Date: Sun, 15 Mar 2026 11:12:25 +0100 Subject: [PATCH] fix(reddit): add User-Agent to doctor health check to avoid false 403 Reddit API requires a non-empty User-Agent header per its API rules. Without it, the JSON endpoint returns 403 even when Reddit is reachable, causing doctor to falsely report the channel as unavailable. Changes: - Add _reddit_reachable() helper that probes Reddit JSON API with UA - doctor check() now distinguishes 'actually unreachable' from 'no proxy' - Users on home IPs get 'ok' when Reddit is reachable; warn only on real failure Fixes #168 --- agent_reach/channels/reddit.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/agent_reach/channels/reddit.py b/agent_reach/channels/reddit.py index b8e9c42..a307fe8 100644 --- a/agent_reach/channels/reddit.py +++ b/agent_reach/channels/reddit.py @@ -1,9 +1,24 @@ # -*- coding: utf-8 -*- -"""Reddit — check if proxy and credentials are configured.""" +"""Reddit — check connectivity and proxy configuration.""" import os +import urllib.request from .base import Channel +_UA = "agent-reach/1.0" +_TIMEOUT = 10 + + +def _reddit_reachable() -> bool: + """Return True if Reddit JSON API responds with 200 (带 User-Agent).""" + url = "https://www.reddit.com/r/linux.json?limit=1" + req = urllib.request.Request(url, headers={"User-Agent": _UA}) + try: + with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp: + return resp.status == 200 + except Exception: + return False + class RedditChannel(Channel): name = "reddit" @@ -20,7 +35,10 @@ class RedditChannel(Channel): proxy = (config.get("reddit_proxy") if config else None) or os.environ.get("REDDIT_PROXY") if proxy: return "ok", "代理已配置,可读取帖子。搜索走 Exa" + # 实际探测连通性(带 User-Agent,符合 Reddit API 要求) + if _reddit_reachable(): + return "ok", "直连可用(JSON API 响应正常)。搜索走 Exa" return "warn", ( - "无代理。服务器 IP 可能被 Reddit 封锁。配置代理:\n" + "无代理且 Reddit JSON API 无响应。服务器 IP 可能被封锁。配置代理:\n" " agent-reach configure proxy http://user:pass@ip:port" )