main.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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. arguments = parser.parse_args()
  185. logging.debug(arguments)
  186. if sys.platform == "win32":
  187. # Subprocess support; not needed in 3.8 but not harmful
  188. asyncio.set_event_loop(asyncio.ProactorEventLoop())
  189. return arguments
  190. class SuperList(list):
  191. """
  192. Makes able: await self.allclients.send_message("foo", "bar")
  193. """
  194. def __getattribute__(self, attr: str) -> typing.Any:
  195. if hasattr(list, attr):
  196. return list.__getattribute__(self, attr)
  197. for obj in self: # TODO: find other way
  198. attribute = getattr(obj, attr)
  199. if callable(attribute):
  200. if asyncio.iscoroutinefunction(attribute):
  201. async def foobar(*args, **kwargs):
  202. return [await getattr(_, attr)(*args, **kwargs) for _ in self]
  203. return foobar
  204. return lambda *args, **kwargs: [
  205. getattr(_, attr)(*args, **kwargs) for _ in self
  206. ]
  207. return [getattr(x, attr) for x in self]
  208. class InteractiveAuthRequired(Exception):
  209. """Is being rased by Telethon, if phone is required"""
  210. def raise_auth():
  211. """Raises `InteractiveAuthRequired`"""
  212. raise InteractiveAuthRequired()
  213. class Hikka:
  214. """Main userbot instance, which can handle multiple clients"""
  215. omit_log = False
  216. def __init__(self):
  217. self.arguments = parse_arguments()
  218. self.loop = asyncio.get_event_loop()
  219. self.clients = SuperList()
  220. self.ready = asyncio.Event()
  221. self._read_sessions()
  222. self._get_api_token()
  223. self._get_proxy()
  224. def _get_proxy(self):
  225. """
  226. Get proxy tuple from --proxy-host, --proxy-port and --proxy-secret
  227. and connection to use (depends on proxy - provided or not)
  228. """
  229. if (
  230. self.arguments.proxy_host is not None
  231. and self.arguments.proxy_port is not None
  232. and self.arguments.proxy_secret is not None
  233. ):
  234. logging.debug(
  235. "Using proxy: %s:%s",
  236. self.arguments.proxy_host,
  237. self.arguments.proxy_port,
  238. )
  239. self.proxy, self.conn = (
  240. (
  241. self.arguments.proxy_host,
  242. self.arguments.proxy_port,
  243. self.arguments.proxy_secret,
  244. ),
  245. ConnectionTcpMTProxyRandomizedIntermediate,
  246. )
  247. return
  248. self.proxy, self.conn = None, ConnectionTcpFull
  249. def _read_sessions(self):
  250. """Gets sessions from environment and data directory"""
  251. self.sessions = []
  252. self.sessions += [
  253. SQLiteSession(
  254. os.path.join(
  255. self.arguments.data_root or BASE_DIR,
  256. session.rsplit(".session", maxsplit=1)[0],
  257. )
  258. )
  259. for session in filter(
  260. lambda f: f.startswith("hikka-") and f.endswith(".session"),
  261. os.listdir(self.arguments.data_root or BASE_DIR),
  262. )
  263. ]
  264. def _get_api_token(self):
  265. """Get API Token from disk or environment"""
  266. api_token_type = collections.namedtuple("api_token", ("ID", "HASH"))
  267. # Try to retrieve credintials from file, or from env vars
  268. try:
  269. with open(
  270. os.path.join(
  271. self.arguments.data_root or BASE_DIR,
  272. "api_token.txt",
  273. )
  274. ) as f:
  275. api_token = api_token_type(*[line.strip() for line in f.readlines()])
  276. except FileNotFoundError:
  277. try:
  278. from . import api_token
  279. except ImportError:
  280. try:
  281. api_token = api_token_type(
  282. os.environ["api_id"],
  283. os.environ["api_hash"],
  284. )
  285. except KeyError:
  286. api_token = None
  287. self.api_token = api_token
  288. def _init_web(self):
  289. """Initialize web"""
  290. if not web_available or getattr(self.arguments, "disable_web", False):
  291. self.web = None
  292. return
  293. self.web = core.Web(
  294. data_root=self.arguments.data_root,
  295. api_token=self.api_token,
  296. proxy=self.proxy,
  297. connection=self.conn,
  298. )
  299. def _get_token(self):
  300. """Reads or waits for user to enter API credentials"""
  301. while self.api_token is None:
  302. if self.arguments.no_auth:
  303. return
  304. if self.web:
  305. self.loop.run_until_complete(
  306. self.web.start(
  307. self.arguments.port,
  308. proxy_pass=True,
  309. )
  310. )
  311. self.loop.run_until_complete(self._web_banner())
  312. self.loop.run_until_complete(self.web.wait_for_api_token_setup())
  313. self.api_token = self.web.api_token
  314. else:
  315. run_config(self.arguments.data_root)
  316. importlib.invalidate_caches()
  317. self._get_api_token()
  318. async def save_client_session(self, client: CustomTelegramClient):
  319. if hasattr(client, "_tg_id"):
  320. telegram_id = client._tg_id
  321. else:
  322. me = await client.get_me()
  323. telegram_id = me.id
  324. client._tg_id = telegram_id
  325. client.tg_id = telegram_id
  326. client.hikka_me = me
  327. session = SQLiteSession(
  328. os.path.join(
  329. self.arguments.data_root or BASE_DIR,
  330. f"hikka-{telegram_id}",
  331. )
  332. )
  333. session.set_dc(
  334. client.session.dc_id,
  335. client.session.server_address,
  336. client.session.port,
  337. )
  338. session.auth_key = client.session.auth_key
  339. session.save()
  340. client.session = session
  341. # Set db attribute to this client in order to save
  342. # custom bot nickname from web
  343. client.hikka_db = database.Database(client)
  344. await client.hikka_db.init()
  345. async def _web_banner(self):
  346. """Shows web banner"""
  347. logging.info("✅ Web mode ready for configuration")
  348. logging.info("🌐 Please visit %s", self.web.url)
  349. async def wait_for_web_auth(self, token: str) -> bool:
  350. """
  351. Waits for web auth confirmation in Telegram
  352. :param token: Token to wait for
  353. :return: True if auth was successful, False otherwise
  354. """
  355. timeout = 5 * 60
  356. polling_interval = 1
  357. for _ in range(ceil(timeout * polling_interval)):
  358. await asyncio.sleep(polling_interval)
  359. for client in self.clients:
  360. if client.loader.inline.pop_web_auth_token(token):
  361. return True
  362. return False
  363. def _initial_setup(self) -> bool:
  364. """Responsible for first start"""
  365. if self.arguments.no_auth:
  366. return False
  367. if not self.web:
  368. try:
  369. phone = input("Phone: ")
  370. client = CustomTelegramClient(
  371. MemorySession(),
  372. self.api_token.ID,
  373. self.api_token.HASH,
  374. connection=self.conn,
  375. proxy=self.proxy,
  376. connection_retries=None,
  377. device_model="Hikka",
  378. )
  379. client.start(phone)
  380. asyncio.ensure_future(self.save_client_session(client))
  381. self.clients += [client]
  382. except (EOFError, OSError):
  383. raise
  384. return True
  385. if not self.web.running.is_set():
  386. self.loop.run_until_complete(
  387. self.web.start(
  388. self.arguments.port,
  389. proxy_pass=True,
  390. )
  391. )
  392. asyncio.ensure_future(self._web_banner())
  393. self.loop.run_until_complete(self.web.wait_for_clients_setup())
  394. return True
  395. def _init_clients(self) -> bool:
  396. """
  397. Reads session from disk and inits them
  398. :returns: `True` if at least one client started successfully
  399. """
  400. for session in self.sessions.copy():
  401. try:
  402. client = CustomTelegramClient(
  403. session,
  404. self.api_token.ID,
  405. self.api_token.HASH,
  406. connection=self.conn,
  407. proxy=self.proxy,
  408. connection_retries=None,
  409. device_model="Hikka",
  410. )
  411. client.start(phone=raise_auth if self.web else lambda: input("Phone: "))
  412. client.phone = "never gonna give you up"
  413. self.clients += [client]
  414. except sqlite3.OperationalError:
  415. logging.error(
  416. "Check that this is the only instance running. "
  417. "If that doesn't help, delete the file '%s'",
  418. session.filename,
  419. )
  420. continue
  421. except (TypeError, AuthKeyDuplicatedError):
  422. os.remove(os.path.join(BASE_DIR, f"{session}.session"))
  423. self.sessions.remove(session)
  424. except (ValueError, ApiIdInvalidError):
  425. # Bad API hash/ID
  426. run_config(self.arguments.data_root)
  427. return False
  428. except PhoneNumberInvalidError:
  429. logging.error(
  430. "Phone number is incorrect. Use international format (+XX...) "
  431. "and don't put spaces in it."
  432. )
  433. self.sessions.remove(session)
  434. except InteractiveAuthRequired:
  435. logging.error(
  436. "Session %s was terminated and re-auth is required",
  437. session.filename,
  438. )
  439. self.sessions.remove(session)
  440. return bool(self.sessions)
  441. def _init_loop(self):
  442. """Initializes main event loop and starts handler for each client"""
  443. loops = [self.amain_wrapper(client) for client in self.clients]
  444. self.loop.run_until_complete(asyncio.gather(*loops))
  445. async def amain_wrapper(self, client: CustomTelegramClient):
  446. """Wrapper around amain"""
  447. async with client:
  448. first = True
  449. me = await client.get_me()
  450. client._tg_id = me.id
  451. client.tg_id = me.id
  452. client.hikka_me = me
  453. while await self.amain(first, client):
  454. first = False
  455. async def _badge(self, client: CustomTelegramClient):
  456. """Call the badge in shell"""
  457. try:
  458. import git
  459. repo = git.Repo()
  460. build = repo.heads[0].commit.hexsha
  461. diff = repo.git.log([f"HEAD..origin/{version.branch}", "--oneline"])
  462. upd = r"Update required" if diff else r"Up-to-date"
  463. _platform = utils.get_named_platform()
  464. logo1 = f"""
  465. █ █ █ █▄▀ █▄▀ ▄▀█
  466. █▀█ █ █ █ █ █ █▀█
  467. • Build: {build[:7]}
  468. • Version: {'.'.join(list(map(str, list(__version__))))}
  469. • {upd}
  470. • Platform: {_platform}
  471. """
  472. if not self.omit_log:
  473. print(logo1)
  474. web_url = (
  475. f"🌐 Web url: {self.web.url}\n"
  476. if self.web and hasattr(self.web, "url")
  477. else ""
  478. )
  479. logging.info(
  480. "🌘 Hikka %s started\n🔏 GitHub commit SHA: %s (%s)\n%s%s",
  481. ".".join(list(map(str, list(__version__)))),
  482. build[:7],
  483. upd,
  484. web_url,
  485. _platform,
  486. )
  487. self.omit_log = True
  488. logging.info("- Started for %s -", client._tg_id)
  489. except Exception:
  490. logging.exception("Badge error")
  491. async def _add_dispatcher(
  492. self,
  493. client: CustomTelegramClient,
  494. modules: loader.Modules,
  495. db: database.Database,
  496. ):
  497. """Inits and adds dispatcher instance to client"""
  498. dispatcher = CommandDispatcher(modules, client, db)
  499. client.dispatcher = dispatcher
  500. modules.check_security = dispatcher.check_security
  501. client.add_event_handler(
  502. dispatcher.handle_incoming,
  503. events.NewMessage,
  504. )
  505. client.add_event_handler(
  506. dispatcher.handle_incoming,
  507. events.ChatAction,
  508. )
  509. client.add_event_handler(
  510. dispatcher.handle_command,
  511. events.NewMessage(forwards=False),
  512. )
  513. client.add_event_handler(
  514. dispatcher.handle_command,
  515. events.MessageEdited(),
  516. )
  517. async def amain(self, first: bool, client: CustomTelegramClient):
  518. """Entrypoint for async init, run once for each user"""
  519. client.parse_mode = "HTML"
  520. await client.start()
  521. db = database.Database(client)
  522. await db.init()
  523. logging.debug("Got DB")
  524. logging.debug("Loading logging config...")
  525. translator = Translator(client, db)
  526. await translator.init()
  527. modules = loader.Modules(client, db, self.clients, translator)
  528. client.loader = modules
  529. if self.web:
  530. await self.web.add_loader(client, modules, db)
  531. await self.web.start_if_ready(
  532. len(self.clients),
  533. self.arguments.port,
  534. )
  535. await self._add_dispatcher(client, modules, db)
  536. await modules.register_all(None)
  537. modules.send_config()
  538. await modules.send_ready()
  539. if first:
  540. await self._badge(client)
  541. await client.run_until_disconnected()
  542. def main(self):
  543. """Main entrypoint"""
  544. self._init_web()
  545. save_config_key("port", self.arguments.port)
  546. self._get_token()
  547. if (
  548. not self.clients # Search for already inited clients
  549. and not self.sessions # Search for already added sessions
  550. or not self._init_clients() # Attempt to read sessions from env
  551. ) and not self._initial_setup(): # Otherwise attempt to run setup
  552. return
  553. self.loop.set_exception_handler(
  554. lambda _, x: logging.error(
  555. "Exception on event loop! %s",
  556. x["message"],
  557. exc_info=x.get("exception", None),
  558. )
  559. )
  560. self._init_loop()
  561. telethon.extensions.html.CUSTOM_EMOJIS = not get_config_key("disable_custom_emojis")
  562. hikka = Hikka()