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
This commit is contained in:
Panniantong
2026-03-15 11:12:25 +01:00
parent 1442852471
commit 1f4154a897
+20 -2
View File
@@ -1,9 +1,24 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Reddit — check if proxy and credentials are configured.""" """Reddit — check connectivity and proxy configuration."""
import os import os
import urllib.request
from .base import Channel 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): class RedditChannel(Channel):
name = "reddit" name = "reddit"
@@ -20,7 +35,10 @@ class RedditChannel(Channel):
proxy = (config.get("reddit_proxy") if config else None) or os.environ.get("REDDIT_PROXY") proxy = (config.get("reddit_proxy") if config else None) or os.environ.get("REDDIT_PROXY")
if proxy: if proxy:
return "ok", "代理已配置,可读取帖子。搜索走 Exa" return "ok", "代理已配置,可读取帖子。搜索走 Exa"
# 实际探测连通性(带 User-Agent,符合 Reddit API 要求)
if _reddit_reachable():
return "ok", "直连可用(JSON API 响应正常)。搜索走 Exa"
return "warn", ( return "warn", (
"无代理。服务器 IP 可能被 Reddit 封锁。配置代理:\n" "无代理且 Reddit JSON API 无响应。服务器 IP 可能被封锁。配置代理:\n"
" agent-reach configure proxy http://user:pass@ip:port" " agent-reach configure proxy http://user:pass@ip:port"
) )