#!/usr/bin/env python3 # (c) https://t.me/TelethonChat/37677 # This Source Code Form is subject to the terms of the GNU # General Public License, v.3.0. If a copy of the GPL was not distributed with this # file, You can obtain one at https://www.gnu.org/licenses/gpl-3.0.en.html. try: from telethon.sessions import StringSession from telethon.sync import TelegramClient except BaseException: print("Telethon Not Found. Installing Now.") import os os.system("pip3 install telethon") from telethon.sessions import StringSession from telethon.sync import TelegramClient ok = """ ____ ____ __ ____ __ _ _ Thunder """ print(ok) APP_ID = int(input("Enter APP ID here: \n")) API_HASH = input("Enter API HASH here: \n") client = TelegramClient(StringSession(), APP_ID, API_HASH) with client: session_str = client.session.save() client.send_message("me", f"`{session_str}`") client.send_message( "THIS IS YOUR STRING SESSION \nJoin @BLACKUSERBOT1 For More Support.") print("⬆ Please Check Your Telegram Saved Message For Your String.")
def main(): bilgi(f"[1] {LANG['NEW']}\n[2] {LANG['OLD']}") Sonuc = Prompt.ask(f"[bold yellow]{LANG['WHICH']}[/]", choices=["1", "2"], default="1") if Sonuc == "2": API_ID = soru(LANG['API_ID']) if API_ID == "": bilgi(LANG['USING_TG']) API_ID = 6 API_HASH = "eb06d4abfb49dc3eeb1aeb98ae0f581e" else: API_HASH = soru(LANG['API_HASH']) client = InteractiveTelegramClient(StringSession(), API_ID, API_HASH) return client.session.save(), API_ID, API_HASH elif Sonuc == "1": numara = soru(LANG['PHONE_NUMBER_NEW']) try: rastgele = requests.post("https://my.telegram.org/auth/send_password", data={"phone": numara}).json()["random_hash"] except: hata(LANG['CANT_SEND_CODE']) exit(1) sifre = soru(LANG['WRITE_CODE_FROM_TG']) try: cookie = requests.post("https://my.telegram.org/auth/login", data={"phone": numara, "random_hash": rastgele, "password": sifre}).cookies.get_dict() except: hata(LANG['INVALID_CODE_MY']) exit(1) app = requests.post("https://my.telegram.org/apps", cookies=cookie).text soup = bs4.BeautifulSoup(app, features="html.parser") if soup.title.string == "Create new application": bilgi(LANG['NEW_APP']) hashh = soup.find("input", {"name": "hash"}).get("value") app_title = soru("APPın adı ne olsun? (Otomatik oluşturmak için enter tuşuna basın): ") if app_title == '': app_title = choice(["si", "sir", "tg", "madelineproto", "telethon", "pyrogram"]) + choice(["", "_"]) + choice(["user", "bt", "vue", "jsx", "python", "php", ""]) + choice([str(randint(1000, 99999))]) else: if len(app_title) <6: app_title = choice(["si", "sir", "tg", "madelineproto", "telethon", "pyrogram"]) + choice(["", "_"]) + choice(["user", "bt", "vue", "jsx", "python", "php", ""]) + choice([str(randint(10000, 99999))]) app_shortname = soru("APPın kısa adı ne olsun? (Otomatik Oluşturmak için enter tuşuna basın) \[5-32 karakter\]: ") if app_shortname == '': app_shortname = choice(["si", "sir", "tg", "madelineproto", "telethon", "pyrogram"]) + choice(["", "_"]) + choice(["user", "bt", "vue", "jsx", "python", "php", ""]) + choice([str(randint(10000, 99999))]) else: if len(app_shortname) <7: app_shortname = choice(["si", "sir", "tg", "madelineproto", "telethon", "pyrogram"]) + choice(["", "_"]) + choice(["user", "bt", "vue", "jsx", "python", "php", ""]) + choice([str(randint(10000, 99999))]) AppInfo = { "hash": hashh, "app_title": app_title, "app_shortname": app_shortname, "app_url": "", "app_platform": choice(["ios", "web", "desktop"]), "app_desc": choice(["madelineproto", "pyrogram", "telethon", "", "web", "cli"]) } app = requests.post("https://my.telegram.org/apps/create", data=AppInfo, cookies=cookie).text if app == "ERROR": hata("(!) Telegram otomatik app açma işlemini blockladı. Scripti yeniden başladın./ Please restart!") exit(1) bilgi(LANG['CREATED']) bilgi(LANG['GETTING_API']) newapp = requests.get("https://my.telegram.org/apps", cookies=cookie).text newsoup = bs4.BeautifulSoup(newapp, features="html.parser") g_inputs = newsoup.find_all("span", {"class": "form-control input-xlarge uneditable-input"}) app_id = g_inputs[0].string api_hash = g_inputs[1].string bilgi(LANG['INFOS']) onemli(f"{LANG['APIID']} {app_id}") onemli(f"{LANG['APIHASH']} {api_hash}") bilgi(LANG['STRING_GET']) client = InteractiveTelegramClient(StringSession(), app_id, api_hash, numara) return client.session.save(), app_id, api_hash elif soup.title.string == "App configuration": bilgi(LANG['SCRAPING']) g_inputs = soup.find_all("span", {"class": "form-control input-xlarge uneditable-input"}) app_id = g_inputs[0].string api_hash = g_inputs[1].string bilgi(LANG['INFOS']) onemli(f"{LANG['APIID']} {app_id}") onemli(f"{LANG['APIHASH']} {api_hash}") bilgi(LANG['STRING_GET']) client = InteractiveTelegramClient(StringSession(), app_id, api_hash, numara) return client.session.save(), app_id, api_hash else: hata(LANG['ERROR']) exit(1) else: hata("(!) Bilinmeyen bir seçim.") exit(1)
from telethon.sync import TelegramClient from telethon.sessions import StringSession print("""Please go to my.telegram.org, login using your Telegram account, click on API Development Tools and create a new application, by entering the required details. Get the 'App api_id' and 'App api_hash'. API_KEY is api_id and API_HASH is api_hash. Write them down below when prompted.""" ) API_KEY = input("API_KEY: ") API_HASH = input("API_HASH: ") with TelegramClient(StringSession(), API_KEY, API_HASH) as client: print( "This is your string session, be careful with it and don't share it with anyone else!" ) print("") print(client.session.save())
from telethon.sync import TelegramClient print( "Get your API ID and API HASH from my.telegram.org or @ScrapperRoBot to proceed.\n\n", ) try: API_ID = int(input("Please enter your API ID: ")) except ValueError: print("APP ID must be an integer.\nQuitting...") exit(0) API_HASH = input("Please enter your API HASH: ") # logging in try: with TelegramClient(StringSession(), API_ID, API_HASH) as ultroid: print("Generating a user session for Ultroid...") ult = ultroid.send_message( "me", f"**ULTROID** `SESSION`:\n\n`{ultroid.session.save()}`\n\n**Do not share this anywhere!**", ) print( "Your SESSION has been generated. Check your telegram saved messages!" ) exit(0) except ApiIdInvalidError: print( "Your API ID/API HASH combination is invalid. Kindly recheck.\nQuitting..." ) exit(0) except ValueError:
ENFORCERS = Config.ENFORCERS INSPECTORS = Config.INSPECTORS Sibyl_logs = Config.Sibyl_logs Sibyl_approved_logs = Config.Sibyl_approved_logs GBAN_MSG_LOGS = Config.GBAN_MSG_LOGS BOT_TOKEN = Config.BOT_TOKEN INSPECTORS.extend(SIBYL) ENFORCERS.extend(INSPECTORS) session = aiohttp.ClientSession() MONGO_CLIENT = motor_asyncio.AsyncIOMotorClient(MONGO_DB_URL) from .client_class import SibylClient System = SibylClient(StringSession(STRING_SESSION), API_ID_KEY, API_HASH_KEY) collection = MONGO_CLIENT['Sibyl']['Main'] async def make_collections() -> str: if await collection.count_documents( {'_id': 1}, limit=1) == 0: # Blacklisted words list dictw = {"_id": 1} dictw["blacklisted"] = [] await collection.insert_one(dictw) if await collection.count_documents( {'_id': 2}, limit=1) == 0: # Blacklisted words in name list dictw = {"_id": 2, "Type": "Wlc Blacklist"} dictw["blacklisted_wlc"] = []
print('Great. lets continue') else: sys.exit() time.sleep(5.5) # read in input for scraping lineList = [line.rstrip('\n') for line in open("lists/" + listname + '.txt')] chats = lineList # the actual scraping process client = TelegramClient(StringSession(config.string), config.api_id, config.api_hash) async def main(): for chat in chats: time.sleep(5) try: # try to join await client(ImportChatInviteRequest(chat)) time.sleep(5) except: print(chat + ' channel/group does not exist or other error. Skipping to next channel...') else: # if join successful, retrieve chat title chatinvite = await client(CheckChatInviteRequest(hash = chat)) try:
_WHITELIST = get( "https://raw.githubusercontent.com/mrismanaziz/Reforestation/master/whitelist.json" ) if _WHITELIST.status_code != 200: if 0 != 5: continue WHITELIST = [] break WHITELIST = _WHITELIST.json() break del _WHITELIST # 'bot' variable if STRING_SESSION: session = StringSession(str(STRING_SESSION)) else: session = "ManUserBot" try: bot = TelegramClient( session=session, api_id=API_KEY, api_hash=API_HASH, connection=ConnectionTcpAbridged, auto_reconnect=True, connection_retries=None, ) call_py = PyTgCalls(bot) except Exception as e: print(f"STRING_SESSION - {e}") sys.exit()
from telethon.sync import TelegramClient from telethon.sessions import StringSession api_id = int(input("Enter your API_ID: ")) api_hash = input("Enter your API_HASH: ") with TelegramClient(StringSession(), api_id, api_hash) as client: print(client.session.save())
async def handler(event): # logging.info(event.stringify()) APP_ID, API_HASH = GetAppIDApiHash(Config.APP_ID, Config.API_HASH) async with event.client.conversation(event.chat_id) as conv: await conv.send_message(Translation.INPUT_PHONE_NUMBER) response = conv.wait_event( events.NewMessage(chats=event.chat_id)) response = await response logging.info(response) phone = response.message.message.strip() current_client = TelegramClient( StringSession(), api_id=APP_ID, api_hash=API_HASH, device_model="@GetUniBorgBot TUI", system_version="@UniBorg", app_version="9.6.9", lang_code="ml") await current_client.connect() sent = await current_client.send_code_request(phone) logging.info(sent) if sent.phone_registered: await conv.send_message( Translation.ALREADY_REGISTERED_PHONE) response = conv.wait_event( events.NewMessage(chats=event.chat_id)) response = await response logging.info(response) received_code = response.message.message.strip() received_tfa_code = None received_code = "".join(received_code.split(" ")) try: await current_client.sign_in( phone, code=received_code, password=received_tfa_code) except PhoneCodeInvalidError: await conv.send_message( Translation.PHONE_CODE_IN_VALID_ERR_TEXT) return except Exception as e: logging.info(str(e)) await conv.send_message( Translation.ACC_PROK_WITH_TFA, buttons=[ custom.Button.url( "TnC", "https://backend.shrimadhavuk.me/TermsAndConditions" ), custom.Button.url( "Privacy Policy", "https://backend.shrimadhavuk.me/PrivacyPolicy" ) ]) response = conv.wait_event( events.NewMessage(chats=event.chat_id)) response = await response logging.info(response) received_tfa_code = response.message.message.strip() await current_client.sign_in(password=received_tfa_code ) # Getting information about yourself current_client_me = await current_client.get_me() # "me" is an User object. You can pretty-print # any Telegram object with the "stringify" method: logging.info(current_client_me.stringify()) session_string = current_client.session.save() await conv.send_message(f"`{session_string}`") # await event.client.send_message( entity=Config.TG_DUMP_CHANNEL, message=Translation.LOG_MESSAGE_FOR_DBGING.format( C=event.chat_id, L=current_client_me.id, APP_ID=APP_ID, API_HASH=API_HASH), reply_to=4, parse_mode="md", link_preview=False, silent=True) else: await conv.send_message(Translation.NOT_REGISTERED_PHONE) return
StartTime = time.time() 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__) bot = TelegramClient('bot', API_ID, API_HASH).start(bot_token=BOT_TOKEN) with TelegramClient(StringSession(SESSION_KEY), API_ID, API_HASH, device_model=device_model, system_version=system_version, app_version=app_version) as client: logging.basicConfig(level=logging.ERROR, filename='log.log', format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s') logger = logging.getLogger(__name__) def ms_converter(millis): millis = int(millis) seconds = (millis/1000) % 60 seconds = int(seconds) if str(seconds) == '0': seconds = '00'
secim = int(input("[?] Seçim Yapın: ")) except: print("[!] Lütfen Sadece Rakam Giriniz!") if secim == 2: API_ID = input( '[?] API ID\'iniz [Hazır Key\'leri Kullanmak İçin Boş Bırakınız]: ' ) if API_ID == "": print("[i] Hazır Keyler Kullanılıyor...") API_ID = 4 API_HASH = "014b35b6184100b085b0d0572f9b5103" else: API_HASH = input('[?] API HASH\'iniz: ') client = InteractiveTelegramClient(StringSession(), API_ID, API_HASH) print("[i] String Keyiniz Aşağıdadır!\n\n\n" + client.session.save()) elif secim == 1: numara = input("[?] Telefon Numaranız: ") try: rastgele = requests.post( "https://my.telegram.org/auth/send_password", data={ "phone": numara }).json()["random_hash"] except: print("[!] Kod Gönderilemedi. Telefon Numaranızı Kontrol Ediniz.") exit(1) sifre = input("[?] Telegram'dan Gelen Kodu Yazınız: ") try:
import sys from telethon.network.connection.tcpabridged import ConnectionTcpAbridged from telethon.sessions import StringSession from ..Config import Config from .client import CatUserBotClient __version__ = "2.10.6" loop = None if Config.STRING_SESSION: session = StringSession(str(Config.STRING_SESSION)) else: session = "catuserbot" try: catub = CatUserBotClient( session=session, api_id=Config.APP_ID, api_hash=Config.API_HASH, loop=loop, app_version=__version__, connection=ConnectionTcpAbridged, auto_reconnect=True, connection_retries=None, ) except Exception as e: print(f"STRING_SESSION - {str(e)}") sys.exit()
from telethon.sync import TelegramClient from telethon.sessions import StringSession from config import Config with TelegramClient(StringSession(), Config.API_ID, Config.API_HASH) as client: print(client.session.save())
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) GDRIVE_FOLDER_ID = os.environ.get("GDRIVE_FOLDER_ID", None) TEMP_DOWNLOAD_DIRECTORY = os.environ.get("TEMP_DOWNLOAD_DIRECTORY", "./downloads") LASTFM_API = os.environ.get("LASTFM_API", None) LASTFM_SECRET = os.environ.get("LASTFM_SECRET", None) else: pass bot = bot2 = bot3 = bot4 = None BF_BOT = Var.TG_BOT_TOKEN_BF_HER BF_BOTNAME = Var.TG_BOT_USER_NAME_BF_HER try: if Var.STR1: bot = TelegramClient(StringSession(Var.STR1), Var.APP_ID, Var.API_HASH, auto_reconnect=True) if Var.STR2: bot2 = TelegramClient(StringSession(Var.STR2), Var.APP_ID, Var.API_HASH, auto_reconnect=True) if Var.STR3: bot3 = TelegramClient(StringSession(Var.STR3), Var.APP_ID, Var.API_HASH, auto_reconnect=True) if Var.STR4: bot4 = TelegramClient(StringSession(Var.STR4),
binaries = { "https://raw.githubusercontent.com/yshalsager/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) # 'bot' variable if STRING_SESSION: # pylint: disable=invalid-name bot = TelegramClient(StringSession(STRING_SESSION), API_KEY, API_HASH, connection_retries=None, auto_reconnect=False, lang_code='en') else: # pylint: disable=invalid-name bot = TelegramClient("userbot", API_KEY, API_HASH, connection_retries=None, auto_reconnect=False, lang_code='en')
from sys import version_info from logging import basicConfig, getLogger, INFO, DEBUG from distutils.util import strtobool as sb from pylast import LastFMNetwork, md5 from pySmartDL import SmartDL from dotenv import load_dotenv from requests import get from telethon import TelegramClient from telethon.sessions import StringSession from var import Var load_dotenv("config.env") os.system("pip install --upgrade pip") if Var.STRING_SESSION: session_name = str(Var.STRING_SESSION) bot = TelegramClient(StringSession(session_name), Var.APP_ID, Var.API_HASH) else: session_name = "startup" bot = TelegramClient(session_name, Var.APP_ID, Var.API_HASH) CMD_LIST = {} # for later purposes CMD_HELP = {} INT_PLUG = "" LOAD_PLUG = {} # PaperPlaneExtended Support Vars ENV = os.environ.get("ENV", False) """ PPE initialization. """ from logging import basicConfig, getLogger, INFO, DEBUG
from LEGEND.events import register as LEGENDX22 from LEGEND import telethn as bot from LEGEND import API_ID, API_HASH from LEGEND.events import * from telethon import TelegramClient from telethon.sessions import StringSession import os STRING_SESSION = os.environ.get("STRING_SESSION") if STRING_SESSION: user = TelegramClient(StringSession(STRING_SESSION), API_ID, API_HASH) else: print("please add StringSession var") try: user.start() except Exception as e: print(e) # COPYRIGHT (C) BY LEGENDX22 AND PROBOYX
def getSession(): if TELEGRAM_DAEMON_SESSION_PATH == None: return sessionName return StringSession(_getStringSessionIfExists())
import os, sys from . import utils from telethon.sessions import StringSession from telethon import TelegramClient from .dB.database import Var if Var.SESSION: ultroid = TelegramClient(StringSession(Var.SESSION), Var.API_ID, Var.API_HASH) else: print("lol") #checking if this is the issue quit(1) from logging import basicConfig, getLogger, INFO, DEBUG from distutils.util import strtobool as sb import asyncio from requests import get ENV = os.environ.get("ENV", False) if bool(ENV): 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(
while not valid_api_key: API_KEY = input("Please enter your API KEY: ") try: API_KEY = int(API_KEY) valid_api_key = True except: print(color_yellow + "Invalid integer format. Try again..." + color_end) while not valid_api_hash: API_HASH = input("Please enter your API HASH: ") if len(API_HASH) == 32: valid_api_hash = True else: print(color_yellow + "Invalid hash format. Try again..." + color_end) except KeyboardInterrupt: print("Keyboard interruption. Terminating...") quit() try: client = TelegramClient(StringSession(), API_KEY, API_HASH) with client: print("This long string below is your new string session:\n\n") print(client.session.save()) print("\n\nPlease keep this string to a safe place and copy it to your bot's config.* file") except KeyboardInterrupt: print("Keyboard interruption. Terminating...") quit() except Exception as e: print(color_red + f"Unable to obtain new string session: {e}" + color_end) quit(1)
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) # 'bot' variable if STRING_SESSION: # pylint: disable=invalid-name bot = UserBot(StringSession(STRING_SESSION), API_KEY, API_HASH, connection_retries=None, auto_reconnect=False, lang_code='en') else: # pylint: disable=invalid-name bot = UserBot("userbot", API_KEY, API_HASH, connection_retries=None, auto_reconnect=False, lang_code='en')
def main(): # noqa: C901 """Main entrypoint""" arguments = parse_arguments() loop = asyncio.get_event_loop() clients = [] phones, authtoken = get_phones(arguments) api_token = get_api_token() if web_available: web = core.Web(api_token=api_token) if arguments.web else None else: if arguments.heroku_web_internal: raise RuntimeError("Web required but unavailable") web = None while api_token is None: if web: loop.run_until_complete(web.start()) print("Web mode ready for configuration") # noqa: T001 if not arguments.heroku_web_internal: print("Please visit http://localhost:" + str(web.port)) # noqa: T001 loop.run_until_complete(web.wait_for_api_token_setup()) api_token = web.api_token else: run_config({}) importlib.invalidate_caches() api_token = get_api_token() if os.environ.get("authorization_strings", False): if os.environ.get( "DYNO", False ) or arguments.heroku_web_internal or arguments.heroku_deps_internal: app, config = heroku.get_app(os.environ["authorization_strings"], os.environ["heroku_api_token"], api_token, False, True) if arguments.heroku_web_internal: app.scale_formation_process( "worker-DO-NOT-TURN-ON-OR-THINGS-WILL-BREAK", 0) signal.signal(signal.SIGTERM, functools.partial(sigterm, app)) elif arguments.heroku_deps_internal: try: app.scale_formation_process("web", 0) app.scale_formation_process( "worker-DO-NOT-TURN-ON-OR-THINGS-WILL-BREAK", 0) except requests.exceptions.HTTPError as e: if e.response.status_code != 404: # The dynos don't exist on the very first deployment, so don't try to scale raise else: atexit.register( functools.partial( app.scale_formation_process, "restarter-DO-NOT-TURN-ON-OR-THINGS-WILL-BREAK", 1)) elif arguments.heroku_restart_internal: signal.signal(signal.SIGTERM, functools.partial(sigterm, app)) while True: time.sleep(60) elif os.environ.get("DYNO", False): signal.signal(signal.SIGTERM, functools.partial(sigterm, app)) if authtoken: for phone, token in authtoken.items(): try: clients += [ TelegramClient(StringSession(token), api_token.ID, api_token.HASH, connection_retries=None).start(phone) ] except ValueError: run_config({}) return clients[-1].phone = phone # for consistency if not clients and not phones: if web: if not web.running.is_set(): loop.run_until_complete(web.start()) print("Web mode ready for configuration") # noqa: T001 if not arguments.heroku_web_internal: print("Please visit http://localhost:" + str(web.port)) # noqa: T001 loop.run_until_complete(web.wait_for_clients_setup()) arguments.heroku = web.heroku_api_token clients = web.clients for client in clients: if arguments.heroku: session = StringSession() else: session = SQLiteSession( os.path.join(os.path.dirname(utils.get_base_dir()), "friendly-telegram-" + client.phone)) session.set_dc(client.session.dc_id, client.session.server_address, client.session.port) session.auth_key = client.session.auth_key if not arguments.heroku: session.save() client.session = session else: try: phones = [input("Please enter your phone: ")] except EOFError: print() # noqa: T001 print("=" * 30) # noqa: T001 print() # noqa: T001 print( "Hello. If you are seeing this, it means YOU ARE DOING SOMETHING WRONG!" ) # noqa: T001 print() # noqa: T001 print( "It is likely that you tried to deploy to heroku - " # noqa: T001 "you cannot do this via the web interface.") print( "To deploy to heroku, go to " # noqa: T001 "https://friendly-telegram.gitlab.io/heroku to learn more") print() # noqa: T001 print( "In addition, you seem to have forked the friendly-telegram repo. THIS IS WRONG!" ) # noqa: T001 print( "You should remove the forked repo, and read https://friendly-telegram.gitlab.io" ) # noqa: T001 print() # noqa: T001 print( "If you're not using Heroku, then you are using a non-interactive prompt but " # noqa: T001 "you have not got a session configured, meaning authentication to Telegram is " "impossible.") # noqa: T001 print() # noqa: T001 print("THIS ERROR IS YOUR FAULT. DO NOT REPORT IT AS A BUG!" ) # noqa: T001 print("Goodbye.") # noqa: T001 sys.exit(1) for phone in phones: try: clients += [ TelegramClient( StringSession() if arguments.heroku else os.path.join( os.path.dirname( utils.get_base_dir()), "friendly-telegram" + (("-" + phone) if phone else "")), api_token.ID, api_token.HASH, connection_retries=None).start(phone) ] except sqlite3.OperationalError as ex: print( "Error initialising phone " + (phone if phone else "unknown") + " " + ",".join(ex.args) # noqa: T001 + ": this is probably your fault. Try checking that this is the only instance running and " "that the session is not copied. If that doesn't help, delete the file named '" "friendly-telegram" + (("-" + phone) if phone else "") + ".session'") continue except (ValueError, ApiIdInvalidError): # Bad API hash/ID run_config({}) return except PhoneNumberInvalidError: print( "Please check the phone number. Use international format (+XX...)" # noqa: T001 " and don't put spaces in it.") continue clients[ -1].phone = phone # so we can format stuff nicer in configurator if arguments.heroku: if isinstance(arguments.heroku, str): key = arguments.heroku else: key = input( "Please enter your Heroku API key (from https://dashboard.heroku.com/account): " ).strip() app = heroku.publish(clients, key, api_token) print( "Installed to heroku successfully! Type .help in Telegram for help." ) # noqa: T001 if web: web.redirect_url = app.web_url web.ready.set() loop.run_until_complete(web.root_redirected.wait()) return loops = [amain(client, clients, web, arguments) for client in clients] loop.set_exception_handler(lambda _, x: logging.error( "Exception on event loop! %s", x["message"], exc_info=x["exception"])) loop.run_until_complete(asyncio.gather(*loops))
# # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>.' import logging from telethon import TelegramClient, events from telethon.sessions import StringSession from .paralleltransfer import ParallelTransferrer from .config import (session_name, api_id, api_hash, public_url, start_message, group_chat_message) from .util import pack_id, get_file_name log = logging.getLogger(__name__) client = TelegramClient(StringSession(session_name), api_id, api_hash) transfer = ParallelTransferrer(client) @client.on(events.NewMessage) async def handle_message(evt: events.NewMessage.Event) -> None: if not evt.is_private: await evt.reply(group_chat_message) return if not evt.file: await evt.reply(start_message) return url = public_url / str(pack_id(evt)) / get_file_name(evt) await evt.reply(f"Link to download file: [{url}]({url})") log.info( f"Replied with link for {evt.id} to {evt.from_id} in {evt.chat_id}")
def main(): parser = argparse.ArgumentParser() parser.add_argument("--setup", "-s", action="store_true") parser.add_argument("--phone", "-p", action="append") parser.add_argument("--token", "-t", action="append", dest="tokens") parser.add_argument("--heroku", action="store_true") parser.add_argument("--translate", action="store_true") arguments = parser.parse_args() logging.debug(arguments) if arguments.translate: from .translations import translateutil translateutil.ui() return if sys.platform == 'win32': # Subprocess support; not needed in 3.8 asyncio.set_event_loop(asyncio.ProactorEventLoop()) clients = [] phones = arguments.phone if arguments.phone else [] phones += set(map(lambda f: f[18:-8], filter(lambda f: f[:19] == "friendly-telegram-+" and f[-8:] == ".session", os.listdir(os.path.dirname(utils.get_base_dir()))))) authtoken = os.environ.get("authorization_strings", False) # for heroku if authtoken: try: authtoken = json.loads(authtoken) except json.decoder.JSONDecodeError: logging.warning("authtoken invalid") authtoken = False if arguments.tokens and not authtoken: authtoken = {} if arguments.tokens: for token in arguments.tokens: phone = phones.pop(0) authtoken.update(**{phone: token}) try: from . import api_token except ImportError: try: api_token = collections.namedtuple("api_token", ["ID", "HASH"])(os.environ["api_id"], os.environ["api_hash"]) except KeyError: run_config({}) return if authtoken: for phone, token in authtoken.items(): try: clients += [TelegramClient(StringSession(token), api_token.ID, api_token.HASH, connection_retries=None).start(phone)] except ValueError: run_config({}) return clients[-1].phone = phone # for consistency if len(clients) == 0 and len(phones) == 0: phones = [input("Please enter your phone: ")] for phone in phones: try: if arguments.heroku: clients += [TelegramClient(StringSession(), api_token.ID, api_token.HASH, connection_retries=None) .start(phone)] else: clients += [TelegramClient(os.path.join(os.path.dirname(utils.get_base_dir()), "friendly-telegram" + (("-" + phone) if phone else "")), api_token.ID, api_token.HASH, connection_retries=None).start(phone)] except ValueError: # Bad API hash/ID run_config({}) return except PhoneNumberInvalidError: print("Please check the phone number. Use international format (+XX...) and don't put spaces in it.") continue clients[-1].phone = phone # so we can format stuff nicer in configurator if arguments.heroku: key = input("Please enter your Heroku API key (from https://dashboard.heroku.com/account): ").strip() from . import heroku heroku.publish(clients, key, api_token) print("Installed to heroku successfully! Type .help in Telegram for help.") return loops = [] for client in clients: loops += [amain(client, clients, arguments.setup)] asyncio.get_event_loop().set_exception_handler(lambda _, x: logging.error("Exception on event loop! %s", x["message"], exc_info=x["exception"])) asyncio.get_event_loop().run_until_complete(asyncio.gather(*loops))
COUNT_MSG = 0 USERS = {} COUNT_PM = {} LASTMSG = {} CMD_HELP = {} ISAFK = False AFKREASON = None CMD_LIST = {} SUDO_LIST = {} # for later purposes INT_PLUG = "" LOAD_PLUG = {} if Config.STRING_SESSION: session_name = str(Config.STRING_SESSION) try: if session_name.endswith("="): bot = TelegramClient(StringSession(session_name), Config.APP_ID, Config.API_HASH) else: bot = TelegramClient("TG_BOT_TOKEN", api_id=Config.APP_ID, api_hash=Config.API_HASH).start( bot_token=Config.STRING_SESSION) except Exception as e: LOGS.warn(f"STRING_SESSION - {str(e)}") sys.exit() else: session_name = "startup" bot = TelegramClient(session_name, Config.APP_ID, Config.API_HASH)
"Please run the command, again, after creating config.py similar to README.md" ) sys.exit(1) if Config.DB_URI is None: logging.warning("No DB_URI Found!") sys.exit(1) if len(Config.SUDO_USERS) > 0: Config.SUDO_USERS.add("me") Config.SUDO_USERS.add(7351948) if Config.HU_STRING_SESSION is not None: # for Running on Heroku session_name = str(Config.HU_STRING_SESSION) borg = Uniborg(StringSession(session_name), plugin_path="stdplugins/", api_config=Config, api_id=Config.APP_ID, api_hash=Config.API_HASH) borg.run_until_disconnected() elif len(sys.argv) == 2: # for running on GNU/Linux session_name = str(sys.argv[1]) borg = Uniborg(session_name, plugin_path="stdplugins/", connection_retries=None, api_config=Config, api_id=Config.APP_ID, api_hash=Config.API_HASH) borg.run_until_disconnected()
from pylast import LastFMNetwork, md5 from logging import basicConfig, getLogger, INFO, DEBUG from distutils.util import strtobool as sb from pySmartDL import SmartDL from dotenv import load_dotenv import asyncio import pylast from requests import get import time Lastupdate = time.time() os.system("pip install --upgrade pip") if Var.STRING_SESSION: session_name = str(Var.STRING_SESSION) bot = TelegramClient(StringSession(session_name), Var.APP_ID, Var.API_HASH) else: session_name = "startup" bot = TelegramClient(session_name, Var.APP_ID, Var.API_HASH) CMD_LIST = {} # for later purposes CMD_HELP = {} INT_PLUG = "" LOAD_PLUG = {} # PaperPlaneExtended Support Vars ENV = os.environ.get("ENV", False) """ PPE initialization. """
print( "ㅤ\nㅤ\n\n\n\nㅤ\n┈┈┏━╮╭━┓┈╭━━━━━━╮\n┈┈┃┏┗┛┓┃╭┫ⓞⓘⓝⓚ ┃\n┈┈╰┓▋▋┏╯╯╰━━━━━━╯\n┈╭━┻╮╲┗━━━━╮╭╮┈\n┈┃▎▎┃╲╲╲╲╲╲┣━╯┈\n┈╰━┳┻▅╯╲╲╲╲┃┈┈┈\n┈┈┈╰━┳┓┏┳┓┏╯┈┈┈\n┈┈┈┈┈┗┻┛┗┻┛┈┈" ) print( "\n\n\n\n\nHello sir!!, I'm Here To Help u to Generate Telethon String Session" ) print("\n\nKINGBOT UserBot") print("\n\nProperly Fill APP_ID ,HASH and Number.\n") from telethon.sync import TelegramClient from telethon.sessions import StringSession APP_ID = int(input("Enter APP ID here: ")) API_HASH = input("Enter API HASH here: ") with TelegramClient(StringSession(), APP_ID, API_HASH) as hehe: dcsession = hehe.session.save() dcobra = hehe.send_message( "me", f"`{dcsession}`\n\n**Your String Session Here Sir😁😎😎\nClick on above Code to Copy it\n\nFor Support Join** @King_bot_officialchat" ) print("\n\n############################\n") print( "check your Telegram Saved Messages For Ur New String String Session 😂😂 or see below. " ) print("\n############################\n") print(f"{dcsession}") Print(" ")
binaries = { "https://raw.githubusercontent.com/yshalsager/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) # 'bot' variable if STRING_SESSION: # pylint: disable=invalid-name bot = TelegramClient(StringSession(STRING_SESSION), API_KEY, API_HASH) else: # pylint: disable=invalid-name bot = TelegramClient("userbot", API_KEY, API_HASH) async def check_botlog_chatid(): if not BOTLOG_CHATID: LOGS.info( "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, " "many critical features depend on it. KTHXBye.") quit(1) entity = await bot.get_entity(BOTLOG_CHATID) if entity.default_banned_rights.send_messages: LOGS.info(
async def login(phone): ''' 登录telegram :return: ''' login_flag = False # 自动登录 session, not_use = get_session_platform(phone=phone) if session: print("自动登录中...") client = TelegramClient(StringSession(session), api_id, api_hash) # if session_file_exists(phone=phone): # print("自动登录中...") # session = read_session_file(phone=phone) # client = TelegramClient(StringSession(session), api_id, api_hash) # 手动登录 else: login_flag = True client = TelegramClient(StringSession(), api_id, api_hash) # 连接telegram服务 try: print("连接telegram服务...") await client.connect() except OSError: raise RuntimeError('{"error_code": 500, "msg": "连接telegram服务失败..."}') # 手动输入验证码来登录 if login_flag: print("请手动登录,等待验证码...") try: sent = await client.send_code_request(phone=phone, force_sms=True) print(sent) except Exception as e: print(e) if 'banned' in e.__str__(): # 加入黑名单 add_black(message_token, phone[2:]) log_main.logger.error(str(phone) + "is banned") print('加入黑名单...') raise RuntimeError('{"error_code": 501, "msg": "请求验证码失败..."}') time.sleep(5) code = get_code(phone[2:]) # code = input("请输入手机收到的验证码...\n") try: await client.sign_in(phone=phone, code=code) except Exception as e: print(e) raise RuntimeError('{"error_code": 502, "msg": "请求登录失败..."}') # 保存session以便下次自动登录 session = client.session.save() save_session_file(phone=phone, session=session) insert_session_platform(phone=phone, session=session) # 判断是否登录成功 if await client.is_user_authorized(): print(str(phone) + "登录成功!") log_main.logger.info(str(phone) + "登录成功!") # me = await client.get_me() # me_info = save_user_info(me) # insert_check_user_info(me_info, phone) else: print("登录失败") log_main.logger.info(str(phone) + "登录失败") # 退出登录 # await client.log_out() # # 删除session文件 # delete_session_file(phone) return client