main.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. """Main script, where all the fun starts"""
  2. # Friendly Telegram (telegram userbot)
  3. # Copyright (C) 2018-2021 The Authors
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU Affero General Public License for more details.
  12. # You should have received a copy of the GNU Affero General Public License
  13. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  15. # █▀█ █ █ █ █▀█ █▀▄ █
  16. # © Copyright 2022
  17. # https://t.me/hikariatama
  18. #
  19. # 🔒 Licensed under the GNU AGPLv3
  20. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  21. import argparse
  22. import asyncio
  23. import collections
  24. import importlib
  25. import json
  26. import logging
  27. import os
  28. import random
  29. import socket
  30. import sqlite3
  31. import sys
  32. from math import ceil
  33. import typing
  34. import telethon
  35. from telethon import events
  36. from telethon.errors.rpcerrorlist import (
  37. ApiIdInvalidError,
  38. AuthKeyDuplicatedError,
  39. PhoneNumberInvalidError,
  40. )
  41. from telethon.network.connection import (
  42. ConnectionTcpFull,
  43. ConnectionTcpMTProxyRandomizedIntermediate,
  44. )
  45. from telethon.sessions import SQLiteSession, MemorySession
  46. from . import database, loader, utils, version
  47. from .dispatcher import CommandDispatcher
  48. from .translations import Translator
  49. from .version import __version__
  50. from .tl_cache import CustomTelegramClient
  51. try:
  52. from .web import core
  53. except ImportError:
  54. web_available = False
  55. logging.exception("Unable to import web")
  56. else:
  57. web_available = True
  58. BASE_DIR = (
  59. os.path.normpath(os.path.join(utils.get_base_dir(), ".."))
  60. if "OKTETO" not in os.environ and "DOCKER" not in os.environ
  61. else "/data"
  62. )
  63. CONFIG_PATH = os.path.join(BASE_DIR, "config.json")
  64. try:
  65. import uvloop
  66. uvloop.install()
  67. except Exception:
  68. pass
  69. def run_config(data_root: str):
  70. """Load configurator.py"""
  71. from . import configurator
  72. return configurator.api_config(data_root)
  73. def get_config_key(key: str) -> typing.Union[str, bool]:
  74. """
  75. Parse and return key from config
  76. :param key: Key name in config
  77. :return: Value of config key or `False`, if it doesn't exist
  78. """
  79. try:
  80. with open(CONFIG_PATH, "r") as f:
  81. config = json.load(f)
  82. return config.get(key, False)
  83. except FileNotFoundError:
  84. return False
  85. def save_config_key(key: str, value: str) -> bool:
  86. """
  87. Save `key` with `value` to config
  88. :param key: Key name in config
  89. :param value: Desired value in config
  90. :return: `True` on success, otherwise `False`
  91. """
  92. try:
  93. # Try to open our newly created json config
  94. with open(CONFIG_PATH, "r") as f:
  95. config = json.load(f)
  96. except FileNotFoundError:
  97. # If it doesn't exist, just default config to none
  98. # It won't cause problems, bc after new save
  99. # we will create new one
  100. config = {}
  101. # Assign config value
  102. config[key] = value
  103. # And save config
  104. with open(CONFIG_PATH, "w") as f:
  105. json.dump(config, f, indent=4)
  106. return True
  107. def gen_port() -> int:
  108. """
  109. Generates random free port in case of VDS, and
  110. 8080 in case of Okteto
  111. In case of Docker, also return 8080, as it's already
  112. exposed by default
  113. :returns: Integer value of generated port
  114. """
  115. if any(trigger in os.environ for trigger in {"OKTETO", "DOCKER"}):
  116. return 8080
  117. # But for own server we generate new free port, and assign to it
  118. port = get_config_key("port")
  119. if port:
  120. return port
  121. # If we didn't get port from config, generate new one
  122. # First, try to randomly get port
  123. port = random.randint(1024, 65536)
  124. # Then ensure it's free
  125. while not socket.socket(
  126. socket.AF_INET,
  127. socket.SOCK_STREAM,
  128. ).connect_ex(("localhost", port)):
  129. # Until we find the free port, generate new one
  130. port = random.randint(1024, 65536)
  131. return port
  132. def parse_arguments() -> dict:
  133. """
  134. Parses the arguments
  135. :returns: Dictionary with arguments
  136. """
  137. parser = argparse.ArgumentParser()
  138. parser.add_argument(
  139. "--port",
  140. dest="port",
  141. action="store",
  142. default=gen_port(),
  143. type=int,
  144. )
  145. parser.add_argument("--phone", "-p", action="append")
  146. parser.add_argument("--no-web", dest="disable_web", action="store_true")
  147. parser.add_argument(
  148. "--data-root",
  149. dest="data_root",
  150. default="",
  151. help="Root path to store session files in",
  152. )
  153. parser.add_argument(
  154. "--no-auth",
  155. dest="no_auth",
  156. action="store_true",
  157. help="Disable authentication and API token input, exitting if needed",
  158. )
  159. parser.add_argument(
  160. "--proxy-host",
  161. dest="proxy_host",
  162. action="store",
  163. help="MTProto proxy host, without port",
  164. )
  165. parser.add_argument(
  166. "--proxy-port",
  167. dest="proxy_port",
  168. action="store",
  169. type=int,
  170. help="MTProto proxy port",
  171. )
  172. parser.add_argument(
  173. "--proxy-secret",
  174. dest="proxy_secret",
  175. action="store",
  176. help="MTProto proxy secret",
  177. )
  178. parser.add_argument(
  179. "--root",
  180. dest="disable_root_check",
  181. action="store_true",
  182. help="Disable `force_insecure` warning",
  183. )
  184. parser.add_argument(
  185. "--proxy-pass",
  186. dest="proxy_pass",
  187. action="store_true",
  188. help="Open proxy pass tunnel on start (not needed on setup)",
  189. )
  190. arguments = parser.parse_args()
  191. logging.debug(arguments)
  192. if sys.platform == "win32":
  193. # Subprocess support; not needed in 3.8 but not harmful
  194. asyncio.set_event_loop(asyncio.ProactorEventLoop())
  195. return arguments
  196. class SuperList(list):
  197. """
  198. Makes able: await self.allclients.send_message("foo", "bar")
  199. """
  200. def __getattribute__(self, attr: str) -> typing.Any:
  201. if hasattr(list, attr):
  202. return list.__getattribute__(self, attr)
  203. for obj in self: # TODO: find other way
  204. attribute = getattr(obj, attr)
  205. if callable(attribute):
  206. if asyncio.iscoroutinefunction(attribute):
  207. async def foobar(*args, **kwargs):
  208. return [await getattr(_, attr)(*args, **kwargs) for _ in self]
  209. return foobar
  210. return lambda *args, **kwargs: [
  211. getattr(_, attr)(*args, **kwargs) for _ in self
  212. ]
  213. return [getattr(x, attr) for x in self]
  214. class InteractiveAuthRequired(Exception):
  215. """Is being rased by Telethon, if phone is required"""
  216. def raise_auth():
  217. """Raises `InteractiveAuthRequired`"""
  218. raise InteractiveAuthRequired()
  219. class Hikka:
  220. """Main userbot instance, which can handle multiple clients"""
  221. omit_log = False
  222. def __init__(self):
  223. self.arguments = parse_arguments()
  224. self.loop = asyncio.get_event_loop()
  225. self.clients = SuperList()
  226. self.ready = asyncio.Event()
  227. self._read_sessions()
  228. self._get_api_token()
  229. self._get_proxy()
  230. def _get_proxy(self):
  231. """
  232. Get proxy tuple from --proxy-host, --proxy-port and --proxy-secret
  233. and connection to use (depends on proxy - provided or not)
  234. """
  235. if (
  236. self.arguments.proxy_host is not None
  237. and self.arguments.proxy_port is not None
  238. and self.arguments.proxy_secret is not None
  239. ):
  240. logging.debug(
  241. "Using proxy: %s:%s",
  242. self.arguments.proxy_host,
  243. self.arguments.proxy_port,
  244. )
  245. self.proxy, self.conn = (
  246. (
  247. self.arguments.proxy_host,
  248. self.arguments.proxy_port,
  249. self.arguments.proxy_secret,
  250. ),
  251. ConnectionTcpMTProxyRandomizedIntermediate,
  252. )
  253. return
  254. self.proxy, self.conn = None, ConnectionTcpFull
  255. def _read_sessions(self):
  256. """Gets sessions from environment and data directory"""
  257. self.sessions = []
  258. self.sessions += [
  259. SQLiteSession(
  260. os.path.join(
  261. self.arguments.data_root or BASE_DIR,
  262. session.rsplit(".session", maxsplit=1)[0],
  263. )
  264. )
  265. for session in filter(
  266. lambda f: f.startswith("hikka-") and f.endswith(".session"),
  267. os.listdir(self.arguments.data_root or BASE_DIR),
  268. )
  269. ]
  270. def _get_api_token(self):
  271. """Get API Token from disk or environment"""
  272. api_token_type = collections.namedtuple("api_token", ("ID", "HASH"))
  273. # Try to retrieve credintials from file, or from env vars
  274. try:
  275. with open(
  276. os.path.join(
  277. self.arguments.data_root or BASE_DIR,
  278. "api_token.txt",
  279. )
  280. ) as f:
  281. api_token = api_token_type(*[line.strip() for line in f.readlines()])
  282. except FileNotFoundError:
  283. try:
  284. from . import api_token
  285. except ImportError:
  286. try:
  287. api_token = api_token_type(
  288. os.environ["api_id"],
  289. os.environ["api_hash"],
  290. )
  291. except KeyError:
  292. api_token = None
  293. self.api_token = api_token
  294. def _init_web(self):
  295. """Initialize web"""
  296. if not web_available or getattr(self.arguments, "disable_web", False):
  297. self.web = None
  298. return
  299. self.web = core.Web(
  300. data_root=self.arguments.data_root,
  301. api_token=self.api_token,
  302. proxy=self.proxy,
  303. connection=self.conn,
  304. )
  305. def _get_token(self):
  306. """Reads or waits for user to enter API credentials"""
  307. while self.api_token is None:
  308. if self.arguments.no_auth:
  309. return
  310. if self.web:
  311. self.loop.run_until_complete(
  312. self.web.start(
  313. self.arguments.port,
  314. proxy_pass=True,
  315. )
  316. )
  317. self.loop.run_until_complete(self._web_banner())
  318. self.loop.run_until_complete(self.web.wait_for_api_token_setup())
  319. self.api_token = self.web.api_token
  320. else:
  321. run_config(self.arguments.data_root)
  322. importlib.invalidate_caches()
  323. self._get_api_token()
  324. async def save_client_session(self, client: CustomTelegramClient):
  325. if hasattr(client, "_tg_id"):
  326. telegram_id = client._tg_id
  327. else:
  328. me = await client.get_me()
  329. telegram_id = me.id
  330. client._tg_id = telegram_id
  331. client.tg_id = telegram_id
  332. client.hikka_me = me
  333. session = SQLiteSession(
  334. os.path.join(
  335. self.arguments.data_root or BASE_DIR,
  336. f"hikka-{telegram_id}",
  337. )
  338. )
  339. session.set_dc(
  340. client.session.dc_id,
  341. client.session.server_address,
  342. client.session.port,
  343. )
  344. session.auth_key = client.session.auth_key
  345. session.save()
  346. client.session = session
  347. # Set db attribute to this client in order to save
  348. # custom bot nickname from web
  349. client.hikka_db = database.Database(client)
  350. await client.hikka_db.init()
  351. async def _web_banner(self):
  352. """Shows web banner"""
  353. logging.info("✅ Web mode ready for configuration")
  354. logging.info("🌐 Please visit %s", self.web.url)
  355. async def wait_for_web_auth(self, token: str) -> bool:
  356. """
  357. Waits for web auth confirmation in Telegram
  358. :param token: Token to wait for
  359. :return: True if auth was successful, False otherwise
  360. """
  361. timeout = 5 * 60
  362. polling_interval = 1
  363. for _ in range(ceil(timeout * polling_interval)):
  364. await asyncio.sleep(polling_interval)
  365. for client in self.clients:
  366. if client.loader.inline.pop_web_auth_token(token):
  367. return True
  368. return False
  369. def _initial_setup(self) -> bool:
  370. """Responsible for first start"""
  371. if self.arguments.no_auth:
  372. return False
  373. if not self.web:
  374. try:
  375. phone = input("Phone: ")
  376. client = CustomTelegramClient(
  377. MemorySession(),
  378. self.api_token.ID,
  379. self.api_token.HASH,
  380. connection=self.conn,
  381. proxy=self.proxy,
  382. connection_retries=None,
  383. device_model="Hikka",
  384. )
  385. client.start(phone)
  386. asyncio.ensure_future(self.save_client_session(client))
  387. self.clients += [client]
  388. except (EOFError, OSError):
  389. raise
  390. return True
  391. if not self.web.running.is_set():
  392. self.loop.run_until_complete(
  393. self.web.start(
  394. self.arguments.port,
  395. proxy_pass=True,
  396. )
  397. )
  398. asyncio.ensure_future(self._web_banner())
  399. self.loop.run_until_complete(self.web.wait_for_clients_setup())
  400. return True
  401. def _init_clients(self) -> bool:
  402. """
  403. Reads session from disk and inits them
  404. :returns: `True` if at least one client started successfully
  405. """
  406. for session in self.sessions.copy():
  407. try:
  408. client = CustomTelegramClient(
  409. session,
  410. self.api_token.ID,
  411. self.api_token.HASH,
  412. connection=self.conn,
  413. proxy=self.proxy,
  414. connection_retries=None,
  415. device_model="Hikka",
  416. )
  417. client.start(phone=raise_auth if self.web else lambda: input("Phone: "))
  418. client.phone = "never gonna give you up"
  419. self.clients += [client]
  420. except sqlite3.OperationalError:
  421. logging.error(
  422. "Check that this is the only instance running. "
  423. "If that doesn't help, delete the file '%s'",
  424. session.filename,
  425. )
  426. continue
  427. except (TypeError, AuthKeyDuplicatedError):
  428. os.remove(os.path.join(BASE_DIR, f"{session}.session"))
  429. self.sessions.remove(session)
  430. except (ValueError, ApiIdInvalidError):
  431. # Bad API hash/ID
  432. run_config(self.arguments.data_root)
  433. return False
  434. except PhoneNumberInvalidError:
  435. logging.error(
  436. "Phone number is incorrect. Use international format (+XX...) "
  437. "and don't put spaces in it."
  438. )
  439. self.sessions.remove(session)
  440. except InteractiveAuthRequired:
  441. logging.error(
  442. "Session %s was terminated and re-auth is required",
  443. session.filename,
  444. )
  445. self.sessions.remove(session)
  446. return bool(self.sessions)
  447. def _init_loop(self):
  448. """Initializes main event loop and starts handler for each client"""
  449. loops = [self.amain_wrapper(client) for client in self.clients]
  450. self.loop.run_until_complete(asyncio.gather(*loops))
  451. async def amain_wrapper(self, client: CustomTelegramClient):
  452. """Wrapper around amain"""
  453. async with client:
  454. first = True
  455. me = await client.get_me()
  456. client._tg_id = me.id
  457. client.tg_id = me.id
  458. client.hikka_me = me
  459. while await self.amain(first, client):
  460. first = False
  461. async def _badge(self, client: CustomTelegramClient):
  462. """Call the badge in shell"""
  463. try:
  464. import git
  465. repo = git.Repo()
  466. build = repo.heads[0].commit.hexsha
  467. diff = repo.git.log([f"HEAD..origin/{version.branch}", "--oneline"])
  468. upd = r"Update required" if diff else r"Up-to-date"
  469. _platform = utils.get_named_platform()
  470. logo1 = f"""
  471. █ █ █ █▄▀ █▄▀ ▄▀█
  472. █▀█ █ █ █ █ █ █▀█
  473. • Build: {build[:7]}
  474. • Version: {'.'.join(list(map(str, list(__version__))))}
  475. • {upd}
  476. • Platform: {_platform}
  477. """
  478. if not self.omit_log:
  479. print(logo1)
  480. web_url = (
  481. f"🌐 Web url: {self.web.url}\n"
  482. if self.web and hasattr(self.web, "url")
  483. else ""
  484. )
  485. logging.info(
  486. "🌘 Hikka %s started\n🔏 GitHub commit SHA: %s (%s)\n%s%s",
  487. ".".join(list(map(str, list(__version__)))),
  488. build[:7],
  489. upd,
  490. web_url,
  491. _platform,
  492. )
  493. self.omit_log = True
  494. logging.info("- Started for %s -", client._tg_id)
  495. except Exception:
  496. logging.exception("Badge error")
  497. async def _add_dispatcher(
  498. self,
  499. client: CustomTelegramClient,
  500. modules: loader.Modules,
  501. db: database.Database,
  502. ):
  503. """Inits and adds dispatcher instance to client"""
  504. dispatcher = CommandDispatcher(modules, client, db)
  505. client.dispatcher = dispatcher
  506. modules.check_security = dispatcher.check_security
  507. client.add_event_handler(
  508. dispatcher.handle_incoming,
  509. events.NewMessage,
  510. )
  511. client.add_event_handler(
  512. dispatcher.handle_incoming,
  513. events.ChatAction,
  514. )
  515. client.add_event_handler(
  516. dispatcher.handle_command,
  517. events.NewMessage(forwards=False),
  518. )
  519. client.add_event_handler(
  520. dispatcher.handle_command,
  521. events.MessageEdited(),
  522. )
  523. client.add_event_handler(
  524. dispatcher.handle_raw,
  525. events.Raw(),
  526. )
  527. async def amain(self, first: bool, client: CustomTelegramClient):
  528. """Entrypoint for async init, run once for each user"""
  529. client.parse_mode = "HTML"
  530. await client.start()
  531. db = database.Database(client)
  532. await db.init()
  533. logging.debug("Got DB")
  534. logging.debug("Loading logging config...")
  535. translator = Translator(client, db)
  536. await translator.init()
  537. modules = loader.Modules(client, db, self.clients, translator)
  538. client.loader = modules
  539. if self.web:
  540. await self.web.add_loader(client, modules, db)
  541. await self.web.start_if_ready(
  542. len(self.clients),
  543. self.arguments.port,
  544. proxy_pass=self.arguments.proxy_pass,
  545. )
  546. await self._add_dispatcher(client, modules, db)
  547. await modules.register_all(None)
  548. modules.send_config()
  549. await modules.send_ready()
  550. if first:
  551. await self._badge(client)
  552. await client.run_until_disconnected()
  553. def main(self):
  554. """Main entrypoint"""
  555. self._init_web()
  556. save_config_key("port", self.arguments.port)
  557. self._get_token()
  558. if (
  559. not self.clients # Search for already inited clients
  560. and not self.sessions # Search for already added sessions
  561. or not self._init_clients() # Attempt to read sessions from env
  562. ) and not self._initial_setup(): # Otherwise attempt to run setup
  563. return
  564. self.loop.set_exception_handler(
  565. lambda _, x: logging.error(
  566. "Exception on event loop! %s",
  567. x["message"],
  568. exc_info=x.get("exception", None),
  569. )
  570. )
  571. self._init_loop()
  572. telethon.extensions.html.CUSTOM_EMOJIS = not get_config_key("disable_custom_emojis")
  573. hikka = Hikka()