crypto-scanner-bot 2.0.0__py3-none-any.whl

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.
Files changed (42) hide show
  1. crypto_scanner/__init__.py +207 -0
  2. crypto_scanner/__main__.py +46 -0
  3. crypto_scanner/blocks/__init__.py +1 -0
  4. crypto_scanner/blocks/balances.py +47 -0
  5. crypto_scanner/blocks/dashboard.py +535 -0
  6. crypto_scanner/blocks/positions.py +407 -0
  7. crypto_scanner/blocks/settings.py +448 -0
  8. crypto_scanner/blocks/tokens.py +326 -0
  9. crypto_scanner/buttons.py +88 -0
  10. crypto_scanner/constants.py +35 -0
  11. crypto_scanner/db/__init__.py +14 -0
  12. crypto_scanner/db/core.py +80 -0
  13. crypto_scanner/db/options.py +20 -0
  14. crypto_scanner/db/schema.py +139 -0
  15. crypto_scanner/db/tokens.py +598 -0
  16. crypto_scanner/health.py +221 -0
  17. crypto_scanner/helpers.py +119 -0
  18. crypto_scanner/jobs.py +408 -0
  19. crypto_scanner/networks.py +509 -0
  20. crypto_scanner/py.typed +0 -0
  21. crypto_scanner/settings.py +139 -0
  22. crypto_scanner/text_input.py +22 -0
  23. crypto_scanner/trading/__init__.py +1 -0
  24. crypto_scanner/trading/monitors.py +465 -0
  25. crypto_scanner/trading/trending.py +230 -0
  26. crypto_scanner/trading/watchers.py +165 -0
  27. crypto_scanner/w3/__init__.py +169 -0
  28. crypto_scanner/w3/audit.py +529 -0
  29. crypto_scanner/w3/tools.py +161 -0
  30. crypto_scanner/w3/trade.py +495 -0
  31. crypto_scanner/w3/v4.py +138 -0
  32. crypto_scanner/web/__init__.py +34 -0
  33. crypto_scanner/web/auth.py +150 -0
  34. crypto_scanner/web/charts.py +130 -0
  35. crypto_scanner/web/core.py +46 -0
  36. crypto_scanner/web/pages.py +150 -0
  37. crypto_scanner/web/views.py +538 -0
  38. crypto_scanner_bot-2.0.0.dist-info/METADATA +166 -0
  39. crypto_scanner_bot-2.0.0.dist-info/RECORD +42 -0
  40. crypto_scanner_bot-2.0.0.dist-info/WHEEL +5 -0
  41. crypto_scanner_bot-2.0.0.dist-info/licenses/LICENSE +21 -0
  42. crypto_scanner_bot-2.0.0.dist-info/top_level.txt +1 -0
@@ -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."""
@@ -0,0 +1,47 @@
1
+ """The wallet balances screen."""
2
+
3
+ from telegram import InlineKeyboardButton, InlineKeyboardMarkup
4
+
5
+ from ..networks import NETWORKS
6
+ from ..settings import SETTINGS
7
+ from ..w3.tools import wallet_balances
8
+
9
+
10
+ async def balances_block(brief: bool = False) -> dict:
11
+ """The wallet's ETH balance on each network as a block."""
12
+ wallet = await wallet_balances()
13
+ eth_usd = wallet["eth_usd"]
14
+
15
+ buttons = []
16
+ body = ""
17
+ for name, eth_val in wallet["networks"]:
18
+ if eth_val is not None:
19
+ body += f" ├ {name}: {eth_val:.4f} ETH (${eth_val * eth_usd:.2f})\n"
20
+ base = NETWORKS.get(name, {}).get("scan", "").replace("/tx/", "")
21
+ buttons.append(
22
+ InlineKeyboardButton(
23
+ f"View {name}", url=f"{base}/address/{SETTINGS.wallet_address}"
24
+ )
25
+ )
26
+ else:
27
+ body += f" ├ {name}: ⚠️ Connection Error\n"
28
+
29
+ total_eth = wallet["total"]
30
+ body += f" └ *Total: {total_eth:.4f} ETH (${total_eth * eth_usd:.2f})*\n"
31
+
32
+ delta = wallet["delta"]
33
+ delta_str = f" ({delta:+.2f}% 24h)" if delta is not None else ""
34
+
35
+ text = f" ₿ *Crypto*{delta_str}\n" + body + "\n"
36
+
37
+ kb = [buttons[i : i + 2] for i in range(0, len(buttons), 2)]
38
+
39
+ kb.append([InlineKeyboardButton("🔄 Refresh", callback_data="scanner:balances")])
40
+ kb.append([InlineKeyboardButton("❌ Close", callback_data="cancel")])
41
+
42
+ return {
43
+ "text": text,
44
+ "reply_markup": InlineKeyboardMarkup(kb),
45
+ "parse_mode": "Markdown",
46
+ "disable_web_page_preview": True,
47
+ }