Пример #1
0
 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()
Пример #2
0
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)
Пример #3
0
    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)
Пример #4
0
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)
Пример #5
0
# 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
    has_media = event.media
Пример #6
0
# 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()

    def __str__(self):
Пример #7
0

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'
    logging.info(
        "[] did not provide / generate "
Пример #8
0
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')
Пример #9
0
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)")
Пример #10
0
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
Пример #11
0
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

    params = (post.message, post.post_author, post.grouped_id, post.fwd_from)