def __init__(self, session_name, api_id, api_hash, phone, connection_string): self._phone = phone container = AlchemySessionContainer(connection_string) session = container.new_session(phone) self._client = TelegramClient(session, api_id, api_hash) self._loop = asyncio.get_event_loop()
async def main(): container = AlchemySessionContainer(DATABASE_URL) session = container.new_session('session_name') async with TelegramClient(session, api_id, api_hash) as client: while True: await process_bots(BOT_LIST, ADMIN_LIST, client) logging.info("Sleeping") await asyncio.sleep(15 * 60)
async def prepare(cls): container = AlchemySessionContainer( f'postgresql://{Config.DB_USER}:' f'{Config.DB_PASSWORD}@{Config.DB_HOST}/{Config.DB_DATABASE}', manage_tables=False, ) session = container.new_session(Config.SESSION) cls.client = TelegramClient(session, Config.APP_ID, Config.API_HASH) await cls.client.start() if not await cls.client.is_user_authorized(): print("Not autorized!") exit(-1)
def connect(to): import mautrix_telegram.db.base as base base.Base = declarative_base(cls=base.BaseBase) from mautrix_telegram.db import (Portal, Message, UserPortal, User, RoomState, UserProfile, Contact, Puppet, BotChat, TelegramFile) db_engine = sql.create_engine(to) db_factory = orm.sessionmaker(bind=db_engine) db_session = orm.scoped_session(db_factory) # type: orm.Session base.Base.metadata.bind = db_engine session_container = AlchemySessionContainer(engine=db_engine, session=db_session, table_base=base.Base, table_prefix="telethon_", manage_tables=False) return db_session, { "Version": session_container.Version, "Session": session_container.Session, "Entity": session_container.Entity, "SentFile": session_container.SentFile, "UpdateState": session_container.UpdateState, "Portal": Portal, "Message": Message, "Puppet": Puppet, "User": User, "UserPortal": UserPortal, "RoomState": RoomState, "UserProfile": UserProfile, "Contact": Contact, "BotChat": BotChat, "TelegramFile": TelegramFile, }
def prepare_db(self) -> None: super().prepare_db() init_db(self.db) self.session_container = AlchemySessionContainer( engine=self.db, table_base=Base, session=False, table_prefix="telethon_", manage_tables=False)
def connect(to): from mautrix.util.db import Base from mautrix.client.state_store.sqlalchemy import RoomState, UserProfile from mautrix_telegram.db import (Portal, Message, UserPortal, User, Contact, Puppet, BotChat, TelegramFile) db_engine = sql.create_engine(to) db_factory = orm.sessionmaker(bind=db_engine) db_session: Union[orm.Session, orm.scoped_session] = orm.scoped_session(db_factory) Base.metadata.bind = db_engine new_base = declarative_base() new_base.metadata.bind = db_engine session_container = AlchemySessionContainer(engine=db_engine, session=db_session, table_base=new_base, table_prefix="telethon_", manage_tables=False) return db_session, { "Version": session_container.Version, "Session": session_container.Session, "Entity": session_container.Entity, "SentFile": session_container.SentFile, "UpdateState": session_container.UpdateState, "Portal": Portal, "Message": Message, "Puppet": Puppet, "User": User, "UserPortal": UserPortal, "RoomState": RoomState, "UserProfile": UserProfile, "Contact": Contact, "BotChat": BotChat, "TelegramFile": TelegramFile, }
log_file.write(f"Exception thrown, {type(e)}: {str(e)}\n") frames = inspect.getinnerframes(sys.exc_info()[2]) for frame_info in reversed(frames): f_locals = frame_info[0].f_locals if "__lgw_marker_local__" in f_locals: continue log_file.write(f"File{frame_info[1]}," f"line {frame_info[2]}" f" in {frame_info[3]}\n" f"{ frame_info[4][0]}\n") for k, v in f_locals.items(): log_to_str = str(v).replace("\n", "\\n") log_file.write(f" {k} = {log_to_str}\n") log_file.write("\n") raise return wrapper class CompanionClient(CustomClient, CustomDisconnect): pass container = AlchemySessionContainer(DB_URI) session = container.new_session(SESSION_NAME) client = CompanionClient(session, APP_ID, APP_HASH)
LOG_LEVEL = env.get("LOG_LEVEL", "DEBUG") LOG_FILE = env.get("LOG_PATH", "bot.log") LOG_FORMAT = env.get("LOG_FORMAT", "%(asctime)s %(name)s %(levelname)s %(message)s") COMMAND_PREFIX = env.get("COMMAND_PREFIX", ".") SPAMWATCH_HOST = env.get("SPAMWATCH_HOST", None) SPAMWATCH_API_KEY = env.get("SPAMWATCH_API_KEY", None) # Set up logging _log_level = logging._nameToLevel[LOG_LEVEL] # pylint: disable=protected-access _log_console_handler = logging.StreamHandler(sys.stdout) logging.basicConfig(filename=LOG_FILE, filemode="w", level=_log_level) logging.getLogger().addHandler(_log_console_handler) coloredlogs.install(fmt=LOG_FORMAT, level=_log_level) # Set up SpamWatch if SPAMWATCH_API_KEY: spamwatch = spamwatch.Client(SPAMWATCH_API_KEY, host=SPAMWATCH_HOST) else: spamwatch = None alchemy_engine = sqlalchemy.create_engine(DB_URL, echo=False) # Set up redis # TODO # Create the bot container = AlchemySessionContainer(engine=alchemy_engine) session = container.new_session('hikoki') bot = TelegramClient(session, API_ID, API_HASH)
config.update() if args.generate_registration: config.generate_registration() config.save() print(f"Registration generated and saved to {config.registration_path}") sys.exit(0) logging.config.dictConfig(copy.deepcopy(config["logging"])) log = logging.getLogger("mau.init") # type: logging.Logger log.debug(f"Initializing mautrix-telegram {__version__}") db_engine = sql.create_engine(config["appservice.database"] or "sqlite:///mautrix-telegram.db") Base.metadata.bind = db_engine session_container = AlchemySessionContainer(engine=db_engine, table_base=Base, session=False, table_prefix="telethon_", manage_tables=False) session_container.core_mode = True try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) log.debug("Using uvloop for asyncio") except ImportError: pass loop = asyncio.get_event_loop() # type: asyncio.AbstractEventLoop state_store = SQLStateStore() mebibyte = 1024 ** 2 appserv = AppService(config["homeserver.address"], config["homeserver.domain"],
# constants MONGODB_NAME = "upwork" MONGODB_HOST = os.environ.get("MONGODB_HOST") API_ID = os.environ.get("API_ID") API_HASH = os.environ.get("API_HASH") USERNAME = os.environ.get("USERNAME") CHANNEL_URL = os.environ.get("CHANNEL_URL") # client id for upwork CLIENT_ID = os.environ.get("CLIENT_ID") container = AlchemySessionContainer(os.environ.get('DATABASE_URL')) session = container.new_session('some session id') mongoengine.connect(MONGODB_NAME, host=MONGODB_HOST) class Url(mongoengine.Document): title = mongoengine.StringField() url = mongoengine.StringField() class Item(mongoengine.Document): guid = mongoengine.StringField() title = mongoengine.StringField() description = mongoengine.StringField()
from filter import MessageFilter # Import MessageTransformation from transformation import MessageTransformation # Connect to database from db.database import Database from db.session_db import SessionDatabase database = Database() session_db = SessionDatabase() # Connect to Telegram from alchemysession import AlchemySessionContainer container = AlchemySessionContainer('mysql://{}:{}@{}/{}'.format( DB_user, DB_passwd, DB_host, DB_SESSION_DBNAME)) session = container.new_session(session_name_forwarder) client = TelegramClient(session, api_id, api_hash) @client.on(events.NewMessage) def my_event_handler(event): # Ignore Outgoing Message Updates if (event.out): return is_group = event.is_group is_channel = event.is_channel is_private = event.is_private message = event.message.message
import logging from quart import jsonify from app import API_ID, API_HASH, DB_URL from telethon import TelegramClient from telethon.tl.functions.messages import CreateChatRequest from alchemysession import AlchemySessionContainer container = AlchemySessionContainer(DB_URL) logger = logging.Logger('catch_all') class TelegramService: @staticmethod async def login(phone): try: client = await TelegramService.get_client(phone) request = await client.send_code_request(phone) return jsonify({'token': request.phone_code_hash}), 201 except Exception as e: return TelegramService.handle_error(e) finally: await TelegramService.close(client) @staticmethod async def send_message(phone, text, group_id, code, token): try: client = await TelegramService.get_client(phone) await client.sign_in(phone, code, phone_code_hash=token) if await client.is_user_authorized(): await client.send_message(group_id, text)
if Config.DB_URI is None: logging.warning("No DB_URI Found!") if len(Config.SUDO_USERS) == 0: logging.warning( "'SUDO_USERS' should have atleast one value" ) sys.exit(1) if Config.HU_STRING_SESSION: # for Running on Heroku session_id = str(Config.HU_STRING_SESSION) container = AlchemySessionContainer( engine=Config.DB_URI ) session = container.new_session(session_id) borg = Uniborg( session, n_plugin_path="stdplugins/", db_plugin_path="dbplugins/", api_config=Config, api_id=Config.APP_ID, api_hash=Config.API_HASH ) borg.run_until_disconnected() elif Config.TG_BOT_TOKEN_BF_HER: # user defined 'TG_BOT_TOKEN_BF_HER' # but did not define, 'HU_STRING_SESSION'
from alchemysession import AlchemySessionContainer from config.main import DB_SESSION_DBNAME, DB_host, DB_passwd, DB_user from telethon.tl.functions.messages import ImportChatInviteRequest from telethon.tl.functions.channels import JoinChannelRequest from telethon import TelegramClient, events, sync from config.main import api_id, api_hash, TELETHON_SESSION_ID, API_PORT import telethon import os import logging logging.basicConfig(level=logging.ERROR) # Telegram Imports # Connect to Telegram container = AlchemySessionContainer('mysql://{}:{}@{}/{}'.format( DB_user, DB_passwd, DB_host, DB_SESSION_DBNAME)) session = container.new_session(TELETHON_SESSION_ID) client = TelegramClient(session, api_id, api_hash) # Create Flask application instance app = Flask(__name__) ###################### # Join Private Users # ###################### @app.route('/joinPublicUserEntity') def joinPublicUserEntity(): entity = request.args.get('entity') is_bot = request.args.get('is_bot')
from telethon import TelegramClient, types from telethon.tl.functions.channels import JoinChannelRequest, LeaveChannelRequest from telethon.errors.rpcerrorlist import UserAlreadyParticipantError, UserNotParticipantError from alchemysession import AlchemySessionContainer from asyncpg.exceptions import UniqueViolationError from res.databaser import Postgres import config logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', datefmt='%d-%m-%y %H:%M:%S', filename=config.LOG_FILE, filemode='a') container = AlchemySessionContainer(config.db_URL) session = container.new_session('1') DB = Postgres(dsn=config.db_URL) stuff_lock = asyncio.Lock() client = TelegramClient(session, config.API_ID, config.API_HASH, device_model='Calculator') config.MainChannel.ID = None def post_photo_filter(event): post: types.Message = event.message
async def bleck_megick(event, config_jbo): bot_me = await event.client.get_me() print(bot_me.stringify()) if bot_me.username.lower() == config_jbo.TG_BOT_USER_NAME_BF_HER.lower( ) and int(event.chat_id) == int(config_jbo.SUDO_USERS[0]): # force int for Type checks # 🤣🤣 validations async with event.client.conversation(event.chat_id) as conv: await conv.send_message( "welcome **master**\n" "please send me your Phone Number, to generate " "`HU_STRING_SESSION` \n" "Enter the Phone Number that you want to make awesome, " "powered by @UniBorg") msg2 = await conv.get_response() logging.info(msg2.stringify()) phone = msg2.message.strip() container = AlchemySessionContainer(config_jbo.DB_URI) session_id = str(secrets.randbelow(1000000)) session = container.new_session(session_id) current_client = TelegramClient(session, api_id=config_jbo.APP_ID, api_hash=config_jbo.API_HASH, device_model="GNU/Linux nonUI", app_version="@UniBorg 2.0", lang_code="ml") await current_client.connect() sent = await current_client.send_code_request(phone) logging.info(sent) if not sent: await conv.send_message( "This number is not registered on Telegram. " "Please check your #karma by reading https://t.me/c/1220993104/28753" ) return await conv.send_message( "This number is registered on Telegram. " "Please input the verification code " "that you receive from [Telegram](tg://user?id=777000) " "seperated by space, " "else a `PhoneCodeInvalidError` would be raised.") msg4 = await conv.get_response() received_code = msg4.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("Invalid Code Received. " "Please re /start") return except SessionPasswordNeededError: await conv.send_message( "The entered Telegram Number is protected with 2FA. " "Please enter your second factor authentication code.\n" "__This message " "will only be used for generating your string session, " "and will never be used for any other purposes " "than for which it is asked.__" "\n\n" "The code is available for review at " "https://github.com/SpEcHiDe/UniBorg/raw/master/helper_sign_in.py" ) msg6 = await conv.get_response() received_tfa_code = msg6.message.strip() await current_client.sign_in(password=received_tfa_code) # all done # 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()) string_session_messeg = await conv.send_message(f"{session_id}") await string_session_messeg.reply("now, " "please turn of the application " "and set the above variable to " "`HU_STRING_SESSION` variable, " "and restart application.") else: await event.reply("un authorized -_- user(s)")
import mautrix_telegram.db from mautrix_telegram.config import Config from alchemysession import AlchemySessionContainer # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config mxtg_config_path = context.get_x_argument(as_dictionary=True).get( "config", "config.yaml") mxtg_config = Config(mxtg_config_path, None, None) mxtg_config.load() config.set_main_option("sqlalchemy.url", mxtg_config["appservice.database"].replace("%", "%%")) AlchemySessionContainer.create_table_classes(None, "telethon_", Base) # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata target_metadata = Base.metadata # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc.
config = context.config mxtg_config_path = context.get_x_argument(as_dictionary=True).get("config", "config.yaml") mxtg_config = Config(mxtg_config_path, None, None) mxtg_config.load() config.set_main_option("sqlalchemy.url", mxtg_config.get("appservice.database", "sqlite:///mautrix-telegram.db")) class FakeDB: @staticmethod def query_property(): return None AlchemySessionContainer.create_table_classes(FakeDB(), "telethon_", Base) # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata target_metadata = Base.metadata # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option")
import sqlalchemy as sa from alchemysession import AlchemySessionContainer from companion.env_vars import DB_URI, SESSION_NAME if DB_URI: engine = sa.create_engine(DB_URI) connection = engine.connect() container = AlchemySessionContainer(DB_URI) container.core_mode = True SESSION = container.new_session(SESSION_NAME) else: engine = None metadata = None connection = None SESSION = SESSION_NAME
sys.exit(0) if config["appservice.debug"]: telethon_log = logging.getLogger("telethon") telethon_log.addHandler(handler) telethon_log.setLevel(logging.DEBUG) log.setLevel(logging.DEBUG) log.debug("Debug messages enabled.") db_engine = sql.create_engine(config.get("appservice.database", "sqlite:///mautrix-telegram.db")) db_factory = orm.sessionmaker(bind=db_engine) db_session = orm.scoping.scoped_session(db_factory) Base.metadata.bind = db_engine telethon_session_container = AlchemySessionContainer(engine=db_engine, session=db_session, table_base=Base, table_prefix="telethon_", manage_tables=False) loop = asyncio.get_event_loop() appserv = AppService(config["homeserver.address"], config["homeserver.domain"], config["appservice.as_token"], config["appservice.hs_token"], config["appservice.bot_username"], log="mau.as", loop=loop, verify_ssl=config["homeserver.verify_ssl"]) context = Context(appserv, db_session, config, loop, None, None, telethon_session_container) if config["appservice.public.enabled"]: public = PublicBridgeWebsite(loop) appserv.app.add_subapp(config.get("appservice.public.prefix", "/public"), public.app)