crypto-scanner-bot 2.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- crypto_scanner_bot-2.0.0/LICENSE +21 -0
- crypto_scanner_bot-2.0.0/PKG-INFO +166 -0
- crypto_scanner_bot-2.0.0/README.md +130 -0
- crypto_scanner_bot-2.0.0/pyproject.toml +67 -0
- crypto_scanner_bot-2.0.0/setup.cfg +4 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/__init__.py +207 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/__main__.py +46 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/blocks/__init__.py +1 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/blocks/balances.py +47 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/blocks/dashboard.py +535 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/blocks/positions.py +407 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/blocks/settings.py +448 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/blocks/tokens.py +326 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/buttons.py +88 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/constants.py +35 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/db/__init__.py +14 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/db/core.py +80 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/db/options.py +20 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/db/schema.py +139 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/db/tokens.py +598 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/health.py +221 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/helpers.py +119 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/jobs.py +408 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/networks.py +509 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/py.typed +0 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/settings.py +139 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/text_input.py +22 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/trading/__init__.py +1 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/trading/monitors.py +465 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/trading/trending.py +230 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/trading/watchers.py +165 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/w3/__init__.py +169 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/w3/audit.py +529 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/w3/tools.py +161 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/w3/trade.py +495 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/w3/v4.py +138 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/web/__init__.py +34 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/web/auth.py +150 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/web/charts.py +130 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/web/core.py +46 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/web/pages.py +150 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner/web/views.py +538 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner_bot.egg-info/PKG-INFO +166 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner_bot.egg-info/SOURCES.txt +50 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner_bot.egg-info/dependency_links.txt +1 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner_bot.egg-info/requires.txt +15 -0
- crypto_scanner_bot-2.0.0/src/crypto_scanner_bot.egg-info/top_level.txt +1 -0
- crypto_scanner_bot-2.0.0/tests/test_bot.py +760 -0
- crypto_scanner_bot-2.0.0/tests/test_health.py +247 -0
- crypto_scanner_bot-2.0.0/tests/test_jobs.py +441 -0
- crypto_scanner_bot-2.0.0/tests/test_package.py +38 -0
- crypto_scanner_bot-2.0.0/tests/test_settings.py +81 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Adz1DoubleD
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: crypto-scanner-bot
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: Self-hosted Telegram bot that watches new crypto tokens, audits them and can trade them from your own wallet.
|
|
5
|
+
Author: Adz1DoubleD
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Adz1DoubleD/crypto-scanner-bot
|
|
8
|
+
Project-URL: Issues, https://github.com/Adz1DoubleD/crypto-scanner-bot/issues
|
|
9
|
+
Keywords: telegram,bot,crypto,ethereum,base,uniswap,scanner
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Topic :: Communications :: Chat
|
|
18
|
+
Requires-Python: >=3.12
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: python-telegram-bot[job-queue]<23,>=22
|
|
22
|
+
Requires-Dist: aiomysql[rsa]<0.4,>=0.3
|
|
23
|
+
Requires-Dist: sentry-sdk<3,>=2
|
|
24
|
+
Requires-Dist: web3<9,>=8
|
|
25
|
+
Requires-Dist: aiohttp<4,>=3.9
|
|
26
|
+
Requires-Dist: httpx<1,>=0.28
|
|
27
|
+
Requires-Dist: python-dotenv<2,>=1
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest==9.2.0; extra == "dev"
|
|
30
|
+
Requires-Dist: pytest-asyncio==1.5.0; extra == "dev"
|
|
31
|
+
Requires-Dist: freezegun==1.5.5; extra == "dev"
|
|
32
|
+
Requires-Dist: mypy==2.4.1; extra == "dev"
|
|
33
|
+
Requires-Dist: ruff==0.17.5; extra == "dev"
|
|
34
|
+
Requires-Dist: pre_commit==4.7.0; extra == "dev"
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
|
|
37
|
+
# crypto-scanner-bot
|
|
38
|
+
|
|
39
|
+
A self-hosted Telegram bot (🤖 Crypto Scanner) that watches decentralised exchanges on Base for new tokens, audits them, and can buy and sell them from **your own wallet**. It runs on its own, or inside another python-telegram-bot application.
|
|
40
|
+
|
|
41
|
+
> **Use at your own risk.** This is not financial advice. Trading new tokens is extremely risky: most fail, many are scams, and you can lose everything you put in. The software comes with no warranty (see [LICENSE](LICENSE)). Only use a separate wallet holding money you can afford to lose. You're responsible for your own trades, and for any tax or legal rules where you live.
|
|
42
|
+
>
|
|
43
|
+
> Not affiliated with Uniswap, Aerodrome, GoPlus, honeypot.is, GeckoTerminal, DEX Screener or any RPC provider.
|
|
44
|
+
|
|
45
|
+
**Status:** early work in progress. Formerly published as `pair-scanner-bot`.
|
|
46
|
+
|
|
47
|
+
## What it does
|
|
48
|
+
|
|
49
|
+
- **Finds new tokens.** It watches the Uniswap V2, Uniswap V3 and Aerodrome factories on Base for new pools paired with WETH.
|
|
50
|
+
- **Audits them.** It checks liquidity, the liquidity-to-market-cap ratio, locked LP, whether one wallet holds too much of the supply, taxes, contract security (GoPlus), honeypot risk (honeypot.is), and whether a sale actually goes through (simulated against the chain). Owner controls such as minting or an upgradeable contract reject a new pair, but not an established pool found by the Trending monitor, since most large tokens have them.
|
|
51
|
+
- **Skips spam names.** A new token is rejected straight away if its ticker hides invisible characters (used to copy a real ticker), or if another token with the same ticker was found in the 24 hours before it. Scam launchers often relaunch the same names every hour or two.
|
|
52
|
+
- **Watches Uniswap v4 too, without buying.** New v4 pools paired with ETH or WETH are checked and reported as "would buy", whatever mode the 🆕 New monitor is in. Only pools with no hook or a known launchpad hook (Clanker, Doppler) are looked at; any other hook is rejected, since a hook can block sales. Liquidity is checked by asking Uniswap's v4 Quoter what selling for `min_liquidity_eth` would take, and the token goes through GoPlus, the tax limit and the big-holder limit. Launchpad tokens are allowed owner controls, which their launchpad builds in. honeypot.is doesn't cover v4 yet, so instead the Quoter is asked to buy `buy_amount_eth` worth and sell it straight back: if the sale fails the token is a honeypot, and if more than a fifth is lost on the way it's rejected for high tax. Each pick then becomes a pretend position, priced from Uniswap's StateView, so the sell rules run on it and its result shows in "Would have made".
|
|
53
|
+
- **Buys what passes,** when the monitor is on 💰 Live, up to your limits.
|
|
54
|
+
- **Judges every position by what a sale would really return.** Each minute it asks the exchange what selling would bring back and compares that with what the buy actually cost, so a thin pool's price can't fake a gain. If no quote comes back it falls back to the pool price.
|
|
55
|
+
- **Sells half** once a position is up by `half_sell_percent` (30% by default; 0 turns it off). The rest then sells at break-even instead of the stop-loss, so a rug after that costs far less.
|
|
56
|
+
- **Sells** on take-profit, stop-loss, trailing stop (it starts once a position is up by `trailing_start_percent`, 20% by default, so gains are protected before take-profit), rug (liquidity drop), dead token, or a honeypot appearing later.
|
|
57
|
+
- **📈 Trending monitor (optional):** buys established pools with strong one-hour momentum. It skips pools younger than `trending_min_pool_age_hours` (24 by default) and checks the pool's real liquidity on-chain before buying.
|
|
58
|
+
- **Alerts** for every buy, sell, would-buy and health problem. Sells come in two groups, 💰 Sell and 🚨 Lost. Buys, profit sells and loss sells each have their own switch in ⚙️ Settings → Monitors & Alerts. Would-buys, failed buys and health alerts are always sent.
|
|
59
|
+
- **Screens:** the scanner dashboard (`/start` opens it), pairs, positions, wallet balances (on Base and Ethereum), health, settings and CSV exports of every pair and position for your own records.
|
|
60
|
+
- **A website too (optional):** the same stats with charts of your running P&L, each sale's return and what Watch picks would have made, plus tables of positions, Watch picks and tokens, why tokens were rejected, health and balances. You log in with Telegram, and only the owner gets in. It only shows things for now: trading and settings stay in the bot. See [The website](#the-website).
|
|
61
|
+
|
|
62
|
+
## Safety
|
|
63
|
+
|
|
64
|
+
- **A mode for each monitor, set in ⚙️ Settings → Monitors & Alerts.** The 🆕 New Monitor and the 📈 Trending Monitor each pick one of three: ⏸️ **Off**: it doesn't run. 👀 **Watch**: it finds and checks tokens and notes what it *would* buy, but never buys. Each pick is then followed as a pretend position with the same sell rules, so you get a **Would have made** figure on the dashboard and every pick on the website, and can see whether Live would have paid before spending anything. These stay out of Telegram unless you switch on **👀 Watch Alerts**, which sends a message for each *would buy* and *would have sold*. 💰 **Live**: it buys. So one can buy while the other only watches. A new install starts with New on Watch and Trending Off. Switching to Live asks you to confirm, and needs `PRIVATE_KEY`.
|
|
65
|
+
- **Owner only.** The bot answers only `OWNER_ID`.
|
|
66
|
+
- **Your key stays yours.** It's read from your environment, used to sign your own transactions, and never printed, stored or sent anywhere else.
|
|
67
|
+
- **Cautious defaults:** 0.001 ETH per buy, at most 3 positions, 5% slippage, and Trending off.
|
|
68
|
+
- **Balance floor.** If the wallet falls below the minimum balance (0.01 ETH by default) while a monitor is on Live, the health check switches it to Watch and alerts you. In Watch the balance only shows on the Health screen, because nothing is bought.
|
|
69
|
+
- **Its own health check.** Every `health_check_interval` minutes, while either monitor is on Watch or Live, it checks the RPCs, the wallet balance, the database (size, read-only, offline) and the pairs feed. It tells you once when something breaks, once more when it's fixed, and reminds you once if it's still broken after 12 hours. When the database nears `db_cleanup_mb` it clears the archive first. **🩺 Health** on the dashboard shows the same check whenever you want.
|
|
70
|
+
- **Open positions are looked after.** While either monitor is on Watch or Live, the sell monitor keeps working on your stop-loss, take-profit and the other sell rules for every open position, whichever monitor bought it. Changing a mode with open positions reminds you what happens to them; only both monitors Off stops selling.
|
|
71
|
+
|
|
72
|
+
## What it connects to
|
|
73
|
+
|
|
74
|
+
There's no telemetry: nothing is sent to the authors. The bot itself talks to:
|
|
75
|
+
|
|
76
|
+
- **Telegram**, for your messages and alerts.
|
|
77
|
+
- **Your RPC nodes** (Alchemy or Ankr if you give it keys, otherwise public nodes), to read the chain, check your balance and send your own transactions.
|
|
78
|
+
- **GeckoTerminal**, for pool prices and momentum, and **GoPlus** and **honeypot.is**, for token safety checks. These are sent token and pool addresses, never your wallet or key.
|
|
79
|
+
- **Your MySQL database**, where everything it remembers is kept.
|
|
80
|
+
|
|
81
|
+
## Run it on its own
|
|
82
|
+
|
|
83
|
+
You need Python 3.12+, a MySQL database and a bot token from [@BotFather](https://t.me/BotFather).
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
pip install crypto-scanner-bot
|
|
87
|
+
python -m crypto_scanner
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Run it from a folder with a `.env` file holding the settings below. [.env.example](.env.example) is a starting point. To find your Telegram user ID for `OWNER_ID`, message [@userinfobot](https://t.me/userinfobot). Then send `/start` to your bot to open the dashboard.
|
|
91
|
+
|
|
92
|
+
To look around before anything runs, set `MODE=off` first: both monitors start ⏸️ Off for that run, whatever modes are saved.
|
|
93
|
+
|
|
94
|
+
## Settings
|
|
95
|
+
|
|
96
|
+
| Setting | Environment variable | Purpose |
|
|
97
|
+
|---|---|---|
|
|
98
|
+
| `token` | `BOT_TOKEN` | Required. Your bot's token |
|
|
99
|
+
| `owner_id` | `OWNER_ID` | Required. Your Telegram user ID; the bot answers nobody else |
|
|
100
|
+
| `db_url` | `DB_URL` | Required. `mysql://user:pass@host:3306/db`. Tables are created on first start: `pairs`, `positions` and `scanner_settings` |
|
|
101
|
+
| `wallet_address` | `WALLET_ADDRESS` | Required. The wallet it watches and trades from |
|
|
102
|
+
| `private_key` | `PRIVATE_KEY` | Only to trade. Without it the bot can't go Live |
|
|
103
|
+
| `alerts_chat_id` | `ALERTS_CHAT_ID` | Where alerts go. Defaults to your private chat. For a group or channel, add the bot to it first (as an admin, for a channel) |
|
|
104
|
+
| `alchemy_api_key`, `ankr_api_key` | `ALCHEMY_API_KEY`, `ANKR_API_KEY` | Optional RPC keys, tried before the public nodes |
|
|
105
|
+
| `timezone` | `TIMEZONE` | Default `Europe/London` |
|
|
106
|
+
| | `SENTRY_DSN` (standalone) | Optional error reporting when run on its own |
|
|
107
|
+
| `mode` | `MODE` | `off` or `watch` to cap both monitors at that mode for this run only, without changing the saved modes. A host passes `mode="off"` for local runs |
|
|
108
|
+
| `website_url` | `WEBSITE_URL` | The website's address, such as `https://example.com/scanner`. Adds **🌐 Open Website** to the dashboard ([details](#the-website)) |
|
|
109
|
+
| `db_dashboard_url` | `DB_DASHBOARD_URL` | Optional web page for your database, such as its Heroku resources page. Database health alerts get a **🔧 Open database dashboard** button. Never put `DB_URL` here: it holds the password |
|
|
110
|
+
|
|
111
|
+
Trading limits, audit thresholds, sell rules and schedules are changed in the bot under **⚙️ Settings** and saved in `scanner_settings`.
|
|
112
|
+
|
|
113
|
+
Upgrading from 1.0 or 1.1: start 1.2 once first. It converts the old switches to a mode per monitor, splits the sell alerts switch, and adds the `half_eth` column; later versions no longer have those steps.
|
|
114
|
+
|
|
115
|
+
## Use it inside another bot
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
from crypto_scanner import start_scanner_bot, stop_scanner_bot
|
|
119
|
+
|
|
120
|
+
await start_scanner_bot(
|
|
121
|
+
share_with=application,
|
|
122
|
+
owner_id=OWNER_ID,
|
|
123
|
+
alerts_chat_id=ALERTS_CHAT_ID,
|
|
124
|
+
)
|
|
125
|
+
...
|
|
126
|
+
await stop_scanner_bot()
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Inside a host (with `share_with`), the scanner reads the same names with a `SCANNER_` prefix, such as `SCANNER_DB_URL` and `SCANNER_WALLET_ADDRESS`, so it never clashes with the host's own settings. Pass `env_prefix=` to use a different prefix. Settings the host already has, like the owner and alerts chat, can be passed as keywords instead.
|
|
130
|
+
|
|
131
|
+
Inside a host, the bot token is optional. Without it, the scanner uses the host's bot: its jobs run on the host's job queue and its alerts come from the host's bot. With it, the scanner runs its own bot alongside the host's. Any setting can be passed as a keyword instead of an environment variable. The host can show the scanner's screens in its own menus, and forward any button whose data starts with `scanner:` to `handle_button`, and text replies to `handle_text_input`:
|
|
132
|
+
|
|
133
|
+
- `scanner_block(context, brief=False)` is the scanner dashboard; `brief=True` gives a short summary for a daily message.
|
|
134
|
+
- `balances_block(brief=False)` shows the wallet's balance on each network.
|
|
135
|
+
- `scanner_health()` returns the RPC, wallet and monitor status as text, plus its alerts, so a host can show them in its own health check if it wants. It only reads: it never changes settings or cleans the database.
|
|
136
|
+
- `scanner_modes()` returns each monitor's mode for this run, such as `{"new": "watch", "trending": "off"}`, so a host can tell whether the scanner is doing anything.
|
|
137
|
+
- `add_web_routes(app, prefix="/scanner")` adds the website to the host's `aiohttp` app ([details](#the-website)). Pass `website_url=` to `start_scanner_bot` so the dashboard links to it.
|
|
138
|
+
|
|
139
|
+
## The website
|
|
140
|
+
|
|
141
|
+
The website needs a public address with HTTPS: Telegram's login only works on a real domain, never on `localhost` or a bare IP. Hosts like Heroku give you one.
|
|
142
|
+
|
|
143
|
+
- **On its own:** set `PORT` and `python -m crypto_scanner` serves the website on that port as well as running the bot. Heroku sets `PORT` for you. The site is at `/scanner`, and `/` goes there.
|
|
144
|
+
- **Inside a host:** call `add_web_routes(app)` on the host's own `aiohttp` app. The site is at `/scanner` on the host's address; pass `prefix=` to move it.
|
|
145
|
+
- **Behind a proxy:** the site reads `X-Forwarded-Proto` to tell it's on HTTPS, so its login cookie is only sent over HTTPS. Heroku and most proxies set it.
|
|
146
|
+
|
|
147
|
+
Then:
|
|
148
|
+
|
|
149
|
+
1. In [@BotFather](https://t.me/BotFather), send `/setdomain`, pick the bot the scanner runs on (the host's bot when it shares one) and send the domain on its own, such as `example.com`.
|
|
150
|
+
2. Set `WEBSITE_URL` to the site's full address, such as `https://example.com/scanner`. The dashboard gets **🌐 Open Website**, which opens the website already logged in.
|
|
151
|
+
|
|
152
|
+
Only `OWNER_ID` can log in. Anyone else who tries is told the dashboard is only for the owner.
|
|
153
|
+
|
|
154
|
+
## Development
|
|
155
|
+
|
|
156
|
+
```bash
|
|
157
|
+
pip install -e ".[dev]"
|
|
158
|
+
pre-commit install
|
|
159
|
+
pytest
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
`pre-commit` runs Ruff, mypy and a file-size check. See [CONTRIBUTING.md](CONTRIBUTING.md) for where things go and how releases work, and [SECURITY.md](SECURITY.md) to report a security problem privately.
|
|
163
|
+
|
|
164
|
+
## Licence
|
|
165
|
+
|
|
166
|
+
[MIT](LICENSE).
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# crypto-scanner-bot
|
|
2
|
+
|
|
3
|
+
A self-hosted Telegram bot (🤖 Crypto Scanner) that watches decentralised exchanges on Base for new tokens, audits them, and can buy and sell them from **your own wallet**. It runs on its own, or inside another python-telegram-bot application.
|
|
4
|
+
|
|
5
|
+
> **Use at your own risk.** This is not financial advice. Trading new tokens is extremely risky: most fail, many are scams, and you can lose everything you put in. The software comes with no warranty (see [LICENSE](LICENSE)). Only use a separate wallet holding money you can afford to lose. You're responsible for your own trades, and for any tax or legal rules where you live.
|
|
6
|
+
>
|
|
7
|
+
> Not affiliated with Uniswap, Aerodrome, GoPlus, honeypot.is, GeckoTerminal, DEX Screener or any RPC provider.
|
|
8
|
+
|
|
9
|
+
**Status:** early work in progress. Formerly published as `pair-scanner-bot`.
|
|
10
|
+
|
|
11
|
+
## What it does
|
|
12
|
+
|
|
13
|
+
- **Finds new tokens.** It watches the Uniswap V2, Uniswap V3 and Aerodrome factories on Base for new pools paired with WETH.
|
|
14
|
+
- **Audits them.** It checks liquidity, the liquidity-to-market-cap ratio, locked LP, whether one wallet holds too much of the supply, taxes, contract security (GoPlus), honeypot risk (honeypot.is), and whether a sale actually goes through (simulated against the chain). Owner controls such as minting or an upgradeable contract reject a new pair, but not an established pool found by the Trending monitor, since most large tokens have them.
|
|
15
|
+
- **Skips spam names.** A new token is rejected straight away if its ticker hides invisible characters (used to copy a real ticker), or if another token with the same ticker was found in the 24 hours before it. Scam launchers often relaunch the same names every hour or two.
|
|
16
|
+
- **Watches Uniswap v4 too, without buying.** New v4 pools paired with ETH or WETH are checked and reported as "would buy", whatever mode the 🆕 New monitor is in. Only pools with no hook or a known launchpad hook (Clanker, Doppler) are looked at; any other hook is rejected, since a hook can block sales. Liquidity is checked by asking Uniswap's v4 Quoter what selling for `min_liquidity_eth` would take, and the token goes through GoPlus, the tax limit and the big-holder limit. Launchpad tokens are allowed owner controls, which their launchpad builds in. honeypot.is doesn't cover v4 yet, so instead the Quoter is asked to buy `buy_amount_eth` worth and sell it straight back: if the sale fails the token is a honeypot, and if more than a fifth is lost on the way it's rejected for high tax. Each pick then becomes a pretend position, priced from Uniswap's StateView, so the sell rules run on it and its result shows in "Would have made".
|
|
17
|
+
- **Buys what passes,** when the monitor is on 💰 Live, up to your limits.
|
|
18
|
+
- **Judges every position by what a sale would really return.** Each minute it asks the exchange what selling would bring back and compares that with what the buy actually cost, so a thin pool's price can't fake a gain. If no quote comes back it falls back to the pool price.
|
|
19
|
+
- **Sells half** once a position is up by `half_sell_percent` (30% by default; 0 turns it off). The rest then sells at break-even instead of the stop-loss, so a rug after that costs far less.
|
|
20
|
+
- **Sells** on take-profit, stop-loss, trailing stop (it starts once a position is up by `trailing_start_percent`, 20% by default, so gains are protected before take-profit), rug (liquidity drop), dead token, or a honeypot appearing later.
|
|
21
|
+
- **📈 Trending monitor (optional):** buys established pools with strong one-hour momentum. It skips pools younger than `trending_min_pool_age_hours` (24 by default) and checks the pool's real liquidity on-chain before buying.
|
|
22
|
+
- **Alerts** for every buy, sell, would-buy and health problem. Sells come in two groups, 💰 Sell and 🚨 Lost. Buys, profit sells and loss sells each have their own switch in ⚙️ Settings → Monitors & Alerts. Would-buys, failed buys and health alerts are always sent.
|
|
23
|
+
- **Screens:** the scanner dashboard (`/start` opens it), pairs, positions, wallet balances (on Base and Ethereum), health, settings and CSV exports of every pair and position for your own records.
|
|
24
|
+
- **A website too (optional):** the same stats with charts of your running P&L, each sale's return and what Watch picks would have made, plus tables of positions, Watch picks and tokens, why tokens were rejected, health and balances. You log in with Telegram, and only the owner gets in. It only shows things for now: trading and settings stay in the bot. See [The website](#the-website).
|
|
25
|
+
|
|
26
|
+
## Safety
|
|
27
|
+
|
|
28
|
+
- **A mode for each monitor, set in ⚙️ Settings → Monitors & Alerts.** The 🆕 New Monitor and the 📈 Trending Monitor each pick one of three: ⏸️ **Off**: it doesn't run. 👀 **Watch**: it finds and checks tokens and notes what it *would* buy, but never buys. Each pick is then followed as a pretend position with the same sell rules, so you get a **Would have made** figure on the dashboard and every pick on the website, and can see whether Live would have paid before spending anything. These stay out of Telegram unless you switch on **👀 Watch Alerts**, which sends a message for each *would buy* and *would have sold*. 💰 **Live**: it buys. So one can buy while the other only watches. A new install starts with New on Watch and Trending Off. Switching to Live asks you to confirm, and needs `PRIVATE_KEY`.
|
|
29
|
+
- **Owner only.** The bot answers only `OWNER_ID`.
|
|
30
|
+
- **Your key stays yours.** It's read from your environment, used to sign your own transactions, and never printed, stored or sent anywhere else.
|
|
31
|
+
- **Cautious defaults:** 0.001 ETH per buy, at most 3 positions, 5% slippage, and Trending off.
|
|
32
|
+
- **Balance floor.** If the wallet falls below the minimum balance (0.01 ETH by default) while a monitor is on Live, the health check switches it to Watch and alerts you. In Watch the balance only shows on the Health screen, because nothing is bought.
|
|
33
|
+
- **Its own health check.** Every `health_check_interval` minutes, while either monitor is on Watch or Live, it checks the RPCs, the wallet balance, the database (size, read-only, offline) and the pairs feed. It tells you once when something breaks, once more when it's fixed, and reminds you once if it's still broken after 12 hours. When the database nears `db_cleanup_mb` it clears the archive first. **🩺 Health** on the dashboard shows the same check whenever you want.
|
|
34
|
+
- **Open positions are looked after.** While either monitor is on Watch or Live, the sell monitor keeps working on your stop-loss, take-profit and the other sell rules for every open position, whichever monitor bought it. Changing a mode with open positions reminds you what happens to them; only both monitors Off stops selling.
|
|
35
|
+
|
|
36
|
+
## What it connects to
|
|
37
|
+
|
|
38
|
+
There's no telemetry: nothing is sent to the authors. The bot itself talks to:
|
|
39
|
+
|
|
40
|
+
- **Telegram**, for your messages and alerts.
|
|
41
|
+
- **Your RPC nodes** (Alchemy or Ankr if you give it keys, otherwise public nodes), to read the chain, check your balance and send your own transactions.
|
|
42
|
+
- **GeckoTerminal**, for pool prices and momentum, and **GoPlus** and **honeypot.is**, for token safety checks. These are sent token and pool addresses, never your wallet or key.
|
|
43
|
+
- **Your MySQL database**, where everything it remembers is kept.
|
|
44
|
+
|
|
45
|
+
## Run it on its own
|
|
46
|
+
|
|
47
|
+
You need Python 3.12+, a MySQL database and a bot token from [@BotFather](https://t.me/BotFather).
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install crypto-scanner-bot
|
|
51
|
+
python -m crypto_scanner
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Run it from a folder with a `.env` file holding the settings below. [.env.example](.env.example) is a starting point. To find your Telegram user ID for `OWNER_ID`, message [@userinfobot](https://t.me/userinfobot). Then send `/start` to your bot to open the dashboard.
|
|
55
|
+
|
|
56
|
+
To look around before anything runs, set `MODE=off` first: both monitors start ⏸️ Off for that run, whatever modes are saved.
|
|
57
|
+
|
|
58
|
+
## Settings
|
|
59
|
+
|
|
60
|
+
| Setting | Environment variable | Purpose |
|
|
61
|
+
|---|---|---|
|
|
62
|
+
| `token` | `BOT_TOKEN` | Required. Your bot's token |
|
|
63
|
+
| `owner_id` | `OWNER_ID` | Required. Your Telegram user ID; the bot answers nobody else |
|
|
64
|
+
| `db_url` | `DB_URL` | Required. `mysql://user:pass@host:3306/db`. Tables are created on first start: `pairs`, `positions` and `scanner_settings` |
|
|
65
|
+
| `wallet_address` | `WALLET_ADDRESS` | Required. The wallet it watches and trades from |
|
|
66
|
+
| `private_key` | `PRIVATE_KEY` | Only to trade. Without it the bot can't go Live |
|
|
67
|
+
| `alerts_chat_id` | `ALERTS_CHAT_ID` | Where alerts go. Defaults to your private chat. For a group or channel, add the bot to it first (as an admin, for a channel) |
|
|
68
|
+
| `alchemy_api_key`, `ankr_api_key` | `ALCHEMY_API_KEY`, `ANKR_API_KEY` | Optional RPC keys, tried before the public nodes |
|
|
69
|
+
| `timezone` | `TIMEZONE` | Default `Europe/London` |
|
|
70
|
+
| | `SENTRY_DSN` (standalone) | Optional error reporting when run on its own |
|
|
71
|
+
| `mode` | `MODE` | `off` or `watch` to cap both monitors at that mode for this run only, without changing the saved modes. A host passes `mode="off"` for local runs |
|
|
72
|
+
| `website_url` | `WEBSITE_URL` | The website's address, such as `https://example.com/scanner`. Adds **🌐 Open Website** to the dashboard ([details](#the-website)) |
|
|
73
|
+
| `db_dashboard_url` | `DB_DASHBOARD_URL` | Optional web page for your database, such as its Heroku resources page. Database health alerts get a **🔧 Open database dashboard** button. Never put `DB_URL` here: it holds the password |
|
|
74
|
+
|
|
75
|
+
Trading limits, audit thresholds, sell rules and schedules are changed in the bot under **⚙️ Settings** and saved in `scanner_settings`.
|
|
76
|
+
|
|
77
|
+
Upgrading from 1.0 or 1.1: start 1.2 once first. It converts the old switches to a mode per monitor, splits the sell alerts switch, and adds the `half_eth` column; later versions no longer have those steps.
|
|
78
|
+
|
|
79
|
+
## Use it inside another bot
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from crypto_scanner import start_scanner_bot, stop_scanner_bot
|
|
83
|
+
|
|
84
|
+
await start_scanner_bot(
|
|
85
|
+
share_with=application,
|
|
86
|
+
owner_id=OWNER_ID,
|
|
87
|
+
alerts_chat_id=ALERTS_CHAT_ID,
|
|
88
|
+
)
|
|
89
|
+
...
|
|
90
|
+
await stop_scanner_bot()
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Inside a host (with `share_with`), the scanner reads the same names with a `SCANNER_` prefix, such as `SCANNER_DB_URL` and `SCANNER_WALLET_ADDRESS`, so it never clashes with the host's own settings. Pass `env_prefix=` to use a different prefix. Settings the host already has, like the owner and alerts chat, can be passed as keywords instead.
|
|
94
|
+
|
|
95
|
+
Inside a host, the bot token is optional. Without it, the scanner uses the host's bot: its jobs run on the host's job queue and its alerts come from the host's bot. With it, the scanner runs its own bot alongside the host's. Any setting can be passed as a keyword instead of an environment variable. The host can show the scanner's screens in its own menus, and forward any button whose data starts with `scanner:` to `handle_button`, and text replies to `handle_text_input`:
|
|
96
|
+
|
|
97
|
+
- `scanner_block(context, brief=False)` is the scanner dashboard; `brief=True` gives a short summary for a daily message.
|
|
98
|
+
- `balances_block(brief=False)` shows the wallet's balance on each network.
|
|
99
|
+
- `scanner_health()` returns the RPC, wallet and monitor status as text, plus its alerts, so a host can show them in its own health check if it wants. It only reads: it never changes settings or cleans the database.
|
|
100
|
+
- `scanner_modes()` returns each monitor's mode for this run, such as `{"new": "watch", "trending": "off"}`, so a host can tell whether the scanner is doing anything.
|
|
101
|
+
- `add_web_routes(app, prefix="/scanner")` adds the website to the host's `aiohttp` app ([details](#the-website)). Pass `website_url=` to `start_scanner_bot` so the dashboard links to it.
|
|
102
|
+
|
|
103
|
+
## The website
|
|
104
|
+
|
|
105
|
+
The website needs a public address with HTTPS: Telegram's login only works on a real domain, never on `localhost` or a bare IP. Hosts like Heroku give you one.
|
|
106
|
+
|
|
107
|
+
- **On its own:** set `PORT` and `python -m crypto_scanner` serves the website on that port as well as running the bot. Heroku sets `PORT` for you. The site is at `/scanner`, and `/` goes there.
|
|
108
|
+
- **Inside a host:** call `add_web_routes(app)` on the host's own `aiohttp` app. The site is at `/scanner` on the host's address; pass `prefix=` to move it.
|
|
109
|
+
- **Behind a proxy:** the site reads `X-Forwarded-Proto` to tell it's on HTTPS, so its login cookie is only sent over HTTPS. Heroku and most proxies set it.
|
|
110
|
+
|
|
111
|
+
Then:
|
|
112
|
+
|
|
113
|
+
1. In [@BotFather](https://t.me/BotFather), send `/setdomain`, pick the bot the scanner runs on (the host's bot when it shares one) and send the domain on its own, such as `example.com`.
|
|
114
|
+
2. Set `WEBSITE_URL` to the site's full address, such as `https://example.com/scanner`. The dashboard gets **🌐 Open Website**, which opens the website already logged in.
|
|
115
|
+
|
|
116
|
+
Only `OWNER_ID` can log in. Anyone else who tries is told the dashboard is only for the owner.
|
|
117
|
+
|
|
118
|
+
## Development
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
pip install -e ".[dev]"
|
|
122
|
+
pre-commit install
|
|
123
|
+
pytest
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
`pre-commit` runs Ruff, mypy and a file-size check. See [CONTRIBUTING.md](CONTRIBUTING.md) for where things go and how releases work, and [SECURITY.md](SECURITY.md) to report a security problem privately.
|
|
127
|
+
|
|
128
|
+
## Licence
|
|
129
|
+
|
|
130
|
+
[MIT](LICENSE).
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "crypto-scanner-bot"
|
|
7
|
+
version = "2.0.0"
|
|
8
|
+
description = "Self-hosted Telegram bot that watches new crypto tokens, audits them and can trade them from your own wallet."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Adz1DoubleD" }]
|
|
13
|
+
keywords = ["telegram", "bot", "crypto", "ethereum", "base", "uniswap", "scanner"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Framework :: AsyncIO",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Programming Language :: Python :: 3.14",
|
|
22
|
+
"Topic :: Communications :: Chat",
|
|
23
|
+
]
|
|
24
|
+
dependencies = [
|
|
25
|
+
"python-telegram-bot[job-queue]>=22,<23",
|
|
26
|
+
"aiomysql[rsa]>=0.3,<0.4",
|
|
27
|
+
"sentry-sdk>=2,<3",
|
|
28
|
+
"web3>=8,<9",
|
|
29
|
+
"aiohttp>=3.9,<4",
|
|
30
|
+
"httpx>=0.28,<1",
|
|
31
|
+
"python-dotenv>=1,<2",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.optional-dependencies]
|
|
35
|
+
dev = [
|
|
36
|
+
"pytest==9.2.0",
|
|
37
|
+
"pytest-asyncio==1.5.0",
|
|
38
|
+
"freezegun==1.5.5",
|
|
39
|
+
"mypy==2.4.1",
|
|
40
|
+
"ruff==0.17.5",
|
|
41
|
+
"pre_commit==4.7.0",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
[project.urls]
|
|
45
|
+
Homepage = "https://github.com/Adz1DoubleD/crypto-scanner-bot"
|
|
46
|
+
Issues = "https://github.com/Adz1DoubleD/crypto-scanner-bot/issues"
|
|
47
|
+
|
|
48
|
+
[tool.setuptools.packages.find]
|
|
49
|
+
where = ["src"]
|
|
50
|
+
include = ["crypto_scanner*"]
|
|
51
|
+
|
|
52
|
+
[tool.setuptools.package-data]
|
|
53
|
+
crypto_scanner = ["py.typed"]
|
|
54
|
+
|
|
55
|
+
[tool.pytest.ini_options]
|
|
56
|
+
testpaths = ["tests"]
|
|
57
|
+
pythonpath = ["."]
|
|
58
|
+
asyncio_mode = "auto"
|
|
59
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
60
|
+
|
|
61
|
+
[tool.mypy]
|
|
62
|
+
python_version = "3.12"
|
|
63
|
+
ignore_missing_imports = true
|
|
64
|
+
check_untyped_defs = true
|
|
65
|
+
disallow_untyped_defs = true
|
|
66
|
+
disallow_incomplete_defs = true
|
|
67
|
+
disable_error_code = ["union-attr"]
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Crypto scanner: start it on its own or inside a host bot, and the functions a host can use."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import sentry_sdk
|
|
9
|
+
from telegram import Update
|
|
10
|
+
from telegram.ext import (
|
|
11
|
+
Application,
|
|
12
|
+
CallbackQueryHandler,
|
|
13
|
+
CommandHandler,
|
|
14
|
+
ContextTypes,
|
|
15
|
+
MessageHandler,
|
|
16
|
+
filters,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from . import jobs
|
|
20
|
+
from .blocks import dashboard
|
|
21
|
+
from .blocks.balances import balances_block
|
|
22
|
+
from .buttons import handle_button
|
|
23
|
+
from .db import close_db, init_scanner_db
|
|
24
|
+
from .health import scanner_health
|
|
25
|
+
from .networks import refresh_networks
|
|
26
|
+
from .settings import (
|
|
27
|
+
ENV_VARS,
|
|
28
|
+
MODE_LIVE,
|
|
29
|
+
MODE_NAMES,
|
|
30
|
+
MODE_OFF,
|
|
31
|
+
MODE_WATCH,
|
|
32
|
+
MONITORS,
|
|
33
|
+
SETTINGS,
|
|
34
|
+
current_mode,
|
|
35
|
+
forced_mode,
|
|
36
|
+
is_owner,
|
|
37
|
+
setup,
|
|
38
|
+
)
|
|
39
|
+
from .text_input import handle_text_input
|
|
40
|
+
from .w3 import close_w3
|
|
41
|
+
from .web import add_web_routes
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
__version__ = version("crypto-scanner-bot")
|
|
45
|
+
except PackageNotFoundError:
|
|
46
|
+
__version__ = "0.0.0"
|
|
47
|
+
|
|
48
|
+
NOISE = (
|
|
49
|
+
"httpx.ReadError",
|
|
50
|
+
"RemoteProtocolError",
|
|
51
|
+
"Timed out",
|
|
52
|
+
"Query is too old",
|
|
53
|
+
"query id is invalid",
|
|
54
|
+
"Message is not modified",
|
|
55
|
+
"Conflict: terminated by other getUpdates",
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
__all__ = [
|
|
59
|
+
"__version__",
|
|
60
|
+
"add_web_routes",
|
|
61
|
+
"balances_block",
|
|
62
|
+
"handle_button",
|
|
63
|
+
"handle_text_input",
|
|
64
|
+
"scanner_block",
|
|
65
|
+
"scanner_health",
|
|
66
|
+
"scanner_modes",
|
|
67
|
+
"start_scanner_bot",
|
|
68
|
+
"stop_scanner_bot",
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def scanner_modes() -> dict[str, str]:
|
|
73
|
+
"""Each monitor's mode for this run, as {"new": "watch", "trending": "off"}.
|
|
74
|
+
|
|
75
|
+
Values are "off", "watch" or "live", after any cap set at start-up.
|
|
76
|
+
"""
|
|
77
|
+
names = {MODE_OFF: "off", MODE_WATCH: "watch", MODE_LIVE: "live"}
|
|
78
|
+
return {monitor: names[current_mode(monitor)] for monitor in MONITORS}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def scanner_block(
|
|
82
|
+
context: ContextTypes.DEFAULT_TYPE, brief: bool = False
|
|
83
|
+
) -> dict:
|
|
84
|
+
"""The scanner dashboard as a block: {"text": ..., "reply_markup": ...}.
|
|
85
|
+
|
|
86
|
+
With brief=True it returns only the stats text, for a host's daily summary.
|
|
87
|
+
"""
|
|
88
|
+
return await dashboard.handle_block(context, brief=brief)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
async def start_scanner_bot(
|
|
92
|
+
share_with: Application | None = None,
|
|
93
|
+
env_prefix: str | None = None,
|
|
94
|
+
**options: Any,
|
|
95
|
+
) -> Application:
|
|
96
|
+
"""Start the scanner and return the Application it runs on.
|
|
97
|
+
|
|
98
|
+
share_with: a host's Application. Without a bot token the scanner then runs
|
|
99
|
+
its jobs on the host's bot; with one it runs its own bot alongside.
|
|
100
|
+
env_prefix: prefix for its environment variables, "SCANNER_" inside a host
|
|
101
|
+
and none on its own.
|
|
102
|
+
options: settings that override the environment, such as owner_id,
|
|
103
|
+
alerts_chat_id, timezone or mode="off".
|
|
104
|
+
"""
|
|
105
|
+
if env_prefix is None:
|
|
106
|
+
env_prefix = "" if share_with is None else "SCANNER_"
|
|
107
|
+
setup(env_prefix, **options)
|
|
108
|
+
required: tuple[str, ...] = ("owner_id", "db_url", "wallet_address")
|
|
109
|
+
if share_with is None:
|
|
110
|
+
required = ("token", *required)
|
|
111
|
+
missing = [
|
|
112
|
+
f"{env_prefix}{ENV_VARS[name]}"
|
|
113
|
+
for name in required
|
|
114
|
+
if not getattr(SETTINGS, name)
|
|
115
|
+
]
|
|
116
|
+
if missing:
|
|
117
|
+
raise ValueError(f"Crypto scanner needs these settings: {', '.join(missing)}")
|
|
118
|
+
if not SETTINGS.alerts_chat_id:
|
|
119
|
+
SETTINGS.alerts_chat_id = SETTINGS.owner_id
|
|
120
|
+
refresh_networks()
|
|
121
|
+
|
|
122
|
+
os.environ.setdefault("PTB_TIMEDELTA", "1")
|
|
123
|
+
for name in ("telegram", "httpx"):
|
|
124
|
+
logging.getLogger(name).addFilter(
|
|
125
|
+
lambda record: not any(n in record.getMessage() for n in NOISE)
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
await init_scanner_db()
|
|
129
|
+
|
|
130
|
+
mode = (
|
|
131
|
+
f"New {MODE_NAMES[current_mode('new')]}, "
|
|
132
|
+
f"Trending {MODE_NAMES[current_mode('trending')]}"
|
|
133
|
+
+ (", for this run" if forced_mode() is not None else "")
|
|
134
|
+
)
|
|
135
|
+
if share_with is not None and not SETTINGS.token:
|
|
136
|
+
jobs.application = share_with
|
|
137
|
+
jobs.shares_host = True
|
|
138
|
+
jobs.start_jobs(share_with)
|
|
139
|
+
print(f"🚀 Crypto scanner running on the host's bot ({mode})")
|
|
140
|
+
return share_with
|
|
141
|
+
|
|
142
|
+
application = Application.builder().token(SETTINGS.token).build()
|
|
143
|
+
application.add_handler(CommandHandler("start", _command_start))
|
|
144
|
+
application.add_handler(
|
|
145
|
+
CallbackQueryHandler(handle_button, pattern=r"^(scanner:|cancel$|ignore$)")
|
|
146
|
+
)
|
|
147
|
+
application.add_handler(
|
|
148
|
+
MessageHandler(
|
|
149
|
+
filters.TEXT & ~filters.COMMAND & ~filters.UpdateType.CHANNEL_POSTS,
|
|
150
|
+
handle_text_input,
|
|
151
|
+
)
|
|
152
|
+
)
|
|
153
|
+
application.add_error_handler(_error_handler)
|
|
154
|
+
if share_with is not None:
|
|
155
|
+
application.bot_data["host"] = share_with
|
|
156
|
+
|
|
157
|
+
await application.initialize()
|
|
158
|
+
await application.start()
|
|
159
|
+
jobs.application = application
|
|
160
|
+
jobs.shares_host = False
|
|
161
|
+
jobs.start_jobs(application)
|
|
162
|
+
await application.updater.start_polling(allowed_updates=Update.ALL_TYPES)
|
|
163
|
+
print(
|
|
164
|
+
f"🚀 Crypto scanner running on its own bot @{application.bot.username} ({mode})"
|
|
165
|
+
)
|
|
166
|
+
return application
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
async def stop_scanner_bot() -> None:
|
|
170
|
+
"""Stop the scanner's jobs, and its own bot if it started one."""
|
|
171
|
+
application = jobs.application
|
|
172
|
+
if application is not None:
|
|
173
|
+
await jobs.stop_jobs(application)
|
|
174
|
+
if jobs.shares_host:
|
|
175
|
+
for name in jobs.JOBS:
|
|
176
|
+
for job in application.job_queue.get_jobs_by_name(name):
|
|
177
|
+
job.schedule_removal()
|
|
178
|
+
elif application.updater and application.updater.running:
|
|
179
|
+
await application.updater.stop()
|
|
180
|
+
if not jobs.shares_host and application.running:
|
|
181
|
+
await application.stop()
|
|
182
|
+
if not jobs.shares_host and application._initialized:
|
|
183
|
+
await application.shutdown()
|
|
184
|
+
jobs.application = None
|
|
185
|
+
jobs.shares_host = False
|
|
186
|
+
await close_w3()
|
|
187
|
+
await close_db()
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
async def _command_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
|
191
|
+
if not is_owner(update.effective_user.id):
|
|
192
|
+
await update.message.reply_text("This bot only answers its owner.")
|
|
193
|
+
return
|
|
194
|
+
context.user_data.pop("state", None)
|
|
195
|
+
block = await dashboard.handle_block(context)
|
|
196
|
+
await update.message.reply_text(
|
|
197
|
+
block["text"],
|
|
198
|
+
reply_markup=block["reply_markup"],
|
|
199
|
+
parse_mode="Markdown",
|
|
200
|
+
disable_web_page_preview=True,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
async def _error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
|
205
|
+
if any(n.lower() in str(context.error).lower() for n in NOISE):
|
|
206
|
+
return
|
|
207
|
+
sentry_sdk.capture_exception(context.error)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Run the scanner on its own with `python -m crypto_scanner`."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
import sentry_sdk
|
|
7
|
+
from aiohttp import web
|
|
8
|
+
from dotenv import find_dotenv, load_dotenv
|
|
9
|
+
|
|
10
|
+
from crypto_scanner import add_web_routes, start_scanner_bot, stop_scanner_bot
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
async def main() -> None:
|
|
14
|
+
load_dotenv(find_dotenv(usecwd=True))
|
|
15
|
+
sentry_sdk.init(dsn=os.environ.get("SENTRY_DSN"))
|
|
16
|
+
try:
|
|
17
|
+
await start_scanner_bot()
|
|
18
|
+
except ValueError as e:
|
|
19
|
+
print(f"❌ {e}. Add them to .env (see .env.example).")
|
|
20
|
+
return
|
|
21
|
+
runner = None
|
|
22
|
+
if os.environ.get("PORT"):
|
|
23
|
+
app = web.Application()
|
|
24
|
+
add_web_routes(app)
|
|
25
|
+
|
|
26
|
+
async def to_site(request: web.Request) -> web.Response:
|
|
27
|
+
raise web.HTTPFound("/scanner/")
|
|
28
|
+
|
|
29
|
+
app.router.add_get("/", to_site)
|
|
30
|
+
runner = web.AppRunner(app)
|
|
31
|
+
await runner.setup()
|
|
32
|
+
await web.TCPSite(runner, "0.0.0.0", int(os.environ["PORT"])).start()
|
|
33
|
+
print(f"🌐 Website running on port {os.environ['PORT']}")
|
|
34
|
+
try:
|
|
35
|
+
await asyncio.Event().wait()
|
|
36
|
+
finally:
|
|
37
|
+
if runner is not None:
|
|
38
|
+
await runner.cleanup()
|
|
39
|
+
await stop_scanner_bot()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
if __name__ == "__main__":
|
|
43
|
+
try:
|
|
44
|
+
asyncio.run(main())
|
|
45
|
+
except KeyboardInterrupt:
|
|
46
|
+
pass
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The scanner's Telegram screens."""
|