def deserialize(method, update): if LOCALHOST: # CODE RUNNING LOCALLY try: with open("ffinstabot/bot/persistence/{}{}.json".format( method, update.effective_chat.id)) as file: json_string = json.load(file) obj = jsonpickle.decode(json_string) return obj except: return None else: # Code Running on Heroku # Get Redis String try: connector = redis.from_url(os.environ.get('REDIS_URL')) obj_bytes = connector.get("persistence:{}{}".format( method, update.effective_chat.id)) connector.close() obj_string = obj_bytes.decode("utf-8") obj = jsonpickle.decode(obj_string) return obj except Exception as error: applogger.debug( 'Error in persistence.deserialzie(): {}'.format(error)) return None
def instagram_username(update, context): instasession: InstaSession = InstaSession.deserialize( Persistence.INSTASESSION, update) if not instasession: return InstaStates.INPUT_USERNAME username = update.message.text message = send_message(update, context, checking_user_vadility_text) instasession.set_message(message.message_id) markup = CreateMarkup({Callbacks.CANCEL: 'Cancel'}).create_markup() # Verify User instaclient = instagram.init_client() try: result = instaclient.is_valid_user(username) applogger.debug('USER {} IS VALID: {}'.format(username, result)) except InvalidUserError as error: send_message(update, context, invalid_user_text.format(error.username), markup) instasession.set_message(message.message_id) instaclient.disconnect() return InstaStates.INPUT_USERNAME except: pass instaclient.disconnect() instasession.set_username(username) # Request Password send_message(update, context, input_password_text, markup) return InstaStates.INPUT_PASSWORD
def get_follow(user_id:int, session:str, target:str, sheet:Worksheet=None): if not sheet: spreadsheet = auth() sheet:Worksheet = spreadsheet.get_worksheet(1) follows = get_follows(user_id, session, sheet) applogger.debug(f'ID: {user_id} SESSION: {session}') if not follows: return None applogger.debug(f'Imported selected follows: {follows}') for follow in follows: if follow.get_target() == target: return follow return None
def get_all_follows(sheet:Worksheet=None): if not sheet: spreadsheet = auth() sheet:Worksheet = spreadsheet.get_worksheet(1) rows = get_rows(sheet)[1:] follows = list() for row in rows: follows.append(jsonpickle.decode(row[0])) if len(follows) < 1: applogger.debug(f'All follows: {follows}') return None applogger.debug(f'All follows: {follows}') return follows
def get_follows(user_id:int, session:str, sheet:Worksheet=None): if not sheet: spreadsheet = auth() sheet:Worksheet = spreadsheet.get_worksheet(1) follows = get_all_follows(sheet) if not follows: return None selected = list() for follow in follows: if follow.get_user_id() == user_id and follow.username == session: selected.append(follow) applogger.debug(f'Selected follows: {follows}') if len(selected) < 1: return None return selected
def discard(self): if LOCALHOST: # CODE RUNNING LOCALLY try: os.remove("ffinstabot/bot/persistence/{}{}.json".format( self.method, self.user_id)) except FileNotFoundError: return self else: # CODE RUNNING ON SERVER try: connector = redis.from_url(os.environ.get('REDIS_URL')) connector.delete('persistence:{}{}'.format( self.method, self.user_id)) connector.close() except Exception as error: applogger.debug( 'Error in persistence.discard(): {}'.format(error))
def send_message(update: Update, context: CallbackContext, message: str, markup=None): if update.callback_query: update.callback_query.answer() if markup: message = update.callback_query.edit_message_text( text=message, reply_markup=markup) else: message = update.callback_query.edit_message_text(text=message) sheet.set_message(update.effective_user.id, message.message_id) return message elif sheet.get_message(update.effective_chat.id): message_id = sheet.get_message(update.effective_chat.id) try: context.bot.delete_message(chat_id=update.effective_chat.id, message_id=message_id) applogger.debug(f'Deleted bot message. id: {message_id}') except: pass try: message_id = update.message.message_id update.message.delete() applogger.debug(f'Deleted user message. id: {message_id}') except: pass if markup: message = context.bot.send_message(chat_id=update.effective_chat.id, text=message, parse_mode=ParseMode.HTML, reply_markup=markup) else: message = context.bot.send_message(chat_id=update.effective_chat.id, text=message, parse_mode=ParseMode.HTML) sheet.set_message(update.effective_user.id, message.message_id) return message
def serialize(self): if LOCALHOST: # CODE RUNNING LOCALLY if not os.path.isdir('ffinstabot/bot/persistence/'): os.mkdir('ffinstabot/bot/persistence/') with open( "ffinstabot/bot/persistence/{}{}.json".format( self.method, self.user_id), "w") as write_file: encoded = jsonpickle.encode(self) json.dump(encoded, write_file, indent=4) else: # Code running on Heroku try: connector = redis.from_url(os.environ.get('REDIS_URL')) obj_string = jsonpickle.encode(self) connector.set( 'persistence:{}{}'.format(self.method, self.user_id), obj_string) connector.close() except Exception as error: applogger.debug( 'Error in persistence.serialize(): {}'.format(error)) return self
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 os.environ.get('PORT') in (None, ""): # CODE RUNNING LOCALLY applogger.debug('DATABASE: Resorted to local JSON file') with open('ffinstabot/config/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) if os.environ.get('PORT') in (None, ""): 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
def check_auth(update, context): users_str = secrets.get_var('USERS') if isinstance(users_str, str): users_str = users_str.replace('[', '') users_str = users_str.replace(']', '') users_str = users_str.replace(' ', '') users = users_str.split(',') for index, user in enumerate(users): users[index] = int(user) else: users = users_str if update.effective_user.id in users: applogger.debug('User is authorized to use the bot') return True else: applogger.debug('User is NOT authorized to use the bot.') try: send_message(update, context, not_authorized_text) return False except Exception as error: applogger.debug('Error in sending message: {}'.format(error)) return False
import os, logging import telegram from ffinstabot import updater, BOT_TOKEN, URL, PORT, LOCALHOST, applogger if __name__ == '__main__': if LOCALHOST: applogger.info('Polling Telegram bot...') updater.start_polling() else: # Setup Telegram Webhook applogger.debug('STARTING WEBHOOK') updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=BOT_TOKEN) applogger.debug('WEBHOOK STARTED - SETTING UP WEBHOOK') updater.bot.set_webhook('{URL}/{HOOK}'.format(URL=URL, HOOK=BOT_TOKEN)) applogger.debug('WEBHOOK SET UP CORRECTLY') updater.idle()