main.py 22 KB

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