async def handle_database_error(bot): GearbotLogging.error(traceback.format_exc()) # database trouble, notify bot owner message = f"{Emoji.get_chat_emoji('WARNING')} Peewee exception caught! attempting to reconnect to the database!" await GearbotLogging.message_owner(bot, message) await GearbotLogging.logToBotlog(message) try: DatabaseConnector.init() bot.database_connection = DatabaseConnector.connection except: # fail, trying again in 10 just in case the database is rebooting time.sleep(15) try: DatabaseConnector.init() bot.database_connection = DatabaseConnector.connection except: if os.path.isfile('stage_2.txt'): message = f"{Emoji.get_chat_emoji('NO')} VM reboot did not fix the problem, shutting down completely for fixes" await bot.get_user(bot.owner_id).dm_channel.send(message) await GearbotLogging.logToBotlog(message) with open("stage_3.txt", "w") as file: file.write("stage_3") os.kill(os.getpid(), 9) elif os.path.isfile('stage_1.txt'): with open("stage_2.txt", "w") as file: file.write("stage_2") message = f"{Emoji.get_chat_emoji('NO')} Reconnecting and bot rebooting failed, escalating to VM reboot" await GearbotLogging.message_owner(bot, message) await GearbotLogging.logToBotlog(message) data = {'type': 'reboot'} async with aiohttp.ClientSession( headers= { 'Content-Type': 'application/json', 'Authorization': f'Bearer {Configuration.getMasterConfigVar("DO_TOKEN")}' }) as session: await session.post( f'https://api.digitalocean.com/v2/droplets/{Configuration.getMasterConfigVar("DO_ID")}/actions', data=json.dumps(data), timeout=30) time.sleep(60) else: message = f"{Emoji.get_chat_emoji('NO')} Reconnecting failed, escalating to reboot" await GearbotLogging.message_owner(bot, message) await GearbotLogging.logToBotlog(message) with open("stage_1.txt", "w") as file: file.write("stage_1") os.kill(os.getpid(), 9) else: message = f"{Emoji.get_chat_emoji('YES')} 2nd reconnection attempt successfully connected!" await GearbotLogging.message_owner(bot, message) await GearbotLogging.logToBotlog(message) else: message = f"{Emoji.get_chat_emoji('YES')} 1st reconnection attempt successfully connected!" await GearbotLogging.message_owner(bot, message) await GearbotLogging.logToBotlog(message)
async def initialize(bot): #lock event handling while we get ready bot.locked = True try: #database GearbotLogging.info("Connecting to the database.") DatabaseConnector.init() bot.database_connection = DatabaseConnector.connection GearbotLogging.info("Database connection established.") GearbotLogging.initialize_pump(bot) Emoji.initialize(bot) Pages.initialize(bot) Utils.initialize(bot) Translator.initialize(bot) InfractionUtils.initialize(bot) bot.data = { "forced_exits": set(), "unbans": set(), "message_deletes": set() } await GearbotLogging.initialize( bot, Configuration.get_master_var("BOT_LOG_CHANNEL")) if bot.redis_pool is None or not hasattr( bot, 'redis_raid_pool') or bot.redis_raid_pool is None: try: bot.redis_pool = await aioredis.create_redis_pool( (Configuration.get_master_var('REDIS_HOST', "localhost"), Configuration.get_master_var('REDIS_PORT', 6379)), encoding="utf-8", db=0) bot.redis_raid_pool = await aioredis.create_redis_pool( (Configuration.get_master_var('REDIS_HOST', "localhost"), Configuration.get_master_var('REDIS_PORT', 6379)), encoding="utf-8", db=1) except OSError: GearbotLogging.error( "==============Failed to connect to redis==============") await GearbotLogging.bot_log( f"{Emoji.get_chat_emoji('NO')} Failed to connect to redis, caching and anti-raid connections unavailable" ) else: GearbotLogging.info("Redis connection established") await GearbotLogging.bot_log( f"{Emoji.get_chat_emoji('YES')} Redis connection established, caching and anti-raid connections established" ) if bot.aiosession is None: bot.aiosession = aiohttp.ClientSession() bot.being_cleaned.clear() await Configuration.initialize(bot) except Exception as ex: #make sure we always unlock, even when something went wrong! bot.locked = False raise ex bot.locked = False
async def initialize(bot, startup=False): #lock event handling while we get ready bot.locked = True try: #database GearbotLogging.info("Connecting to the database.") DatabaseConnector.init() bot.database_connection = DatabaseConnector.connection GearbotLogging.info("Database connection established.") Emoji.initialize(bot) Utils.initialize(bot) InfractionUtils.initialize(bot) bot.data = { "forced_exits": set(), "unbans": set(), "message_deletes": set(), "nickname_changes": set() } await GearbotLogging.initialize(bot, Configuration.get_master_var("BOT_LOG_CHANNEL")) if startup: c = await Utils.get_commit() bot.version = c GearbotLogging.info(f"GearBot spinning up version {c}") await GearbotLogging.bot_log(f"{Emoji.get_chat_emoji('ALTER')} GearBot spinning up version {c}") if bot.redis_pool is None: try: socket = Configuration.get_master_var("REDIS_SOCKET", "") if socket == "": bot.redis_pool = await aioredis.create_redis_pool((Configuration.get_master_var('REDIS_HOST', "localhost"), Configuration.get_master_var('REDIS_PORT', 6379)), encoding="utf-8", db=0) else: bot.redis_pool = await aioredis.create_redis_pool(socket, encoding="utf-8", db=0) except OSError: GearbotLogging.error("==============Failed to connect to redis==============") await GearbotLogging.bot_log(f"{Emoji.get_chat_emoji('NO')} Failed to connect to redis, caching unavailable") else: GearbotLogging.info("Redis connection established") await GearbotLogging.bot_log(f"{Emoji.get_chat_emoji('YES')} Redis connection established, let's go full speed!") if bot.aiosession is None: bot.aiosession = aiohttp.ClientSession() await Translator.initialize(bot) bot.being_cleaned.clear() await Configuration.initialize(bot) DashConfig.initialize(bot) except Exception as ex: #make sure we always unlock, even when something went wrong! bot.locked = False raise ex bot.locked = False
def main(): try: database = DatabaseConnector(config.USER, config.PASSWORD, config.HOST, config.DATABASE) mysql_connect = database.mysql_open_connection() sql = ( 'SELECT article_id, title, received_date FROM article WHERE received_date BETWEEN %s AND %s' ) received_date_start = datetime.date(2008, 1, 4) received_date_end = datetime.date(2008, 3, 5) paremeters = (received_date_start, received_date_end) cursor, data = database.mysql_execute_cursor_select( mysql_connect, sql, paremeters) if cursor.rowcount > 0: for row in data: print(row[ArticleColumn.article_id.value], row[ArticleColumn.title.value], row[ArticleColumn.received_date.value], sep='\t') except: exception_message = sys.exc_info()[0] print("An error occurred. {}".format(exception_message)) finally: database.mysql_close_cursor(cursor) database.mysql_close_connection(mysql_connect)
def open_mysql_database( user = None, password = None, host = None, db = None): db = None db_connect = None try: db = DatabaseConnector(config.USER, config.PASSWORD, config.HOST, config.DATABASE) db_connect = db.mysql_open_connection() except Exception as ex: _logger.error('Unable to open the ' + config.DATABASE + ' database: ') _logger.error(str(ex)) db = None db_connect = None return (db, db_connect)
def main(): try: database = DatabaseConnector(config.USER, config.PASSWORD, config.HOST, config.DATABASE) mysql_connect = database.mysql_open_connection() sql = ('DELETE FROM magazine_type WHERE magazine_type_id = %s') paremeters = (9, ) database.mysql_execute_cursor_update(mysql_connect, sql, paremeters) except: exception_message = sys.exc_info()[0] print("An error occurred. {}".format(exception_message)) finally: database.mysql_close_connection(mysql_connect)
def main(): try: database = DatabaseConnector(config.USER, config.PASSWORD, config.HOST, config.DATABASE) mysql_connect = database.mysql_open_connection() sql = ( 'INSERT INTO magazine_type (type, description, notes, update_id) VALUES (%s, %s, %s, %s)' ) paremeters = ('Lunix', 'The Lunix Magazine', 'The Notes', 300) database.mysql_execute_cursor_update(mysql_connect, sql, paremeters) except: exception_message = sys.exc_info()[0] print("An error occurred. {}".format(exception_message)) finally: database.mysql_close_connection(mysql_connect)
def main(): try: database = DatabaseConnector(config.USER, config.PASSWORD, config.HOST, config.DATABASE) mysql_connect = database.mysql_open_connection() sql = ( "UPDATE magazine_type SET type = %s , description = %s, notes = %s, update_id = %s WHERE magazine_type_id = %s" ) paremeters = ('Windows', 'The Windows IT Magazine', 'The Notes', 300, 14) database.mysql_execute_cursor_update(mysql_connect, sql, paremeters) except: exception_message = sys.exc_info()[0] print("An error occurred. {}".format(exception_message)) finally: database.mysql_close_connection(mysql_connect)
def main(): try: database = DatabaseConnector(config.USER, config.PASSWORD, config.HOST, config.DATABASE) mysql_connect = database.mysql_open_connection() sql = ( 'SELECT author_id, first_name, last_name, middle_name FROM author WHERE last_name LIKE %s ORDER BY first_name' ) paremeters = ('%w%', ) cursor, data = database.mysql_execute_cursor_select( mysql_connect, sql, paremeters) if cursor.rowcount > 0: for row in data: print(row[ArticleColumn.article_id.value], row[ArticleColumn.title.value], row[ArticleColumn.received_date.value], sep='\t') except: exception_message = sys.exc_info()[0] print("An error occurred. {}".format(exception_message)) finally: database.mysql_close_cursor(cursor) database.mysql_close_connection(mysql_connect)
def get_author_info(first_name_parameters): try: database = DatabaseConnector(config.USER, config.PASSWORD, config.HOST, config.DATABASE) mysql_connect = database.mysql_open_connection() sql = ( "SELECT author_id, first_name, last_name, middle_name FROM author WHERE first_name = %s" ) paremeters = ('John', ) cursor, data = database.mysql_execute_cursor_select( mysql_connect, sql, paremeters) if cursor.rowcount > 0: for row in data: print(row[AuthorContact.author_id.value], row[AuthorContact.first_name.value], row[AuthorContact.last_name.value], row[AuthorContact.middle_name.value], sep='\t') except: exception_message = sys.exc_info()[0] print("An error occurred. {}".format(exception_message)) finally: database.mysql_close_cursor(cursor) database.mysql_close_connection(mysql_connect)
from gui import Gui from database import DatabaseConnector database_connector = DatabaseConnector("database.db") def main(): database_connector.connect() database_connector.setup_tables() print("Connected to database.") gui = Gui(database_connector) gui.show_main() database_connector.disconnect() print("Disconnected from database.") if __name__ == '__main__': main()
def prepDatabase(bot): GearbotLogging.info("Connecting to the database.") DatabaseConnector.init() bot.database_connection = DatabaseConnector.connection GearbotLogging.info("Database connection established.")
picture = 16 notes = 17 active = 18 updated_id = 19 updated_date = 20 # author_id, first_name, last_name, middle_name, title, job_description, street_1, street_2, city, # state_province, zip_code, country, phone, fax, email, website, picture, notes, active, updated_id, updated_date # class DataEnum: # author_id, first_name, last_name, middle_name, title, job_description, street_1, street_2, city, state_province, zip_code, country, phone, fax, email, website, picture, notes, active, updated_id, updated_date = range(0, 21) if __name__ == '__main__': try: database = DatabaseConnector(config.USER, config.PASSWORD, config.HOST, config.DATABASE) mysql_connect = database.mysql_open_connection() dataset = database.mysql_call_procedure_select(mysql_connect, "usp_author_select") for row in dataset: print(row[AuthorColumn.author_id.value], row[AuthorColumn.first_name.value], row[AuthorColumn.last_name.value], row[AuthorColumn.middle_name.value], row[AuthorColumn.title.value], row[AuthorColumn.job_description.value], row[AuthorColumn.street_1.value], row[AuthorColumn.street_2.value], row[AuthorColumn.city.value], row[AuthorColumn.state_province.value], row[AuthorColumn.zip_code.value],