1"""Telegram keyword search without login.
2Step 1: ask web search engines which public channels mention the keyword.
3Step 2: run Telegram's own in-channel search (t.me/s/<channel>?q=<keyword>) on each channel.
4"""
5import asyncio
6import time
7import base64
8import random
9import re
10from urllib.parse import quote, unquote
11
12try:
13 import httpx
14except ImportError:
15 import httpx2 as httpx
16from apify import Actor
17from bs4 import BeautifulSoup
18
19UA = [
20 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
21 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
22 "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
23]
24RESERVED = {
25 "s", "joinchat", "addstickers", "share", "iv", "proxy", "socks", "login", "addemoji", "setlanguage",
26 "c", "addtheme", "bg", "confirmphone", "contact", "invoice", "addlist", "boost", "giftcode", "m", "k",
27 "telegram", "blog", "faq", "apps", "dl", "tos", "privacy", "press", "api", "bots", "dev",
28}
29TME = re.compile(r"(?:t\.me|telegram\.me)/(?:s/)?([A-Za-z][A-Za-z0-9_]{3,31})(?:/(\d+))?", re.I)
30TME_CRUMB = re.compile(r"t\.me(?:\s*›\s*s)?\s*›\s*([A-Za-z][A-Za-z0-9_]{3,31})", re.I)
31BING_U = re.compile(r"[?&;]u=a1([A-Za-z0-9_\-]+)")
32
33ENGINES = {
34 "ddg": lambda q, page: f"https://html.duckduckgo.com/html/?q={quote(q)}" + (f"&s={page * 30}&dc={page * 30 + 1}" if page else ""),
35 "bing": lambda q, page: f"https://www.bing.com/search?q={quote(q)}&first={page * 10 + 1}&count=30",
36 "brave": lambda q, page: f"https://search.brave.com/search?q={quote(q)}&offset={page}",
37 "mojeek": lambda q, page: f"https://www.mojeek.com/search?q={quote(q)}&s={page * 10 + 1}",
38 "yahoo": lambda q, page: f"https://search.yahoo.com/search?p={quote(q)}&b={page * 10 + 1}",
39}
40
41
42def extract(html: str) -> set:
43 found = set()
44 texts = [html, unquote(html), re.sub(r"<[^>]+>", "", html)]
45 for m in BING_U.finditer(html):
46 raw = m.group(1)
47 try:
48 texts.append(base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4)).decode("utf-8", "ignore"))
49 except Exception:
50 pass
51 for t in texts:
52 for m in TME.finditer(t):
53 name = m.group(1).lower()
54 if name not in RESERVED and not name.endswith("bot"):
55 found.add((name, m.group(2)))
56 for m in TME_CRUMB.finditer(t):
57 name = m.group(1).lower()
58 if name not in RESERVED and not name.endswith("bot"):
59 found.add((name, None))
60 return found
61
62
63async def get(client, url, proxy_cfg=None, timeout=8.0):
64 headers = {"User-Agent": random.choice(UA), "Accept-Language": "en-US,en;q=0.9", "Accept": "text/html,application/xhtml+xml"}
65 try:
66 if proxy_cfg:
67 proxy_url = await proxy_cfg.new_url()
68 async with httpx.AsyncClient(proxy=proxy_url, timeout=timeout, follow_redirects=True) as pc:
69 r = await pc.get(url, headers=headers)
70 else:
71 r = await client.get(url, headers=headers, timeout=timeout)
72 return r.status_code, r.text
73 except Exception as e:
74 return 0, f"ERR {type(e).__name__}"
75
76
77def to_int(s):
78 if not s:
79 return None
80 s = s.strip().upper().replace(" ", "").replace(",", ".")
81 mult = 1
82 if s.endswith("K"):
83 mult, s = 1_000, s[:-1]
84 elif s.endswith("M"):
85 mult, s = 1_000_000, s[:-1]
86 try:
87 return int(float(s) * mult)
88 except ValueError:
89 return None
90
91
92def parse_posts(html: str, channel: str, keyword: str):
93 soup = BeautifulSoup(html, "html.parser")
94 title_el = soup.select_one(".tgme_channel_info_header_title")
95 subs = None
96 for c in soup.select(".tgme_channel_info_counter"):
97 t = c.select_one(".counter_type")
98 v = c.select_one(".counter_value")
99 if t and v and "subscriber" in t.get_text().lower():
100 subs = to_int(v.get_text(strip=True))
101 kw = keyword.lower()
102 words = [w for w in re.split(r"\s+", kw) if w]
103 out = []
104 for msg in soup.select(".tgme_widget_message"):
105 post = msg.get("data-post") or ""
106 if "/" not in post:
107 continue
108 text_el = msg.select_one(".tgme_widget_message_text")
109 text = text_el.get_text(" ", strip=True) if text_el else ""
110 low = text.lower()
111 time_el = msg.select_one("time[datetime]")
112 views_el = msg.select_one(".tgme_widget_message_views")
113 out.append({
114 "keyword": keyword,
115 "channel": channel,
116 "channelTitle": title_el.get_text(strip=True) if title_el else None,
117 "subscribers": subs,
118 "postUrl": f"https://t.me/{post}",
119 "postId": int(post.split("/")[-1]) if post.split("/")[-1].isdigit() else None,
120 "date": time_el.get("datetime") if time_el else None,
121 "views": to_int(views_el.get_text(strip=True)) if views_el else None,
122 "text": text[:4000],
123 "exactMatch": kw in low,
124 "allWordsMatch": all(w in low for w in words),
125 })
126 return out
127
128
129async def search_channels(client, kw, serp_cfg, budget):
130 jobs = []
131 for eng in ("yahoo", "bing"):
132 for q in (f'site:t.me "{kw}"', f"site:t.me/s {kw}", f"t.me {kw} telegram channel"):
133 jobs.append((eng, get(client, ENGINES[eng](q, 0))))
134 if serp_cfg:
135 for q in (f"site:t.me {kw}", f'site:t.me/s "{kw}"'):
136 for st in (0, 10, 20):
137 jobs.append(("google", get(client, f"http://www.google.com/search?q={quote(q)}&start={st}", serp_cfg)))
138 tasks = [asyncio.ensure_future(c) for _, c in jobs]
139 done, pending = await asyncio.wait(tasks, timeout=budget)
140 for p in pending:
141 p.cancel()
142 score: dict = {}
143 per: dict = {}
144 for (eng, _), task in zip(jobs, tasks):
145 st = per.setdefault(eng, {"ok": 0, "bad": 0, "channels": set()})
146 if task in done and not task.cancelled() and task.exception() is None and task.result()[0] == 200:
147 st["ok"] += 1
148 for name, post_id in extract(task.result()[1]):
149 st["channels"].add(name)
150 e = score.setdefault(name, {"engines": set(), "hits": 0})
151 e["engines"].add(eng)
152 e["hits"] += 2 if post_id else 1
153 else:
154 st["bad"] += 1
155 if serp_cfg and len(score) < 20:
156 retry = [(f"site:t.me {kw}", 0), (f"site:t.me {kw}", 10), (f't.me "{kw}"', 0)]
157 res2 = await asyncio.gather(*(get(client, f"http://www.google.com/search?q={quote(q)}&start={s}", serp_cfg, 14.0) for q, s in retry))
158 st = per.setdefault("google", {"ok": 0, "bad": 0, "channels": set()})
159 for code, html in res2:
160 if code == 200:
161 st["ok"] += 1
162 for name, post_id in extract(html):
163 st["channels"].add(name)
164 e = score.setdefault(name, {"engines": set(), "hits": 0})
165 e["engines"].add("google")
166 e["hits"] += 2 if post_id else 1
167 else:
168 st["bad"] += 1
169 ranked = sorted(score, key=lambda n: (len(score[n]["engines"]), score[n]["hits"]), reverse=True)
170 return ranked, {e: {"ok": v["ok"], "bad": v["bad"], "channels": len(v["channels"])} for e, v in per.items()}
171
172
173async def main() -> None:
174 async with Actor:
175 inp = await Actor.get_input() or {}
176 keywords = [k.strip() for k in (inp.get("keywords") or []) if isinstance(k, str) and k.strip()]
177 if not keywords:
178 await Actor.fail(status_message="Add at least one keyword.")
179 return
180 max_posts = int(inp.get("maxPostsPerKeyword") or 100)
181 max_channels = int(inp.get("maxChannelsPerKeyword") or 40)
182 exact_only = bool(inp.get("exactMatchOnly", False))
183 budget = float(inp.get("searchTimeoutSecs") or 9)
184 serp_cfg = None
185 try:
186 serp_cfg = await Actor.create_proxy_configuration(groups=["GOOGLE_SERP"])
187 except Exception as e:
188 Actor.log.warning(f"Google search is not available, using other engines only: {e}")
189 stats = []
190 limits = httpx.Limits(max_connections=40, max_keepalive_connections=20)
191 async with httpx.AsyncClient(follow_redirects=True, limits=limits) as client:
192 sem = asyncio.Semaphore(12)
193
194 async def one(ch, kw):
195 async with sem:
196 code, html = await get(client, f"https://t.me/s/{ch}?q={quote(kw)}", None, 7.0)
197 return parse_posts(html, ch, kw) if code == 200 else []
198
199 for kw in keywords:
200 t0 = time.monotonic()
201 ranked, per = await search_channels(client, kw, serp_cfg, budget)
202 t1 = time.monotonic()
203 picked = ranked[:max_channels]
204 lists = await asyncio.gather(*(one(ch, kw) for ch in picked))
205 seen = set()
206 posts = []
207 for lst in lists:
208 for p in lst:
209 if p["postUrl"] in seen:
210 continue
211 seen.add(p["postUrl"])
212 if exact_only and not p["exactMatch"]:
213 continue
214 posts.append(p)
215 posts.sort(key=lambda p: (p["exactMatch"], p["allWordsMatch"], p["date"] or ""), reverse=True)
216 posts = posts[:max_posts]
217 if posts:
218 await Actor.push_data(posts)
219 t2 = time.monotonic()
220 row = {
221 "keyword": kw, "channelsFound": len(ranked), "channelsChecked": len(picked),
222 "channelsWithPosts": sum(1 for lst in lists if lst), "posts": len(posts),
223 "exact": sum(1 for p in posts if p["exactMatch"]),
224 "allWords": sum(1 for p in posts if p["allWordsMatch"]),
225 "searchSec": round(t1 - t0, 1), "telegramSec": round(t2 - t1, 1), "engines": per,
226 }
227 stats.append(row)
228 Actor.log.info(f"ROW {row}")
229 if not posts:
230 Actor.log.warning(f"No public posts found for {kw!r}. Try a shorter or more common keyword.")
231 await Actor.set_value("STATS", stats)
232 await Actor.set_status_message(f"Done: {sum(r['posts'] for r in stats)} posts for {len(stats)} keyword(s).")
233
234
235if __name__ == "__main__":
236 asyncio.run(main())