예제 #1
0
    def create_client(self):
        """Creates and returns a TelegramClient"""
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        api_id = secrets.get_var('API_ID')
        api_hash = secrets.get_var('API_HASH')
        # TODO
        # proxy=(socks.SOCKS5, '127.0.0.1', 4444)

        if LOCALHOST:
            session = 'karim/bot/persistence/{}'.format(self.user_id)
        else:
            session_string = os.environ.get('session:{}'.format(self.user_id))
            if not session_string:
                try:
                    # Falling Back to RedisSession
                    print('LOADING REDIS SESSION')
                    connector = redis.from_url(os.environ.get('REDIS_URL'))
                    string = connector.get('session:{}'.format(self.user_id))
                    print('SESSION STRING OUTPUTTED')
                    if string:
                        # Session is stored in Redis
                        decoded_string = string.decode("utf-8")
                        session = StringSession(decoded_string)
                    else:
                        session = StringSession()
                    connector.close()
                except Exception as error:
                    # No Session Error
                    print('Error in session_manager.create_client(): ', error)
                    raise error
            else:
                try:
                    session = StringSession(session_string)
                except Exception as error:
                    print('Error in session_manager.create_client(): ', error)
                    raise error
        try:
            client = TelegramClient(session, api_id, api_hash,
                                    loop=loop)  #proxy = proxy
        except Exception as error:
            print('Error in session_manager.create_client(): ', error)
            raise error
        print('TELEGRAM CLIENT WITH SESSION CREATED')
        return client
예제 #2
0
파일: mq_bot.py 프로젝트: wickerdevs/karim
 def report_error(self, error=None, send_screenshot=False, screenshot_name=''):
     string = str(secrets.get_var('DEVS')).replace('[', '')
     string = string.replace(']', '')
     string = string.replace(' ', '')
     devs = list(string.split(','))
     for dev in devs:
         if send_screenshot:
             self.send_photo(chat_id=int(dev), photo=open('{}.png'.format(screenshot_name), 'rb'), caption='There was an error with the Karim Luman bot: \n{}'.format(error))
         else:
             self.send_message(chat_id=int(dev), text='There was an error with the Karim Luman bot: \n{}'.format(error))
예제 #3
0
 def request_code(self):
     client = self.create_client()
     client.connect()
     print('SENT CODE TO PHONE')
     #if not request_again:
     try:
         sent_code = client(
             functions.auth.SendCodeRequest(
                 phone_number=self.phone,
                 api_id=int(secrets.get_var('API_ID')),
                 api_hash=secrets.get_var('API_HASH'),
                 settings=types.CodeSettings(allow_flashcall=True,
                                             current_number=True,
                                             allow_app_hash=True)))
     except PhoneNumberFloodError as error:
         print('Error in session_manager.request_code(): ', error)
         raise error
     except PhonePasswordFloodError as error:
         print('Error in session_manager.request_code(): ', error)
         raise error
     except PhonePasswordProtectedError as error:
         print('Error in session_manager.request_code(): ', error)
         raise error
     except Exception as error:
         print('Error in session_manager.request_code(): ', error)
         raise error
     """ else:
         try:
             sent_code = client(ResendCodeRequest(self.phone, self.phone_code_hash))
         except PhoneNumberInvalidError as error:
             print('Error in session_manager.request_code(): ', error)
             raise error
         except Exception as error:
             print('Error in session_manager.request_code(): ', error)
             raise error """
     print('SENT CODE REQUEST!')
     self.phone_code_hash = sent_code.phone_code_hash
     self.code_tries += 1
     client.disconnect()
     return sent_code
예제 #4
0
def auth():
    creds_string = secrets.get_var('GSPREAD_CREDS')
    if creds_string == None:
        # use creds to create a client to interact with the Google Drive API
        scope = [
            'https://spreadsheets.google.com/feeds',
            'https://www.googleapis.com/auth/drive',
            'https://www.googleapis.com/auth/drive.file',
            'https://www.googleapis.com/auth/drive'
        ]
        # CREDENTIALS HAVE NOT BEEN INITIALIZED BEFORE
        client_secret = os.environ.get('GCLIENT_SECRET')
        if LOCALHOST:
            # CODE RUNNING LOCALLY
            print('DATABASE: Resorted to local JSON file')
            with open('karim/secrets/client_secret.json') as json_file:
                client_secret_dict = json.load(json_file)
        else:
            # CODE RUNNING ON SERVER
            client_secret_dict = json.loads(client_secret)

        creds = ServiceAccountCredentials.from_json_keyfile_dict(
            client_secret_dict, scope)
        creds_string = jsonpickle.encode(creds)
        secrets.set_var('GSPREAD_CREDS', creds_string)
    creds = jsonpickle.decode(creds_string)
    client = gspread.authorize(creds)

    # IF NO SPREADSHEET ENV VARIABLE HAS BEEN SET, SET UP NEW SPREADSHEET
    if secrets.get_var('SPREADSHEET') == None:
        spreadsheet = set_sheet(client)
        return spreadsheet
    else:
        SPREADSHEET = secrets.get_var('SPREADSHEET')
        spreadsheet = client.open_by_key(SPREADSHEET)
        return spreadsheet
