replicator/twitter-setup.py
2022-02-16 18:43:30 +01:00

92 lines
2.1 KiB
Python

import getpass
import os
import sys
import psycopg2
import pdb
def save_secrets(api_key, api_key_secret):
save_error = None
sql = f'INSERT INTO tsecrets (api_key, api_key_secret) VALUES (%s,%s)'
conn = None
try:
conn = psycopg2.connect(database = replicator_db, user = replicator_db_user, password = "", host = "/var/run/postgresql", port = "5432")
cur = conn.cursor()
cur.execute(sql, (api_key, api_key_secret))
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
save_error = error.pgcode
sys.stdout.write(f'\n{str(error)}\n')
finally:
if conn is not None:
conn.close()
return save_error
def get_config():
# Load configuration from config file
config_filepath = "config/db_config.txt"
replicator_db = get_db_params("replicator_db", config_filepath)
replicator_db_user = get_db_params("replicator_db_user", config_filepath)
return (config_filepath, replicator_db, replicator_db_user)
def ask_secrets():
print(f'Setting up Twitter key & secret ...\n')
api_key = input("API Key: ")
api_key_secret = input("API Key Secret: ")
return (api_key, api_key_secret)
def get_db_params( parameter, file_path ):
if not os.path.isfile(file_path):
print("File %s not found, exiting."%file_path)
sys.exit(0)
# Find parameter in file
with open( file_path ) as f:
for line in f:
if line.startswith( parameter ):
return line.replace(parameter + ":", "").strip()
# Cannot find parameter, exit
print(file_path + " Missing parameter %s "%parameter)
sys.exit(0)
###############################################################################
# main
if __name__ == '__main__':
config_filepath, replicator_db, replicator_db_user = get_config()
api_key, api_key_secret = ask_secrets()
save_error = save_secrets(api_key, api_key_secret)
if save_error == None:
print(f'Done.')
else:
if save_error == '423505':
sys.exit()