async def on_channel_create(channel): Mysql.add_channel(channel) channelString = str(channel) if channelString.startswith("Direct Message"): output.info(channelString) else: output.info("Channel {0} added to {1}".format(channel.name, channel.server.name))
async def on_server_join(server): output.info("Added to {0}".format(server.name)) Mysql.add_server(server) for channel in server.channels: Mysql.add_channel(channel) await bot.say(server.default_channel, "Hey {0}, {1} seems nice. To set me up run {2}configure otherwise I will work in all channels".format( server.owner.mention, server.name, config["prefix"]))
def prompt(self): """ Interaction shell with the session """ def get_cwd(): self.send_cmd({ 'command': '', }) self.recv_output() cmd = None get_cwd() while cmd != "exit": try: cmd = raw_input(self.cwd + '> ') if cmd == 'exit': break msg = None fw = cmd.split(" ")[0] if self.commands.has_key(fw): method = self.commands[fw]['method'] cmd_args = len(cmd.split(" ")) - 1 if cmd_args == 2: arg1, arg2 = cmd.split(" ")[1], cmd.split(" ")[2] msg = method(self, arg1, arg2) elif cmd_args == 1: arg1 = cmd.split(" ")[1] msg = method(self, arg1) elif not cmd_args: msg = method(self) else: help_menu(self.commands) if msg is not None: status = msg[0] print_str = msg[1] if status == 'success': good(print_str) elif status == 'error': error(print_str) elif cmd == 'help': help_menu(self.commands) else: if self.send_cmd({'command': cmd}): if cmd == 'kill': break try: cmd_output = self.recv_output()['output'] except struct.error: error('Slave connection died') break except Exception as e: raise else: if cmd_output: print(cmd_output) else: error('Could not send command') except (socket.timeout): error("Connection closed by remote host") break except KeyboardInterrupt: info("Closing session prompt") break
async def shutdown(ctx): """Shut down the bot [ADMIN ONLY]""" author = str(ctx.message.author) try: await ctx.send("Shutting down...") await bot.logout() output.info('{} has shut down the bot...'.format(author)) except Exception as e: print(e)
async def on_ready(): output.info("Loading {} extension(s)...".format(len(startup_extensions))) for extension in startup_extensions: try: bot.load_extension("cogs.{}".format(extension.replace(".py", ""))) loaded_extensions.append(extension) except Exception as e: exc = '{}: {}'.format(type(e).__name__, e) output.error('Failed to load extension {}\n\t->{}'.format(extension, exc)) output.success('Successfully loaded the following extension(s): {}'.format(', '.join(loaded_extensions))) output.info('You can now invite the bot to a server using the following link: https://discordapp.com/oauth2/authorize?client_id={}&scope=bot'.format(bot.user.id))
def check_for_user(self, tx_account): to_exec = """SELECT snowflake FROM db WHERE snowflake LIKE %s""" self.cursor.execute(to_exec, (str(tx_account))) result_set = self.cursor.fetchone() if result_set == None: output.info("User does not exist in db, adding...") self.make_user(tx_account) output.success("User exists in db, proceeding...") return result_set
async def on_ready(): output.info("Loading {} extension(s)...".format(len(startup_extensions))) for extension in startup_extensions: try: bot.load_extension("cogs.{}".format(extension.replace(".py", ""))) loaded_extensions.append(extension) except Exception as e: exc = '{}: {}'.format(type(e).__name__, e) output.error('Failed to load extension {}\n\t->{}'.format(extension, exc)) output.success('Successfully loaded the following extension(s); {}'.format(loaded_extensions))
async def restart(ctx): """Restart the bot""" author = str(ctx.message.author) try: await ctx.send("Restarting...") await bot.logout() output.info('{} has restarted the bot...'.format(author)) except Exception as e: print(e) pass finally: os.system('./restart.sh')
def report(self): utils.report("Budget (monthly)", self.data, self.surplus) if (self.surplus < 0.0): output.warn( "Spending exceeds available income by %.2f. Please readjust." % -(self.surplus)) else: output.info("You have surplus %.2f to invest." % (self.surplus)) pie_n = [n for n, v in self.data.items() if (n != "income")] pie_v = [abs(v) for n, v in self.data.items() if (n != "income")] pie_n.append("surplus") pie_v.append(self.surplus) utils.piechart("Budget", "Budget Allocation", pie_n, pie_v)
def my_connection(self): if self.connected == 0: output.warning( "Connection has been lost, attempting to reconnect...") elif self.connected == 1: output.info("Establishing connection to database...") self.connection = pymysql.connect(host=self.host, port=self.port, user=self.db_user, password=self.db_pass, db=self.db) self.cursor = self.connection.cursor(pymysql.cursors.DictCursor) return
async def unload(ctx, module: str): """Unload any loaded cog [ADMIN ONLY]""" author = str(ctx.message.author) module = module.strip() try: bot.unload_extension("cog.{}".format(module)) output.info('{} unloaded module: {}'.format(author, module)) startup_extensions.remove(module) await ctx.send("Successfully unloaded {}.py".format(module)) except Exception as e: exc = '{}: {}'.format(type(e).__name__, e) await ctx.send('Failed to load extension {}\n\t->{}'.format( module, exc))
async def shutdown(ctx): """Shut down the bot""" author = str(ctx.message.author) try: await bot.say("Shutting down...") await bot.logout() bot.loop.stop() output.info('{} has shut down the bot...'.format(author)) except Exception as e: exc = '{}: {}'.format(type(e).__name__, e) output.error('{} has attempted to shut down the bot, but the following ' 'exception occurred;\n\t->{}'.format(author, exc))
async def reload(ctx, module: str): """Load a cog located in /cogs [ADMIN ONLY]""" author = str(ctx.message.author) module = module.strip() try: bot.reload_extension("cog.{}".format(module)) output.info('{} reloaded module: {}'.format(author, module)) await ctx.send("Successfully reloaded {}.py".format(module)) except Exception as e: exc = '{}: {}'.format(type(e).__name__, e) output.error('{} attempted to reload module \'{}\' but the following ' 'exception occured;\n\t->{}'.format(author, module, exc)) await ctx.send('Failed to reload extension {}\n\t->{}'.format( module, exc))
def get_db(self, tx_account, tx_amount, txid, tx_category): to_exec = """SELECT balance, staked FROM db WHERE snowflake LIKE %s""" self.cursor.execute(to_exec, str(tx_account)) result_set = self.cursor.fetchone() if tx_category == "generated": new_stake = float(result_set["staked"]) - tx_amount output.info("Adding user's staked amount to db...") self.update_stake_db(tx_account, new_stake, txid) else: output.info("Adding user's new balance to db...") new_balance = float(result_set["balance"]) + tx_amount self.update_balance_db(tx_account, new_balance, txid)
async def restart(ctx): """Restart the bot""" author = str(ctx.message.author) try: await bot.say("Restarting...") await bot.logout() bot.loop.stop() output.info('{} has restarted the bot...'.format(author)) os.system('sh restart.sh') except Exception as e: exc = '{}: {}'.format(type(e).__name__, e) output.error('{} has attempted to restart the bot, but the following ' 'exception occurred;\n\t->{}'.format(author, exc))
def emergency_fund(self): print("\n") output.section_start("Emergency Fund means sleep in peace...") output.info("ANALYSIS - Checking and allocating emergency fund....") a = self._a b = self._b e = self._e expenses = e.get_monthly() required = expenses * EMERGENCY_FUND_MONTHS self.allocation['Emergency Fund'] = 0.0 if (required < a.total): output.info( "You have enough emergency fund %.2f in your assets %.2f." % (required, a.total)) output.info("Allocating your assets to build emergency fund %.2f" % (required)) output.action("Build or allocate emergency fund.") for n, v in sorted(a.data.items(), key=lambda x: x[1][1]): if (required <= 0.0): break (val, rate) = v take = min(val, required) output.action("Move %.2f from %s to emergency fund." % (take, n)) a.reduce(n, take, rate) required -= take self.allocation['Emergency Fund'] += take if (required > 0.0): output.warn( "Need monthly budget to build remaining emergency fund %.2f." % (required)) months = int((required + b.get_monthly()) / b.get_monthly()) #print(" No. of months - %d" % (months)) output.action( "You need to first build your emergency fund for the next %d months." % (months)) self.m_for_ef_debt = months self._b.add_expense("Emergency Fund", b.get_monthly()) self._b.report() #quit() else: output.info("Your emergency fund is built now.") output.info("ANALYSIS - Done allocating emergency fund....") output.section_end()
def process_tx(self, txid): transaction = self.gettransaction(txid) tx_conf = transaction["confirmations"] if len(transaction["details"]) > 1: tx_account = transaction["details"][1]["account"] tx_amount = float(transaction["details"][1]["amount"]) tx_category = transaction["details"][1]["category"] else: tx_account = transaction["details"][0]["account"] tx_amount = float(transaction["details"][0]["amount"]) tx_category = transaction["details"][0]["category"] if tx_conf > 0: output.info("{} tx has confirmed, removing...".format(tx_category)) self.remove_tx_db(tx_account, tx_amount, txid, tx_category) else: output.info("{} tx has 0 confs, adding to unconfirmed...".format( tx_category)) self.add_tx_db(tx_account, tx_amount, txid, tx_category)
def _accept_conns(self): """ Background thread accepts client connections """ info("Listening for connections...") for c in self.connections: c.close() self.connections = [] self.addresses = [] while 1: try: conn, addr = self.socket.accept() conn.setblocking(1) hostname = conn.recv(1024).decode("utf-8") address = addr + (hostname, ) except Exception as e: error("Failed accepting connections", e[0]) continue self.connections.append(conn) self.addresses.append(address) good("Connection established from %s (%s)" % (addr[-1], addr[0]))
def live_below_means(self): print("\n") output.section_start("Its good to live within your means...") output.info("ANALYSIS - Checking living below means....") excess = self._b.get_monthly() if (self._b.get_monthly() <= 0.0): output.warn("Live below your means!!") output.action( "You need to reduce your expenses by at least $%.2f" % (-(excess))) return False else: output.info("You are living below your means by $%.2f" % (excess)) output.info("ANALYSIS - Done living below means....") output.section_end() return True
async def on_channel_delete(channel): Mysql.remove_channel(channel) output.info("Channel {0} deleted from {1}".format(channel.name, channel.server.name))
async def on_channel_create(channel): if isinstance(channel, discord.PrivateChannel): return Mysql.add_channel(channel) output.info("Channel {0} added to {1}".format(channel.name, channel.server.name))
async def on_server_leave(server): Mysql.remove_server(server) output.info("Removed from {0}".format(server.name))
async def on_server_join(server): output.info("Added to {0}".format(server.name)) Mysql.add_server(server) for channel in server.channels: Mysql.add_channel(channel)
async def on_server_join(server): output.info("Added to {0}".format(server.name))
def check_pay_debt(self): print("\n") output.section_start("Debt free life means Freedom...") output.info("ANALYSIS - Checking your debt and a payoff plan....") # check for consumer debt d = self._d.unknown b = self._b a = self._a total = 0.0 self.allocation['Debt Payoff'] = 0.0 debt_payment = 0.0 for n, v in d.items(): (val, rate, y) = v if (rate > HIGH_INTEREST_RATE): output.warn("High interest rate for %s: $%.2f @ %.2f" % (n, val, rate)) total += val debt_payment += self._d.payment[n] if (total == 0.0): output.info("Congratulations - You are debt free.") output.info("You can invest %.2f per month and grow your assets." % (b.get_monthly())) output.info("Your current assets") a.report("Assets_after_debt_free") else: #print("\n") output.action("Pay the debt $%.2f in order - " % (total)) for n, v in sorted(d.items(), key=lambda x: x[1][0]): print(" n:%s rate:%.2f value:$%.2f" % (n, v[1], v[0])) # check assets for paying off debt for n, v in sorted(a.data.items(), key=lambda x: x[1][1]): if (total <= 0.0): break (val, rate) = v if (val <= 0.0): continue take = min(val, total) output.action("Use the %s to pay off debt with value $%.2f" % (n, take)) total -= val a.reduce(n, take, rate) self.allocation['Debt Payoff'] += take #print("\n") output.info("Assets after paying off debt.") a.report("Assets_after_paying_off_debt") if (total > 0.0): if (b.get_monthly() <= 0.0): if (self.surplus > 0.0): output.warn( "You can pay off debt only after the emergency fund is built." ) output.action( "Need monthly budget $%.2f to pay off remaining debt $%.2f" % (self.surplus, total)) months = int((total + self.surplus) / self.surplus) self.m_for_ef_debt += months output.info("You will be debt free in %d months." % (self.m_for_ef_debt)) output.info( "You will save %s%.2f of debt payments every month." % (utils.get_currency(), debt_payment)) self.surplus += debt_payment else: output.warn( "You do not have surplus left in your budget to pay off debt. Reduce your expenses." ) else: output.action( "Need monthly budget $%.2f to pay off remaining debt $%.2f" % (b.get_monthly(), total)) months = int((total + b.get_monthly()) / b.get_monthly()) print(" No. of months - %d" % (months)) output.info("You will be debt free in %d months." % (months)) output.info( "You will save %s%.2f of debt payments every month." % (utils.get_currency(), debt_payment)) self.m_for_ef_debt = months self._b.add_expense("Debt Payoff", b.get_monthly()) self.surplus += debt_payment else: output.info("You can be debt-free now.") output.info("ANALYSIS - Done debt payoff plan....") output.section_end()
def grow_assets(self): print("\n") output.section_start("Building wealth steadily is not difficult...") output.info("ANALYSIS - Projecting growth of assets") p = self._p b = self._b a = self._a x = list() y = list() y_ = list() start = p.getCurrentAge() + (self.m_for_ef_debt / 12) monthly_surplus = b.get_monthly() if (start > p.getCurrentAge()): output.info( "You can start investing only at the age of %d years after emergency fund and/or debt payoff." % (start)) monthly_surplus = self.surplus if (start > p.getRetireAge()): output.warn( "Unfortunately time to pay off debt or building emergency fund exceeds your retirement age %d." % (p.getRetireAge())) output.warn("You need to delay your retirement by few more years.") quit() time_to_grow = p.getRetireAge() - p.getCurrentAge() - ( self.m_for_ef_debt / 12) risk = p.getRiskNumber() # Take 401k etc. into account monthly_surplus += (self._i.deductions) / 12 output.info( "Your assets will grow in next %.2f years if you regularly invest %s%.2f every month" % (time_to_grow, utils.get_currency(), monthly_surplus)) output.info("Invest %.2f per month for next %.2f years" % (monthly_surplus, time_to_grow)) d = dict() d = a.data.copy() t = utils.fv(d, monthly_surplus / len(d), time_to_grow) if (t > 100000): output.info("You will be a MILLIONAIRE") else: if (t > 900000): output.info("You will be very close to a millionaire") utils.report( "If you invest %s%.2f regularly, your assets will be" % (utils.get_currency(), monthly_surplus), d, t) utils.piechart("FV_regular", "Future Value of Assets if you invest regularly", [n for n, v in d.items()], [v for n, v in d.items()]) e = dict() e = a.data.copy() t = utils.fv(e, 0.0, time_to_grow) utils.report( "If you do not invest the surplus, your assets will remain", e, t) utils.piechart("FV_static", "Future Value of Assets if you do not invest anymore", [n for n, v in e.items()], [v for n, v in e.items()]) output.info("ANALYSIS - Asset projection done....") x = [i for i in range(1, int(time_to_grow))] for j in x: f = a.data.copy() y.append(utils.fv(f, monthly_surplus / len(f), j)) f = a.data.copy() y_.append(utils.fv(f, 0.0, j)) #print(x, y, y_) output.section_end() # update self.surplus for asset allocation self.surplus = monthly_surplus return x, y, y_
def allocate(self): output.section_start( "Mortgage payoff calculation and projection at retirement") equity = 0.0 debt = 0.0 for n, v in self.d.items(): (val, rate, years) = v home_equity, home_debt = utils.mortgage_payment( val, int(self.t * 12), rate, years) equity += home_equity debt += home_debt output.action( "Keep paying your mortgage as regular to build home equity") output.section_end() assets = self.a.total allocation = dict() equity_percent = self.p.data['risk aversion'] bond_percent = 100 - equity_percent output.section_start( "Investing your assets with chosen asset allocation %d:%d (stocks:bonds)" % (equity_percent, bond_percent)) allocation['equity'] = (assets * equity_percent / 100, STOCK_GROWTH_RATE) allocation['bond'] = (assets * bond_percent / 100, BOND_GROWTH_RATE) output.action( "Re-balance your assets of %s%.2f as %d_%d (stocks_bonds)" % (utils.get_currency(), assets, equity_percent, bond_percent)) utils.piechart("Asset_allocated_now", "Asset allocation now", [n for n, v in allocation.items()], [v[0] for n, v in allocation.items()]) invest = dict() invest['equity'] = self.s * equity_percent / 100 invest['bond'] = self.s * bond_percent / 100 total = utils.fv_allocation(allocation, invest, self.t) allocation['real estate'] = (equity) total += equity output.action("Invest %s%.2f per month for %.2f years" % (utils.get_currency(), self.s, self.t)) output.info("Total assets with proper allocation: %s%.2f" % (utils.get_currency(), total)) output.info("Total debt at retirement: %s%.2f" % (utils.get_currency(), debt)) output.info("Net worth: %s%.2f" % (utils.get_currency(), (total - debt))) utils.piechart("Assets_in_%d_years" % (self.t), "Assets in %d years" % (self.t), [n for n, v in allocation.items()], [v for n, v in allocation.items()]) net_worth = total - debt output.action( "Preserve your net worth %s%.2f by moving to safer assets" % (utils.get_currency(), net_worth)) expense = self.e.get_monthly() years = net_worth / (expense * 12) output.info( "Your net worth will last %d years if you spend %s%.2f monthly as of today." % (years, utils.get_currency(), expense)) if ((years + self.p.getRetireAge()) > LIFE_EXPECTANCY): output.info( "You have a secure retirement considering life expectancy of %d years" % (LIFE_EXPECTANCY)) output.action( "Enjoy your retirement with %s%.2f, withdraw %s%.2f per month." % (utils.get_currency(), net_worth, utils.get_currency(), expense)) else: output.warn( "You will not have enough corpus to last a retired life expectancy of %d years" % (LIFE_EXPECTANCY)) output.action("You need to save more or reduce your expenses") output.section_end()
def report(self): output.info("Your net worth is %s%.2f" % (utils.currency_symbol, self.metrics["Net worth"])) utils.report("Metrics", self.ratios, 0.0, pre="", post="%")
"Tx has been removed, adding to user's balance/staked...") self.check_for_user(tx_account) self.get_db(tx_account, tx_amount, txid, tx_category) def process_tx(self, txid): transaction = self.gettransaction(txid) tx_conf = transaction["confirmations"] if len(transaction["details"]) > 1: tx_account = transaction["details"][1]["account"] tx_amount = float(transaction["details"][1]["amount"]) tx_category = transaction["details"][1]["category"] else: tx_account = transaction["details"][0]["account"] tx_amount = float(transaction["details"][0]["amount"]) tx_category = transaction["details"][0]["category"] if tx_conf > 0: output.info("{} tx has confirmed, removing...".format(tx_category)) self.remove_tx_db(tx_account, tx_amount, txid, tx_category) else: output.info("{} tx has 0 confs, adding to unconfirmed...".format( tx_category)) self.add_tx_db(tx_account, tx_amount, txid, tx_category) if __name__ == "__main__": txid = str(sys.argv[1]) notify = Walletnotify() output.info("Received new tx!") notify.process_tx(txid)