agus1111 commited on
Commit
60efb5f
·
verified ·
1 Parent(s): 02f7b7a

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +12 -0
  2. bot-trading.py +287 -0
  3. requirements.txt +4 -0
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Telegram Trading Bot (HF Spaces)
2
+
3
+ Runs a Telethon-based auto-buyer with FastAPI health endpoint.
4
+
5
+ ## Secrets
6
+ - API_ID, API_HASH, STRING_SESSION (required)
7
+ - SOURCE_CHAT, TARGET_CHAT (optional)
8
+ - AMOUNT_LABEL, RETRY_*, RECENT_CA_TTL_MINUTES (optional)
9
+
10
+ ## Endpoints
11
+ - GET / -> "OK"
12
+ - GET /metrics -> simple metric
bot-trading.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import time
4
+ import asyncio
5
+ import nest_asyncio
6
+ from typing import Optional, Tuple
7
+
8
+ from fastapi import FastAPI
9
+ from fastapi.responses import PlainTextResponse
10
+ import uvicorn
11
+
12
+ from telethon import TelegramClient, events
13
+ from telethon.sessions import StringSession
14
+ from telethon.errors.rpcerrorlist import FloodWaitError
15
+
16
+ # ========= ENV (set di HF Spaces: Settings → Variables and secrets) =========
17
+ API_ID = int(os.environ.get("API_ID", "0")) # wajib
18
+ API_HASH = os.environ.get("API_HASH", "") # wajib
19
+ STRING_SESSION = os.environ.get("STRING_SESSION", "") # wajib
20
+
21
+ SOURCE_CHAT = os.environ.get("SOURCE_CHAT", "https://t.me/MidasTouchsignalll")
22
+ TARGET_CHAT = os.environ.get("TARGET_CHAT", "@solana_trojanbot")
23
+
24
+ AMOUNT_LABEL = os.environ.get("AMOUNT_LABEL", "").strip()
25
+
26
+ # Retry labels; BUY pakai regex longgar (?i)buy
27
+ RETRY_LABELS = [x.strip() for x in os.environ.get(
28
+ "RETRY_LABELS", "Retry,Try Again,Rerty,RETRY,RE-TRY,Try again"
29
+ ).split(",") if x.strip()]
30
+
31
+ RETRY_MAX_ATTEMPTS = int(os.environ.get("RETRY_MAX_ATTEMPTS", "12"))
32
+ RETRY_SLEEP_SECONDS = float(os.environ.get("RETRY_SLEEP_SECONDS", "1.2"))
33
+ RETRY_OVERALL_TIMEOUT = float(os.environ.get("RETRY_OVERALL_TIMEOUT", "60"))
34
+ RECENT_CA_TTL_MINUTES = int(os.environ.get("RECENT_CA_TTL_MINUTES", "60"))
35
+
36
+ nest_asyncio.apply()
37
+
38
+ # ========= Regex CA =========
39
+ CA_SOL_RE = re.compile(r"\b([1-9A-HJ-NP-Za-km-z]{32,44})(?:pump)?\b")
40
+ CA_EVM_RE = re.compile(r"\b0x[a-fA-F0-9]{40}\b")
41
+
42
+ def find_first_ca(text: str) -> Optional[Tuple[str, str]]:
43
+ if not text:
44
+ return None
45
+ t = re.sub(r"(?m)^>.*", "", text)
46
+ t = re.sub(r"\s+", " ", t).strip()
47
+ m_evm = CA_EVM_RE.search(t)
48
+ m_sol = CA_SOL_RE.search(t)
49
+ cand = []
50
+ if m_evm: cand.append(("evm", m_evm.start(), m_evm.group(0)))
51
+ if m_sol: cand.append(("sol", m_sol.start(), m_sol.group(1)))
52
+ if not cand:
53
+ return None
54
+ chain, _, addr = sorted(cand, key=lambda x: x[1])[0]
55
+ return chain, addr
56
+
57
+ # ========= Helpers =========
58
+ def _normalize_chat(s: str) -> str:
59
+ if not s:
60
+ return s
61
+ m = re.search(r"(?:https?://)?t\.me/([^/\s]+)", s)
62
+ if m:
63
+ s = m.group(1)
64
+ return s.lstrip("@")
65
+
66
+ def _pat_any(labels):
67
+ if not labels:
68
+ return re.compile(r"$^")
69
+ return re.compile(r"(?i)(" + "|".join(map(re.escape, labels)) + r")")
70
+
71
+ BUY_PAT = re.compile(r"(?i)buy")
72
+ RETRY_PAT = _pat_any(RETRY_LABELS)
73
+
74
+ recent_ca_ts = {}
75
+ def _is_recent(addr: str) -> bool:
76
+ ts = recent_ca_ts.get(addr)
77
+ return bool(ts and (time.time() - ts) < (RECENT_CA_TTL_MINUTES * 60))
78
+ def _mark_ca(addr: str): recent_ca_ts[addr] = time.time()
79
+
80
+ if not (API_ID and API_HASH and STRING_SESSION):
81
+ raise RuntimeError("API_ID/API_HASH/STRING_SESSION belum di-set di Secrets.")
82
+
83
+ client = TelegramClient(StringSession(STRING_SESSION), API_ID, API_HASH)
84
+ app = FastAPI()
85
+ ca_queue: "asyncio.Queue[str]" = asyncio.Queue()
86
+ _worker_task = None
87
+
88
+ async def refresh_message(msg):
89
+ return await client.get_messages(msg.chat_id, ids=msg.id)
90
+
91
+ async def wait_new_keyboard(chat, *, min_id: int, timeout=25, interval=0.8):
92
+ steps = max(1, int(timeout / interval))
93
+ for _ in range(steps):
94
+ msgs = await client.get_messages(chat, limit=8)
95
+ for m in msgs:
96
+ if m.id > min_id and m.buttons:
97
+ return m
98
+ await asyncio.sleep(interval)
99
+ return None
100
+
101
+ def dump_buttons(msg, title="[DBG] Tombol:"):
102
+ if not msg or not getattr(msg, "buttons", None):
103
+ print(f"{title} <no buttons>")
104
+ return
105
+ rows = []
106
+ for row in msg.buttons:
107
+ rows.append(" | ".join([(getattr(b, "text", "") or "").strip() for b in row]))
108
+ print(f"{title} " + " || ".join(rows))
109
+
110
+ async def click_first_match(msg, pat) -> bool:
111
+ if not msg or not msg.buttons:
112
+ return False
113
+ msg = await refresh_message(msg)
114
+ if not msg.buttons:
115
+ return False
116
+ for i, row in enumerate(msg.buttons):
117
+ for j, btn in enumerate(row):
118
+ label = (getattr(btn, "text", "") or "").strip()
119
+ if label and pat.search(label):
120
+ print(f"[CLICK] {label} at [{i},{j}] (msg {msg.id})")
121
+ await msg.click(i, j)
122
+ return True
123
+ return False
124
+
125
+ async def search_latest_with_button(chat, pat, *, min_id: int, limit=10):
126
+ msgs = await client.get_messages(chat, limit=limit)
127
+ for m in msgs:
128
+ if m.id >= min_id and m.buttons:
129
+ m2 = await client.get_messages(chat, ids=m.id)
130
+ if m2 and await click_first_match(m2, pat):
131
+ return m2
132
+ return None
133
+
134
+ async def click_retry_until_gone(anchor_msg, *, baseline_id: int) -> bool:
135
+ attempts = 0
136
+ started = time.monotonic()
137
+ did_once = False
138
+ msg_kb = anchor_msg
139
+ while attempts < RETRY_MAX_ATTEMPTS and (time.monotonic() - started) < RETRY_OVERALL_TIMEOUT:
140
+ msg_kb = await refresh_message(msg_kb)
141
+ if await click_first_match(msg_kb, RETRY_PAT):
142
+ did_once = True
143
+ attempts += 1
144
+ await asyncio.sleep(RETRY_SLEEP_SECONDS)
145
+ continue
146
+ hit = False
147
+ msgs = await client.get_messages(TARGET_CHAT, limit=8)
148
+ for m in msgs:
149
+ if m.id >= baseline_id and m.buttons:
150
+ m2 = await client.get_messages(TARGET_CHAT, ids=m.id)
151
+ if m2 and await click_first_match(m2, RETRY_PAT):
152
+ did_once = True
153
+ attempts += 1
154
+ baseline_id = max(baseline_id, m2.id)
155
+ await asyncio.sleep(RETRY_SLEEP_SECONDS)
156
+ hit = True
157
+ break
158
+ if hit:
159
+ continue
160
+ print("[RETRY] Tombol Retry sudah tidak ada — anggap sukses.")
161
+ break
162
+ return did_once
163
+
164
+ async def buy_flow_with_ca(addr: str):
165
+ print(f"[FLOW] Start BUY untuk CA: {addr}")
166
+ last = await client.get_messages(TARGET_CHAT, limit=1)
167
+ baseline_id = last[0].id if last else 0
168
+
169
+ await client.send_message(TARGET_CHAT, addr)
170
+ msg_kb = await wait_new_keyboard(TARGET_CHAT, min_id=baseline_id, timeout=25)
171
+ if not msg_kb:
172
+ print("[FLOW] Tidak ada keyboard. /start → kirim CA ulang…")
173
+ await client.send_message(TARGET_CHAT, "/start")
174
+ await asyncio.sleep(1.0)
175
+ await client.send_message(TARGET_CHAT, addr)
176
+ msg_kb = await wait_new_keyboard(TARGET_CHAT, min_id=baseline_id, timeout=25)
177
+ if not msg_kb:
178
+ print("[FLOW] Gagal dapat keyboard. Stop.")
179
+ return
180
+
181
+ baseline_id = max(baseline_id, msg_kb.id)
182
+
183
+ if AMOUNT_LABEL:
184
+ ok_amt = await click_first_match(msg_kb, re.compile(re.escape(AMOUNT_LABEL), re.IGNORECASE))
185
+ await asyncio.sleep(1.0)
186
+ if ok_amt:
187
+ msg2 = await wait_new_keyboard(TARGET_CHAT, min_id=baseline_id, timeout=12)
188
+ msg_kb = msg2 or await refresh_message(msg_kb)
189
+ baseline_id = max(baseline_id, getattr(msg_kb, "id", baseline_id))
190
+
191
+ ok_buy = await click_first_match(msg_kb, BUY_PAT)
192
+ if not ok_buy:
193
+ hit = await search_latest_with_button(TARGET_CHAT, BUY_PAT, min_id=baseline_id, limit=10)
194
+ if hit:
195
+ msg_kb = hit
196
+ ok_buy = True
197
+
198
+ if not ok_buy:
199
+ dump_buttons(msg_kb, "[DBG] Tombol sebelum fallback BUY")
200
+ if msg_kb.buttons and msg_kb.buttons[-1]:
201
+ try:
202
+ await msg_kb.click(len(msg_kb.buttons) - 1, 0)
203
+ print("[CLICK] Fallback klik tombol terakhir (BUY?)")
204
+ ok_buy = True
205
+ except Exception as e:
206
+ print(f"[CLICK] Fallback gagal: {e}")
207
+
208
+ if not ok_buy:
209
+ print("[FLOW] BUY belum ketemu. /start → kirim CA ulang…")
210
+ await client.send_message(TARGET_CHAT, "/start")
211
+ await asyncio.sleep(1.0)
212
+ await client.send_message(TARGET_CHAT, addr)
213
+ msg_kb2 = await wait_new_keyboard(TARGET_CHAT, min_id=baseline_id, timeout=25)
214
+ msg_kb = msg_kb2 or msg_kb
215
+ dump_buttons(msg_kb, "[DBG] Tombol setelah fallback /start")
216
+ if not await click_first_match(msg_kb, BUY_PAT):
217
+ hit2 = await search_latest_with_button(TARGET_CHAT, BUY_PAT, min_id=baseline_id, limit=10)
218
+ if hit2:
219
+ msg_kb = hit2
220
+ else:
221
+ print("[FLOW] Gagal menemukan BUY.")
222
+ return
223
+
224
+ await asyncio.sleep(1.0)
225
+ _ = await click_retry_until_gone(msg_kb, baseline_id=baseline_id)
226
+
227
+ async def worker_buy():
228
+ while True:
229
+ addr = await ca_queue.get()
230
+ try:
231
+ await buy_flow_with_ca(addr)
232
+ except FloodWaitError as fw:
233
+ print(f"[BUY] FloodWait {fw.seconds}s; tidur…")
234
+ await asyncio.sleep(fw.seconds + 2)
235
+ except Exception as e:
236
+ print(f"[BUY] Error CA {addr}: {e}")
237
+ finally:
238
+ ca_queue.task_done()
239
+
240
+ def _accept_ca(addr: str) -> bool:
241
+ if not addr:
242
+ return False
243
+ if _is_recent(addr):
244
+ print(f"[SKIP] CA {addr} (anti double {RECENT_CA_TTL_MINUTES}m)")
245
+ return False
246
+ _mark_ca(addr)
247
+ return True
248
+
249
+ @client.on(events.NewMessage(chats=_normalize_chat(SOURCE_CHAT)))
250
+ async def on_message_from_source(event: events.NewMessage.Event):
251
+ txt = (event.raw_text or "").strip()
252
+ found = find_first_ca(txt)
253
+ if not found:
254
+ return
255
+ chain, addr = found
256
+ print(f"[SRC] CA ({chain}): {addr} (msg {event.message.id})")
257
+ if _accept_ca(addr):
258
+ await ca_queue.put(addr)
259
+
260
+ # ========= FastAPI lifecycle =========
261
+ @app.on_event("startup")
262
+ async def on_startup():
263
+ await client.start()
264
+ print(f"[INIT] Login OK. Sumber: @{_normalize_chat(SOURCE_CHAT)} → Target: {TARGET_CHAT}")
265
+ global _worker_task
266
+ _worker_task = asyncio.create_task(worker_buy())
267
+
268
+ @app.on_event("shutdown")
269
+ async def on_shutdown():
270
+ try:
271
+ if _worker_task:
272
+ _worker_task.cancel()
273
+ finally:
274
+ await client.disconnect()
275
+
276
+ @app.get("/", response_class=PlainTextResponse)
277
+ async def root():
278
+ return "OK"
279
+
280
+ @app.get("/metrics", response_class=PlainTextResponse)
281
+ async def metrics():
282
+ # very simple metric
283
+ return f"recent_ca_count {len(recent_ca_ts)}"
284
+
285
+ # Local run (useful when testing)
286
+ if __name__ == "__main__":
287
+ uvicorn.run("app:app", host="0.0.0.0", port=int(os.environ.get("PORT", "7860")))
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ telethon==1.36.0
2
+ fastapi==0.114.2
3
+ uvicorn==0.30.6
4
+ nest_asyncio==1.6.0