text: # Copyright (C) 2019 The Raphielscape Company LLC.
  #
  # Licensed under the Raphielscape Public License, Version 1.c (the "License");
  # you may not use this file except in compliance with the License.
  #
  """ Userbot initialization. """
  
  import os
  import signal
  from distutils.util import strtobool as sb
  from logging import DEBUG, INFO, basicConfig, getLogger
  from platform import python_version
  from sys import version_info
  from time import time, sleep
  
  from dotenv import load_dotenv
  from pylast import LastFMNetwork, md5
  from pySmartDL import SmartDL
  from requests import get
  from telethon import TelegramClient, version
  from telethon.network.connection.tcpabridged import ConnectionTcpAbridged
  from telethon.sessions import StringSession
  
  load_dotenv("config.env")
  ubotStart = time()
  
  # Bot Logs setup:
  CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False"))
  
  if CONSOLE_LOGGER_VERBOSE:
      basicConfig(
          format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
          level=DEBUG,
      )
  else:
      basicConfig(
          format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=INFO
      )
  LOGS = getLogger(__name__)
  
  if version_info[0] < 3 or version_info[1] < 8:
      LOGS.info(
          "You MUST have a python version of at least 3.8."
          "Multiple features depend on this. Bot quitting."
      )
      quit(1)
  
  # Check if the config was edited by using the already used variable.
  # Basically, its the 'virginity check' for the config file ;)
  CONFIG_CHECK = os.environ.get(
      "___________PLOX_______REMOVE_____THIS_____LINE__________", None
  )
  
  if CONFIG_CHECK:
      LOGS.info(
          "Please remove the line mentioned in the first hashtag from the config.env file"
      )
      quit(1)
  
  # Telegram App KEY and HASH
  API_KEY = os.environ.get("API_KEY", None)
  API_HASH = os.environ.get("API_HASH", None)
  
  
  # Userbot Session String
  STRING_SESSION = os.environ.get("STRING_SESSION", None)
  
  # Logging channel/group ID configuration.
  BOTLOG_CHATID = int(os.environ.get("BOTLOG_CHATID", None))
  
  # Userbot logging feature switch.
  BOTLOG = sb(os.environ.get("BOTLOG", "False"))
  LOGSPAMMER = sb(os.environ.get("LOGSPAMMER", "False"))
  
  # Bleep Blop, this is a bot ;)
  PM_AUTO_BAN = sb(os.environ.get("PM_AUTO_BAN", "False"))
  
  # Heroku Credentials for updater.
  HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME", None)
  HEROKU_API_KEY = os.environ.get("HEROKU_API_KEY", None)
  
  # Custom (forked) repo URL for updater.
  UPSTREAM_REPO_URL = os.environ.get(
      "UPSTREAM_REPO_URL", "https://github.com/BianSepang/WeebProject.git"
  )
  # UPSTREAM_REPO_URL branch, the default is master
  UPSTREAM_REPO_BRANCH = os.environ.get("UPSTREAM_REPO_BRANCH", "master")
  
  # Console verbose logging
  CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False"))
  
  # SQL Database URI
  DB_URI = os.environ.get("DATABASE_URL", None)
  
  # OCR API key
  OCR_SPACE_API_KEY = os.environ.get("OCR_SPACE_API_KEY", None)
  
  # Default .alive name anf logo
  ALIVE_NAME = os.environ.get("ALIVE_NAME") or None
  ALIVE_LOGO = (
      os.environ.get("ALIVE_LOGO") or "https://telegra.ph/file/9e888cb1e485adf3a179e.mp4"
  )
  
  # remove.bg API key
  REM_BG_API_KEY = os.environ.get("REM_BG_API_KEY", None)
  
  # Chrome Driver and Headless Google Chrome Binaries
  CHROME_DRIVER = os.environ.get("CHROME_DRIVER") or "/usr/bin/chromedriver"
  GOOGLE_CHROME_BIN = os.environ.get("GOOGLE_CHROME_BIN") or "/usr/bin/google-chrome"
  
  # OpenWeatherMap API Key
  OPEN_WEATHER_MAP_APPID = os.environ.get("OPEN_WEATHER_MAP_APPID", None)
  WEATHER_DEFCITY = os.environ.get("WEATHER_DEFCITY", None)
  
  # Anti Spambot Config
  ANTI_SPAMBOT = sb(os.environ.get("ANTI_SPAMBOT", "False"))
  ANTI_SPAMBOT_SHOUT = sb(os.environ.get("ANTI_SPAMBOT_SHOUT", "False"))
  
  # Default .alive name
  ALIVE_NAME = os.environ.get("ALIVE_NAME", None)
  
  # Time & Date - Country and Time Zone
  COUNTRY = str(os.environ.get("COUNTRY", ""))
  TZ_NUMBER = int(os.environ.get("TZ_NUMBER", 1))
  
  # Clean Welcome
  CLEAN_WELCOME = sb(os.environ.get("CLEAN_WELCOME", "True"))
  
  # Deezload Credentials
  DEEZER_ARL_TOKEN = os.environ.get("DEEZER_ARL_TOKEN", None)
  DEEZER_EMAIL = os.environ.get("DEEZER_EMAIL", None)
  DEEZER_PASSWORD = os.environ.get("DEEZER_PASSWORD", None)
  
  # Last.fm Module
  BIO_PREFIX = os.environ.get("BIO_PREFIX", None)
  DEFAULT_BIO = os.environ.get("DEFAULT_BIO", None)
  
  LASTFM_API = os.environ.get("LASTFM_API", None)
  LASTFM_SECRET = os.environ.get("LASTFM_SECRET", None)
  LASTFM_USERNAME = os.environ.get("LASTFM_USERNAME", None)
  LASTFM_PASSWORD_PLAIN = os.environ.get("LASTFM_PASSWORD", None)
  LASTFM_PASS = md5(LASTFM_PASSWORD_PLAIN)
  
  lastfm = None
  if LASTFM_API and LASTFM_SECRET and LASTFM_USERNAME and LASTFM_PASS:
      try:
          lastfm = LastFMNetwork(
              api_key=LASTFM_API,
              api_secret=LASTFM_SECRET,
              username=LASTFM_USERNAME,
              password_hash=LASTFM_PASS,
          )
      except Exception:
          pass
  
  # Google Drive Module
  G_DRIVE_DATA = os.environ.get("G_DRIVE_DATA", None)
  G_DRIVE_CLIENT_ID = os.environ.get("G_DRIVE_CLIENT_ID", None)
  G_DRIVE_CLIENT_SECRET = os.environ.get("G_DRIVE_CLIENT_SECRET", None)
  G_DRIVE_AUTH_TOKEN_DATA = os.environ.get("G_DRIVE_AUTH_TOKEN_DATA", None)
  G_DRIVE_FOLDER_ID = os.environ.get("G_DRIVE_FOLDER_ID", None)
  G_DRIVE_INDEX_URL = os.environ.get("G_DRIVE_INDEX_URL", None)
  TEMP_DOWNLOAD_DIRECTORY = os.environ.get("TMP_DOWNLOAD_DIRECTORY", "./downloads/")
  
  # Terminal Alias
  TERM_ALIAS = os.environ.get("TERM_ALIAS", None)
  
  # Genius Lyrics API
  GENIUS = os.environ.get("GENIUS_ACCESS_TOKEN", None)
  
  # Uptobox
  USR_TOKEN = os.environ.get("USR_TOKEN_UPTOBOX", None)
  
  
  # Setting Up CloudMail.ru and MEGA.nz extractor binaries,
  # and giving them correct perms to work properly.
  if not os.path.exists("bin"):
      os.mkdir("bin")
  
  binaries = {
      "https://raw.githubusercontent.com/adekmaulana/megadown/master/megadown": "bin/megadown",
      "https://raw.githubusercontent.com/yshalsager/cmrudl.py/master/cmrudl.py": "bin/cmrudl",
  }
  
  for binary, path in binaries.items():
      downloader = SmartDL(binary, path, progress_bar=False)
      downloader.start()
      os.chmod(path, 0o755)
  
  
  def shutdown_bot(signum, frame):
      LOGS.info("Received SIGTERM.")
      bot.disconnect()
      sys.exit(143)
  
  
  signal.signal(signal.SIGTERM, shutdown_bot)
  
  
  def migration_workaround():
      try:
          from userbot.modules.sql_helper.globals import addgvar, delgvar, gvarstatus
      except AttributeError:
          return None
  
      old_ip = gvarstatus("public_ip")
      new_ip = get("https://api.ipify.org").text
  
      if old_ip is None:
          delgvar("public_ip")
          addgvar("public_ip", new_ip)
          return None
  
      if old_ip == new_ip:
          return None
  
      sleep_time = 180
      LOGS.info(
          f"A change in IP address is detected, waiting for {sleep_time / 60} minutes before starting the bot."
      )
      sleep(sleep_time)
      LOGS.info("Starting bot...")
  
      delgvar("public_ip")
      addgvar("public_ip", new_ip)
      return None
  
  
  bot = TelegramClient(
      session=StringSession(STRING_SESSION),
      api_id=API_KEY,
      api_hash=API_HASH,
      connection=ConnectionTcpAbridged,
      auto_reconnect=True,
  )
  
  
  async def check_botlog_chatid():
      if not BOTLOG_CHATID and LOGSPAMMER:
          LOGS.info(
              "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the private error log storage to work."
          )
          quit(1)
  
      elif not BOTLOG_CHATID and BOTLOG:
          LOGS.info(
              "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the userbot logging feature to work."
          )
          quit(1)
  
      elif not BOTLOG or not LOGSPAMMER:
          return
  
      entity = await bot.get_entity(BOTLOG_CHATID)
      if entity.default_banned_rights.send_messages:
          LOGS.info(
              "Your account doesn't have rights to send messages to BOTLOG_CHATID "
              "group. Check if you typed the Chat ID correctly."
          )
          quit(1)
  
  
  with bot:
      try:
          bot.loop.run_until_complete(check_botlog_chatid())
      except BaseException:
          LOGS.info(
              "BOTLOG_CHATID environment variable isn't a "
              "valid entity. Check your environment variables/config.env file."
          )
          quit(1)
  
  
  async def update_restart_msg(chat_id, msg_id):
      DEFAULTUSER = ALIVE_NAME or "Set `ALIVE_NAME` ConfigVar!"
      message = (
          f"**WeebProject is back up and running!**\n\n"
          f"**Telethon :** __{version.__version__}__\n"
          f"**Python :** __{python_version()}__\n"
          f"**User :** __{DEFAULTUSER}__"
      )
      await bot.edit_message(chat_id, msg_id, message)
      return True
  
  
  try:
      from userbot.modules.sql_helper.globals import delgvar, gvarstatus
  
      chat_id, msg_id = gvarstatus("restartstatus").split("\n")
      try:
          with bot:
              bot.loop.run_until_complete(update_restart_msg(int(chat_id), int(msg_id)))
      except BaseException:
          pass
      delgvar("restartstatus")
  except AttributeError:
      pass
  
  # Global Variables
  COUNT_MSG = 0
  USERS = {}
  COUNT_PM = {}
  LASTMSG = {}
  CMD_HELP = {}
  ISAFK = False
  AFKREASON = None
  