pair-scanner-bot 1.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.
- pair_scanner_bot-1.0.0/LICENSE +21 -0
- pair_scanner_bot-1.0.0/PKG-INFO +138 -0
- pair_scanner_bot-1.0.0/README.md +103 -0
- pair_scanner_bot-1.0.0/pair_scanner/__init__.py +259 -0
- pair_scanner_bot-1.0.0/pair_scanner/__main__.py +28 -0
- pair_scanner_bot-1.0.0/pair_scanner/blocks/__init__.py +0 -0
- pair_scanner_bot-1.0.0/pair_scanner/blocks/balances.py +54 -0
- pair_scanner_bot-1.0.0/pair_scanner/blocks/pairs.py +313 -0
- pair_scanner_bot-1.0.0/pair_scanner/blocks/positions.py +386 -0
- pair_scanner_bot-1.0.0/pair_scanner/blocks/scanner.py +496 -0
- pair_scanner_bot-1.0.0/pair_scanner/blocks/settings.py +316 -0
- pair_scanner_bot-1.0.0/pair_scanner/constants.py +19 -0
- pair_scanner_bot-1.0.0/pair_scanner/db/__init__.py +12 -0
- pair_scanner_bot-1.0.0/pair_scanner/db/core.py +75 -0
- pair_scanner_bot-1.0.0/pair_scanner/db/options.py +16 -0
- pair_scanner_bot-1.0.0/pair_scanner/db/pairs.py +437 -0
- pair_scanner_bot-1.0.0/pair_scanner/db/schema.py +91 -0
- pair_scanner_bot-1.0.0/pair_scanner/health.py +147 -0
- pair_scanner_bot-1.0.0/pair_scanner/helpers.py +110 -0
- pair_scanner_bot-1.0.0/pair_scanner/jobs.py +323 -0
- pair_scanner_bot-1.0.0/pair_scanner/monitors.py +490 -0
- pair_scanner_bot-1.0.0/pair_scanner/networks.py +403 -0
- pair_scanner_bot-1.0.0/pair_scanner/settings.py +113 -0
- pair_scanner_bot-1.0.0/pair_scanner/w3/__init__.py +142 -0
- pair_scanner_bot-1.0.0/pair_scanner/w3/audit.py +446 -0
- pair_scanner_bot-1.0.0/pair_scanner/w3/tools.py +114 -0
- pair_scanner_bot-1.0.0/pair_scanner/w3/trade.py +428 -0
- pair_scanner_bot-1.0.0/pair_scanner/watchers.py +129 -0
- pair_scanner_bot-1.0.0/pair_scanner_bot.egg-info/PKG-INFO +138 -0
- pair_scanner_bot-1.0.0/pair_scanner_bot.egg-info/SOURCES.txt +49 -0
- pair_scanner_bot-1.0.0/pair_scanner_bot.egg-info/dependency_links.txt +1 -0
- pair_scanner_bot-1.0.0/pair_scanner_bot.egg-info/requires.txt +14 -0
- pair_scanner_bot-1.0.0/pair_scanner_bot.egg-info/top_level.txt +1 -0
- pair_scanner_bot-1.0.0/pyproject.toml +54 -0
- pair_scanner_bot-1.0.0/setup.cfg +4 -0
- pair_scanner_bot-1.0.0/tests/test_bot.py +458 -0
- pair_scanner_bot-1.0.0/tests/test_db_pairs.py +315 -0
- pair_scanner_bot-1.0.0/tests/test_health.py +198 -0
- pair_scanner_bot-1.0.0/tests/test_jobs.py +254 -0
- pair_scanner_bot-1.0.0/tests/test_monitors.py +1083 -0
- pair_scanner_bot-1.0.0/tests/test_package.py +5 -0
- pair_scanner_bot-1.0.0/tests/test_schema.py +98 -0
- pair_scanner_bot-1.0.0/tests/test_settings.py +81 -0
- pair_scanner_bot-1.0.0/tests/test_w3_audit.py +359 -0
- pair_scanner_bot-1.0.0/tests/test_w3_core.py +303 -0
- pair_scanner_bot-1.0.0/tests/test_w3_honeypot.py +85 -0
- pair_scanner_bot-1.0.0/tests/test_w3_tools.py +110 -0
- pair_scanner_bot-1.0.0/tests/test_w3_trade.py +266 -0
- pair_scanner_bot-1.0.0/tests/test_w3_trade_timeouts.py +76 -0
- pair_scanner_bot-1.0.0/tests/test_watch_only.py +219 -0
- pair_scanner_bot-1.0.0/tests/test_watchers.py +204 -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,138 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pair-scanner-bot
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Self-hosted Telegram bot that watches new token pairs, 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/pair-scanner-bot
|
|
8
|
+
Project-URL: Issues, https://github.com/Adz1DoubleD/pair-scanner-bot/issues
|
|
9
|
+
Keywords: telegram,bot,ethereum,base,uniswap,scanner
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
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: ruff==0.17.5; extra == "dev"
|
|
33
|
+
Requires-Dist: pre_commit==4.7.0; extra == "dev"
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
|
|
36
|
+
# pair-scanner-bot
|
|
37
|
+
|
|
38
|
+
A self-hosted Telegram bot that watches decentralised exchanges on Base for new token pairs, audits them, and can buy and sell them from **your own wallet**. It runs on its own, or inside another python-telegram-bot application.
|
|
39
|
+
|
|
40
|
+
> **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.
|
|
41
|
+
>
|
|
42
|
+
> Not affiliated with Uniswap, Aerodrome, GoPlus, honeypot.is, GeckoTerminal, DEX Screener or any RPC provider.
|
|
43
|
+
|
|
44
|
+
**Status:** early work in progress.
|
|
45
|
+
|
|
46
|
+
## What it does
|
|
47
|
+
|
|
48
|
+
- **Finds new pairs.** It watches the Uniswap V2, Uniswap V3 and Aerodrome factories on Base for new pools paired with WETH.
|
|
49
|
+
- **Audits them.** It checks liquidity, the liquidity-to-market-cap ratio, locked LP, taxes, contract security (GoPlus), honeypot risk (honeypot.is), and whether a sale actually goes through (simulated against the chain).
|
|
50
|
+
- **Buys what passes,** if trading is on, up to your limits.
|
|
51
|
+
- **Sells** on take-profit, stop-loss, trailing stop, rug (liquidity drop), dead token, or a honeypot appearing later.
|
|
52
|
+
- **Strategy monitor (optional):** buys established pools with strong one-hour momentum.
|
|
53
|
+
- **Alerts** for every buy, sell, would-buy and health problem.
|
|
54
|
+
- **Screens:** the scanner dashboard, pairs, positions, wallet balances (on Base and Ethereum), health, settings and CSV exports of every pair and position for your own records.
|
|
55
|
+
|
|
56
|
+
## Safety
|
|
57
|
+
|
|
58
|
+
- **Watch-only by default.** A new install finds and audits pairs and tells you what it *would* buy, but never buys. Turning trading on asks you to confirm, and needs `PRIVATE_KEY`.
|
|
59
|
+
- **Owner only.** The bot answers only `OWNER_ID`.
|
|
60
|
+
- **Your key stays yours.** It's read from your environment, used to sign your own transactions, and never printed, stored or sent anywhere else.
|
|
61
|
+
- **Cautious defaults:** 0.001 ETH per buy, at most 3 positions, 5% slippage, and the strategy off.
|
|
62
|
+
- **Balance floor.** If the wallet falls below the minimum balance (0.01 ETH by default) while trading is on, the health check switches the monitors off and alerts you. In watch-only the balance only shows on the Health screen, because nothing is bought.
|
|
63
|
+
- **Its own health check.** Every `health_check_interval` minutes it checks the RPCs, the wallet balance, the database (size, read-only, offline) and the pairs feed, and only messages you when something's wrong. When the database nears `db_cleanup_mb` it clears the archive first. **🩺 Health** on the dashboard shows the same check whenever you want.
|
|
64
|
+
- **Watch-only stops new buys, not sells.** Positions it already holds keep their stop-losses.
|
|
65
|
+
|
|
66
|
+
## What it connects to
|
|
67
|
+
|
|
68
|
+
There's no telemetry: nothing is sent to the authors. The bot itself talks to:
|
|
69
|
+
|
|
70
|
+
- **Telegram**, for your messages and alerts.
|
|
71
|
+
- **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.
|
|
72
|
+
- **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.
|
|
73
|
+
- **Your MySQL database**, where everything it remembers is kept.
|
|
74
|
+
|
|
75
|
+
## Run it on its own
|
|
76
|
+
|
|
77
|
+
You need Python 3.12+, a MySQL database and a bot token from [@BotFather](https://t.me/BotFather).
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
pip install pair-scanner-bot
|
|
81
|
+
python -m pair_scanner
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
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.
|
|
85
|
+
|
|
86
|
+
To look around before anything runs, set `TEST_MODE=1` first.
|
|
87
|
+
|
|
88
|
+
## Settings
|
|
89
|
+
|
|
90
|
+
| Setting | Environment variable | Purpose |
|
|
91
|
+
|---|---|---|
|
|
92
|
+
| `token` | `BOT_TOKEN` | Required. Your bot's token |
|
|
93
|
+
| `owner_id` | `OWNER_ID` | Required. Your Telegram user ID; the bot answers nobody else |
|
|
94
|
+
| `db_url` | `DB_URL` | Required. `mysql://user:pass@host:3306/db`. Tables are created on first start: `pairs`, `positions` and `scanner_settings` |
|
|
95
|
+
| `wallet_address` | `WALLET_ADDRESS` | Required. The wallet it watches and trades from |
|
|
96
|
+
| `private_key` | `PRIVATE_KEY` | Only to trade. Without it the bot stays watch-only |
|
|
97
|
+
| `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) |
|
|
98
|
+
| `alchemy_api_key`, `ankr_api_key` | `ALCHEMY_API_KEY`, `ANKR_API_KEY` | Optional RPC keys, tried before the public nodes |
|
|
99
|
+
| `timezone` | `TIMEZONE` | Default `Europe/London` |
|
|
100
|
+
| | `SENTRY_DSN` (standalone) | Optional error reporting when run on its own |
|
|
101
|
+
| `test_mode` | `TEST_MODE` | `1` to try the screens safely: no background jobs, no alerts and no trades, even with a private key |
|
|
102
|
+
| `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 |
|
|
103
|
+
|
|
104
|
+
Trading limits, audit thresholds, sell rules and schedules are changed in the bot under **⚙️ Settings** and saved in `scanner_settings`.
|
|
105
|
+
|
|
106
|
+
## Use it inside another bot
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from pair_scanner import start_scanner_bot, stop_scanner_bot
|
|
110
|
+
|
|
111
|
+
await start_scanner_bot(
|
|
112
|
+
share_with=application,
|
|
113
|
+
owner_id=OWNER_ID,
|
|
114
|
+
alerts_chat_id=ALERTS_CHAT_ID,
|
|
115
|
+
)
|
|
116
|
+
...
|
|
117
|
+
await stop_scanner_bot()
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
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.
|
|
121
|
+
|
|
122
|
+
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`:
|
|
123
|
+
|
|
124
|
+
- `scanner_block(context, brief=False)` is the scanner dashboard; `brief=True` gives a short summary for a daily message.
|
|
125
|
+
- `balances_block(brief=False)` shows the wallet's balance on each network.
|
|
126
|
+
- `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.
|
|
127
|
+
|
|
128
|
+
## Development
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
pip install -e ".[dev]"
|
|
132
|
+
pre-commit install
|
|
133
|
+
pytest
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Licence
|
|
137
|
+
|
|
138
|
+
[MIT](LICENSE).
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# pair-scanner-bot
|
|
2
|
+
|
|
3
|
+
A self-hosted Telegram bot that watches decentralised exchanges on Base for new token pairs, 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.
|
|
10
|
+
|
|
11
|
+
## What it does
|
|
12
|
+
|
|
13
|
+
- **Finds new pairs.** 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, taxes, contract security (GoPlus), honeypot risk (honeypot.is), and whether a sale actually goes through (simulated against the chain).
|
|
15
|
+
- **Buys what passes,** if trading is on, up to your limits.
|
|
16
|
+
- **Sells** on take-profit, stop-loss, trailing stop, rug (liquidity drop), dead token, or a honeypot appearing later.
|
|
17
|
+
- **Strategy monitor (optional):** buys established pools with strong one-hour momentum.
|
|
18
|
+
- **Alerts** for every buy, sell, would-buy and health problem.
|
|
19
|
+
- **Screens:** the scanner dashboard, pairs, positions, wallet balances (on Base and Ethereum), health, settings and CSV exports of every pair and position for your own records.
|
|
20
|
+
|
|
21
|
+
## Safety
|
|
22
|
+
|
|
23
|
+
- **Watch-only by default.** A new install finds and audits pairs and tells you what it *would* buy, but never buys. Turning trading on asks you to confirm, and needs `PRIVATE_KEY`.
|
|
24
|
+
- **Owner only.** The bot answers only `OWNER_ID`.
|
|
25
|
+
- **Your key stays yours.** It's read from your environment, used to sign your own transactions, and never printed, stored or sent anywhere else.
|
|
26
|
+
- **Cautious defaults:** 0.001 ETH per buy, at most 3 positions, 5% slippage, and the strategy off.
|
|
27
|
+
- **Balance floor.** If the wallet falls below the minimum balance (0.01 ETH by default) while trading is on, the health check switches the monitors off and alerts you. In watch-only the balance only shows on the Health screen, because nothing is bought.
|
|
28
|
+
- **Its own health check.** Every `health_check_interval` minutes it checks the RPCs, the wallet balance, the database (size, read-only, offline) and the pairs feed, and only messages you when something's wrong. When the database nears `db_cleanup_mb` it clears the archive first. **🩺 Health** on the dashboard shows the same check whenever you want.
|
|
29
|
+
- **Watch-only stops new buys, not sells.** Positions it already holds keep their stop-losses.
|
|
30
|
+
|
|
31
|
+
## What it connects to
|
|
32
|
+
|
|
33
|
+
There's no telemetry: nothing is sent to the authors. The bot itself talks to:
|
|
34
|
+
|
|
35
|
+
- **Telegram**, for your messages and alerts.
|
|
36
|
+
- **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.
|
|
37
|
+
- **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.
|
|
38
|
+
- **Your MySQL database**, where everything it remembers is kept.
|
|
39
|
+
|
|
40
|
+
## Run it on its own
|
|
41
|
+
|
|
42
|
+
You need Python 3.12+, a MySQL database and a bot token from [@BotFather](https://t.me/BotFather).
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install pair-scanner-bot
|
|
46
|
+
python -m pair_scanner
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
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.
|
|
50
|
+
|
|
51
|
+
To look around before anything runs, set `TEST_MODE=1` first.
|
|
52
|
+
|
|
53
|
+
## Settings
|
|
54
|
+
|
|
55
|
+
| Setting | Environment variable | Purpose |
|
|
56
|
+
|---|---|---|
|
|
57
|
+
| `token` | `BOT_TOKEN` | Required. Your bot's token |
|
|
58
|
+
| `owner_id` | `OWNER_ID` | Required. Your Telegram user ID; the bot answers nobody else |
|
|
59
|
+
| `db_url` | `DB_URL` | Required. `mysql://user:pass@host:3306/db`. Tables are created on first start: `pairs`, `positions` and `scanner_settings` |
|
|
60
|
+
| `wallet_address` | `WALLET_ADDRESS` | Required. The wallet it watches and trades from |
|
|
61
|
+
| `private_key` | `PRIVATE_KEY` | Only to trade. Without it the bot stays watch-only |
|
|
62
|
+
| `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) |
|
|
63
|
+
| `alchemy_api_key`, `ankr_api_key` | `ALCHEMY_API_KEY`, `ANKR_API_KEY` | Optional RPC keys, tried before the public nodes |
|
|
64
|
+
| `timezone` | `TIMEZONE` | Default `Europe/London` |
|
|
65
|
+
| | `SENTRY_DSN` (standalone) | Optional error reporting when run on its own |
|
|
66
|
+
| `test_mode` | `TEST_MODE` | `1` to try the screens safely: no background jobs, no alerts and no trades, even with a private key |
|
|
67
|
+
| `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 |
|
|
68
|
+
|
|
69
|
+
Trading limits, audit thresholds, sell rules and schedules are changed in the bot under **⚙️ Settings** and saved in `scanner_settings`.
|
|
70
|
+
|
|
71
|
+
## Use it inside another bot
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from pair_scanner import start_scanner_bot, stop_scanner_bot
|
|
75
|
+
|
|
76
|
+
await start_scanner_bot(
|
|
77
|
+
share_with=application,
|
|
78
|
+
owner_id=OWNER_ID,
|
|
79
|
+
alerts_chat_id=ALERTS_CHAT_ID,
|
|
80
|
+
)
|
|
81
|
+
...
|
|
82
|
+
await stop_scanner_bot()
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
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.
|
|
86
|
+
|
|
87
|
+
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`:
|
|
88
|
+
|
|
89
|
+
- `scanner_block(context, brief=False)` is the scanner dashboard; `brief=True` gives a short summary for a daily message.
|
|
90
|
+
- `balances_block(brief=False)` shows the wallet's balance on each network.
|
|
91
|
+
- `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.
|
|
92
|
+
|
|
93
|
+
## Development
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
pip install -e ".[dev]"
|
|
97
|
+
pre-commit install
|
|
98
|
+
pytest
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Licence
|
|
102
|
+
|
|
103
|
+
[MIT](LICENSE).
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import io
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
7
|
+
|
|
8
|
+
import sentry_sdk
|
|
9
|
+
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
|
|
10
|
+
from telegram.error import BadRequest
|
|
11
|
+
from telegram.ext import (
|
|
12
|
+
Application,
|
|
13
|
+
CallbackQueryHandler,
|
|
14
|
+
CommandHandler,
|
|
15
|
+
ContextTypes,
|
|
16
|
+
MessageHandler,
|
|
17
|
+
filters,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
from . import jobs
|
|
21
|
+
from .blocks import scanner as scanner_screen
|
|
22
|
+
from .blocks import settings as settings_screen
|
|
23
|
+
from .blocks.balances import balances_block
|
|
24
|
+
from .db import close_db, init_scanner_db
|
|
25
|
+
from .db.pairs import pairs_get_by_status
|
|
26
|
+
from .health import scanner_health
|
|
27
|
+
from .networks import refresh_networks
|
|
28
|
+
from .settings import ENV_VARS, OPTIONS, SETTINGS, is_owner, is_test_mode, setup
|
|
29
|
+
from .w3 import close_w3
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
__version__ = version("pair-scanner-bot")
|
|
33
|
+
except PackageNotFoundError:
|
|
34
|
+
__version__ = "0.0.0"
|
|
35
|
+
|
|
36
|
+
NOISE = (
|
|
37
|
+
"httpx.ReadError",
|
|
38
|
+
"RemoteProtocolError",
|
|
39
|
+
"Timed out",
|
|
40
|
+
"Query is too old",
|
|
41
|
+
"query id is invalid",
|
|
42
|
+
"Message is not modified",
|
|
43
|
+
"Conflict: terminated by other getUpdates",
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
__all__ = [
|
|
47
|
+
"__version__",
|
|
48
|
+
"balances_block",
|
|
49
|
+
"handle_button",
|
|
50
|
+
"handle_text_input",
|
|
51
|
+
"scanner_block",
|
|
52
|
+
"scanner_health",
|
|
53
|
+
"start_scanner_bot",
|
|
54
|
+
"stop_scanner_bot",
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def scanner_block(context: ContextTypes.DEFAULT_TYPE, brief=False):
|
|
59
|
+
return await scanner_screen.handle_block(context, brief=brief)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
async def home_block():
|
|
63
|
+
trading = int(OPTIONS.get("trading_enabled", 0))
|
|
64
|
+
text = "🎯 *Pair Scanner*\n\n" + (
|
|
65
|
+
"💸 Trading is on." if trading else "👀 Watch-only: trading is off."
|
|
66
|
+
)
|
|
67
|
+
return {
|
|
68
|
+
"text": text,
|
|
69
|
+
"parse_mode": "Markdown",
|
|
70
|
+
"reply_markup": InlineKeyboardMarkup(
|
|
71
|
+
[
|
|
72
|
+
[
|
|
73
|
+
InlineKeyboardButton("🎯 Scanner", callback_data="scanner:home"),
|
|
74
|
+
InlineKeyboardButton(
|
|
75
|
+
"₿ Balances", callback_data="scanner:balances"
|
|
76
|
+
),
|
|
77
|
+
],
|
|
78
|
+
[InlineKeyboardButton("⚙️ Settings", callback_data="scanner:settings")],
|
|
79
|
+
[InlineKeyboardButton("❌ Close", callback_data="cancel")],
|
|
80
|
+
]
|
|
81
|
+
),
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
async def handle_button(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
86
|
+
query = update.callback_query
|
|
87
|
+
data = query.data
|
|
88
|
+
|
|
89
|
+
if not is_owner(query.from_user.id):
|
|
90
|
+
await query.answer("This bot only answers its owner.", show_alert=True)
|
|
91
|
+
return
|
|
92
|
+
|
|
93
|
+
if data.startswith("scanner:settings"):
|
|
94
|
+
await settings_screen.handle_button(update, context)
|
|
95
|
+
return
|
|
96
|
+
|
|
97
|
+
await query.answer()
|
|
98
|
+
|
|
99
|
+
if data == "ignore":
|
|
100
|
+
return
|
|
101
|
+
|
|
102
|
+
if data == "cancel":
|
|
103
|
+
try:
|
|
104
|
+
await query.message.delete()
|
|
105
|
+
except BadRequest:
|
|
106
|
+
await query.edit_message_reply_markup(None)
|
|
107
|
+
return
|
|
108
|
+
|
|
109
|
+
if data.startswith("scanner:export:"):
|
|
110
|
+
table = data.split(":")[2]
|
|
111
|
+
if table not in ("pairs", "positions"):
|
|
112
|
+
return
|
|
113
|
+
rows = await pairs_get_by_status(None, table) or []
|
|
114
|
+
buf = io.StringIO()
|
|
115
|
+
if rows:
|
|
116
|
+
writer = csv.DictWriter(buf, fieldnames=list(rows[0]))
|
|
117
|
+
writer.writeheader()
|
|
118
|
+
writer.writerows(rows)
|
|
119
|
+
stamp = datetime.now().strftime("%Y-%m-%d")
|
|
120
|
+
await context.bot.send_document(
|
|
121
|
+
chat_id=query.message.chat_id,
|
|
122
|
+
document=io.BytesIO(buf.getvalue().encode("utf-8-sig")),
|
|
123
|
+
filename=f"{table}_{stamp}.csv",
|
|
124
|
+
caption=f"📤 {table.capitalize()}: {len(rows)} rows",
|
|
125
|
+
)
|
|
126
|
+
return
|
|
127
|
+
|
|
128
|
+
if data in ("scanner:menu", "scanner:home", "scanner:balances"):
|
|
129
|
+
if data == "scanner:menu":
|
|
130
|
+
block = await home_block()
|
|
131
|
+
elif data == "scanner:home":
|
|
132
|
+
block = await scanner_screen.handle_block(context)
|
|
133
|
+
else:
|
|
134
|
+
block = await balances_block()
|
|
135
|
+
await query.edit_message_text(
|
|
136
|
+
block["text"],
|
|
137
|
+
reply_markup=block.get("reply_markup"),
|
|
138
|
+
parse_mode="Markdown",
|
|
139
|
+
disable_web_page_preview=True,
|
|
140
|
+
)
|
|
141
|
+
return
|
|
142
|
+
|
|
143
|
+
await scanner_screen.handle_button(update, context)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
async def handle_text_input(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
147
|
+
if not is_owner(update.effective_user.id):
|
|
148
|
+
return
|
|
149
|
+
state = context.user_data.get("state") or ""
|
|
150
|
+
if not state.startswith("scanner:settings:"):
|
|
151
|
+
return
|
|
152
|
+
text = (update.message.text or "").strip()
|
|
153
|
+
try:
|
|
154
|
+
await update.message.delete()
|
|
155
|
+
except Exception:
|
|
156
|
+
pass
|
|
157
|
+
await settings_screen.handle_text(update, context, text)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
async def command_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
161
|
+
if not is_owner(update.effective_user.id):
|
|
162
|
+
await update.message.reply_text("This bot only answers its owner.")
|
|
163
|
+
return
|
|
164
|
+
context.user_data.pop("state", None)
|
|
165
|
+
block = await home_block()
|
|
166
|
+
await update.message.reply_text(
|
|
167
|
+
block["text"], reply_markup=block["reply_markup"], parse_mode="Markdown"
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
172
|
+
if any(n.lower() in str(context.error).lower() for n in NOISE):
|
|
173
|
+
return
|
|
174
|
+
sentry_sdk.capture_exception(context.error)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
async def start_scanner_bot(share_with=None, env_prefix=None, **options):
|
|
178
|
+
if env_prefix is None:
|
|
179
|
+
env_prefix = "" if share_with is None else "SCANNER_"
|
|
180
|
+
setup(env_prefix, **options)
|
|
181
|
+
required = ("owner_id", "db_url", "wallet_address")
|
|
182
|
+
if share_with is None:
|
|
183
|
+
required = ("token", *required)
|
|
184
|
+
missing = [
|
|
185
|
+
f"{env_prefix}{ENV_VARS[name]}"
|
|
186
|
+
for name in required
|
|
187
|
+
if not getattr(SETTINGS, name)
|
|
188
|
+
]
|
|
189
|
+
if missing:
|
|
190
|
+
raise ValueError(f"Pair scanner needs these settings: {', '.join(missing)}")
|
|
191
|
+
if not SETTINGS.alerts_chat_id:
|
|
192
|
+
SETTINGS.alerts_chat_id = SETTINGS.owner_id
|
|
193
|
+
refresh_networks()
|
|
194
|
+
|
|
195
|
+
os.environ.setdefault("PTB_TIMEDELTA", "1")
|
|
196
|
+
for name in ("telegram", "httpx"):
|
|
197
|
+
logging.getLogger(name).addFilter(
|
|
198
|
+
lambda record: not any(n in record.getMessage() for n in NOISE)
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
await init_scanner_db()
|
|
202
|
+
|
|
203
|
+
mode = "trading" if int(OPTIONS.get("trading_enabled", 0)) else "watch-only"
|
|
204
|
+
if is_test_mode():
|
|
205
|
+
mode = "test mode"
|
|
206
|
+
if share_with is not None and not SETTINGS.token:
|
|
207
|
+
jobs.application = share_with
|
|
208
|
+
jobs.shares_host = True
|
|
209
|
+
if not is_test_mode():
|
|
210
|
+
jobs.start_jobs(share_with)
|
|
211
|
+
print(f"🚀 Pair scanner running on the host's bot ({mode})")
|
|
212
|
+
return share_with
|
|
213
|
+
|
|
214
|
+
application = Application.builder().token(SETTINGS.token).build()
|
|
215
|
+
application.add_handler(CommandHandler("start", command_start))
|
|
216
|
+
application.add_handler(
|
|
217
|
+
CallbackQueryHandler(handle_button, pattern=r"^(scanner:|cancel$|ignore$)")
|
|
218
|
+
)
|
|
219
|
+
application.add_handler(
|
|
220
|
+
MessageHandler(
|
|
221
|
+
filters.TEXT & ~filters.COMMAND & ~filters.UpdateType.CHANNEL_POSTS,
|
|
222
|
+
handle_text_input,
|
|
223
|
+
)
|
|
224
|
+
)
|
|
225
|
+
application.add_error_handler(error_handler)
|
|
226
|
+
if share_with is not None:
|
|
227
|
+
application.bot_data["host"] = share_with
|
|
228
|
+
|
|
229
|
+
await application.initialize()
|
|
230
|
+
await application.start()
|
|
231
|
+
jobs.application = application
|
|
232
|
+
jobs.shares_host = False
|
|
233
|
+
if not is_test_mode():
|
|
234
|
+
jobs.start_jobs(application)
|
|
235
|
+
await application.updater.start_polling(allowed_updates=Update.ALL_TYPES)
|
|
236
|
+
print(
|
|
237
|
+
f"🚀 Pair scanner running on its own bot @{application.bot.username} ({mode})"
|
|
238
|
+
)
|
|
239
|
+
return application
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
async def stop_scanner_bot():
|
|
243
|
+
application = jobs.application
|
|
244
|
+
if application is not None:
|
|
245
|
+
await jobs.stop_jobs(application)
|
|
246
|
+
if jobs.shares_host:
|
|
247
|
+
for name in jobs.JOBS:
|
|
248
|
+
for job in application.job_queue.get_jobs_by_name(name):
|
|
249
|
+
job.schedule_removal()
|
|
250
|
+
elif application.updater and application.updater.running:
|
|
251
|
+
await application.updater.stop()
|
|
252
|
+
if not jobs.shares_host and application.running:
|
|
253
|
+
await application.stop()
|
|
254
|
+
if not jobs.shares_host and application._initialized:
|
|
255
|
+
await application.shutdown()
|
|
256
|
+
jobs.application = None
|
|
257
|
+
jobs.shares_host = False
|
|
258
|
+
await close_w3()
|
|
259
|
+
await close_db()
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
import sentry_sdk
|
|
5
|
+
from dotenv import find_dotenv, load_dotenv
|
|
6
|
+
|
|
7
|
+
from pair_scanner import start_scanner_bot, stop_scanner_bot
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
async def main():
|
|
11
|
+
load_dotenv(find_dotenv(usecwd=True))
|
|
12
|
+
sentry_sdk.init(dsn=os.environ.get("SENTRY_DSN"))
|
|
13
|
+
try:
|
|
14
|
+
await start_scanner_bot()
|
|
15
|
+
except ValueError as e:
|
|
16
|
+
print(f"❌ {e}. Add them to .env (see .env.example).")
|
|
17
|
+
return
|
|
18
|
+
try:
|
|
19
|
+
await asyncio.Event().wait()
|
|
20
|
+
finally:
|
|
21
|
+
await stop_scanner_bot()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
if __name__ == "__main__":
|
|
25
|
+
try:
|
|
26
|
+
asyncio.run(main())
|
|
27
|
+
except KeyboardInterrupt:
|
|
28
|
+
pass
|
|
File without changes
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
|
|
3
|
+
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
|
|
4
|
+
|
|
5
|
+
from ..networks import NETWORKS
|
|
6
|
+
from ..settings import SETTINGS
|
|
7
|
+
from ..w3.tools import eth_balance_delta, fetch_eth_usd_price, fetch_network_bal
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
async def balances_block(brief=False):
|
|
11
|
+
eth_usd = await fetch_eth_usd_price()
|
|
12
|
+
|
|
13
|
+
tasks = [
|
|
14
|
+
fetch_network_bal(n, c, SETTINGS.wallet_address) for n, c in NETWORKS.items()
|
|
15
|
+
]
|
|
16
|
+
results = await asyncio.gather(*tasks)
|
|
17
|
+
|
|
18
|
+
total_eth = 0.0
|
|
19
|
+
buttons = []
|
|
20
|
+
body = ""
|
|
21
|
+
for name, eth_val in results:
|
|
22
|
+
if eth_val is not None:
|
|
23
|
+
usd_val = eth_val * eth_usd
|
|
24
|
+
total_eth += eth_val
|
|
25
|
+
body += f" ├ {name}: {eth_val:.4f} ETH (${usd_val:.2f})\n"
|
|
26
|
+
conf = NETWORKS.get(name, {})
|
|
27
|
+
base = conf.get("scan", "").replace("/tx/", "")
|
|
28
|
+
buttons.append(
|
|
29
|
+
InlineKeyboardButton(
|
|
30
|
+
f"View {name}", url=f"{base}/address/{SETTINGS.wallet_address}"
|
|
31
|
+
)
|
|
32
|
+
)
|
|
33
|
+
else:
|
|
34
|
+
body += f" ├ {name}: ⚠️ Connection Error\n"
|
|
35
|
+
|
|
36
|
+
total_usd = total_eth * eth_usd
|
|
37
|
+
body += f" └ *Total: {total_eth:.4f} ETH (${total_usd:.2f})*\n"
|
|
38
|
+
|
|
39
|
+
delta = await eth_balance_delta(total_eth)
|
|
40
|
+
delta_str = f" ({delta:+.2f}% 24h)" if delta is not None else ""
|
|
41
|
+
|
|
42
|
+
text = f" ₿ *Crypto*{delta_str}\n" + body + "\n"
|
|
43
|
+
|
|
44
|
+
kb = [buttons[i : i + 2] for i in range(0, len(buttons), 2)]
|
|
45
|
+
|
|
46
|
+
kb.append([InlineKeyboardButton("🔄 Refresh", callback_data="scanner:balances")])
|
|
47
|
+
kb.append([InlineKeyboardButton("❌ Close", callback_data="cancel")])
|
|
48
|
+
|
|
49
|
+
return {
|
|
50
|
+
"text": text,
|
|
51
|
+
"reply_markup": InlineKeyboardMarkup(kb),
|
|
52
|
+
"parse_mode": "Markdown",
|
|
53
|
+
"disable_web_page_preview": True,
|
|
54
|
+
}
|