예제 #5
0
def error(update, context):
    """Log the error and send a telegram message to notify the developer."""
    # Log the error before we do anything else, so we can see it even if something breaks.
    logger.error(msg="Exception while handling an update:",
                 exc_info=context.error)

    # traceback.format_exception returns the usual python message about an exception, but as a
    # list of strings rather than a single string, so we have to join them together.
    tb_list = traceback.format_exception(None, context.error,
                                         context.error.__traceback__)
    tb = ''.join(tb_list)

    # Build the message with some markup and additional information about what happened.
    # You might need to add some logic to deal with messages longer than the 4096 character limit.
    message = ('<b>An exception was raised while handling an update</b>\n'
               '<pre>{}</pre>').format(html.escape(tb))

    # Finally, send the message
    devs = secrets.get_var('DEVS')
    for dev in devs:
        context.bot.send_message(chat_id=dev,
                                 text=message,
                                 parse_mode=ParseMode.HTML)
예제 #6
0
def set_sheet(client: Client):
    """
    Setup spreadsheet database if none exists yet.
    Will save the spreadsheet ID to Heroku Env Variables or to secrets.json file
    The service email you created throught the Google API will create the new spreadsheet and share it with the email you indicated in the GDRIVE_EMAIL enviroment variable. You will find the spreadsheet database in your google drive shared folder.
    Don't change the order of the worksheets or it will break the code.

    :param client: GSpread client to utilize
    :type client: Client
    :return: The newly created spreadsheet
    :rtype: Spreadsheet
    """
    # CREATE SPREADSHEET
    spreadsheet: Spreadsheet = client.create('KARIM NEWSLETTER')
    secrets.set_var('SPREADSHEET', spreadsheet.id)

    # CREATE GROUP CHATS SHEET
    subscribers = spreadsheet.add_worksheet(title="Subscribers",
                                            rows="150",
                                            cols="1")
    scraped = spreadsheet.add_worksheet(title='IG Scraped',
                                        rows='150',
                                        cols='3')

    # CREATE LOGS SHEET
    logs = spreadsheet.add_worksheet(title="Logs", rows="500", cols="3")
    logs.append_row(["TIMESTAMP", "USER ID", "ACTION"])

    # DELETE PRE-EXISTING SHEET
    sheet = spreadsheet.get_worksheet(0)
    spreadsheet.del_worksheet(sheet)

    # SHARE SPREADSHEET
    spreadsheet.share(value=secrets.get_var('GDRIVE_EMAIL'),
                      perm_type="user",
                      role="owner")
    return spreadsheet
예제 #7
0
LOCALHOST = True
queue = None
if os.environ.get('PORT') in (None, ""):
    # Code running locally
    LOCALHOST = True
    if not os.path.exists('karim/bot/persistence'):
        os.makedirs('karim/bot/persistence')
else:
    LOCALHOST = False
    queue = Queue(connection=conn)
    

# Initialize Bot
from karim.secrets import secrets
BOT_TOKEN = secrets.get_var('BOT_TOKEN', localhost=LOCALHOST)
URL = secrets.get_var('SERVER_APP_DOMAIN', localhost=LOCALHOST)
PORT = int(os.environ.get('PORT', 5000))
from karim.bot import telebot

# set connection pool size for bot 
request = Request(con_pool_size=8)
q = mq.MessageQueue(all_burst_limit=3, all_time_limit_ms=3000)
telegram_bot = MQBot(BOT_TOKEN, request=request, mqueue=q)
updater = Updater(bot=telegram_bot, use_context=True)

# SET UP BOT COMMAND HANDLERS
telebot.setup(updater)