main.py 22 KB

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