def activate_coach(coach=None, card_ids=None): """Activates coach and copies cards in card_ids list to new season""" if not coach: raise ValueError("coach argument is empty") if not isinstance(coach, Coach): raise TypeError("coach is not of class Coach") if coach.active(): raise ValueError("coach is already active") if not isinstance(card_ids, list): card_ids = [] selected_cards = Card.query.join(Card.coach).\ filter(Coach.id == coach.id, Card.id.in_(card_ids)).\ all() selected_card_ids = [card.id for card in selected_cards] missing = [id for id in card_ids if id not in selected_card_ids] if missing: raise ValueError( f"Not all card IDs were found - {str(missing)[1:-1]}") total_value = sum([ card.template.value for card in selected_cards if card.template.rarity != "Unique" ]) if total_value > 35: raise ValueError(f"Total value is higher than 35!!!") selected_card_names = [card.template.name for card in selected_cards] pack = PackService.admin_pack(card_names=selected_card_names, coach=coach) reason = "Account activation - Admin Transfer Pack" tran = Transaction(pack=pack, description=reason, price=0) coach.activate() coach.make_transaction(tran) pack = PackService.new_starter_pack(coach=coach) reason = "Account activation - Starter Pack" tran = Transaction(pack=pack, description=reason, price=0) coach.make_transaction(tran) coach.account.reset() db.session.commit() #late joiner bonus CoachService.award_bonus(coach) coach.high_command.reset() db.session.commit() return True
def process(cls, coach, amount, reason): t = Transaction(description=reason, price=amount) coach.make_transaction(t) NotificationService.notify( f"<@{coach.disc_id}>: Your bank has been updated by **{-1*amount}** coins - {reason}" ) return True
async def adminbank(self, ctx, amount: int, coach_name: str, *reason): """Add or remove cash from coach USAGE: !adminbank <amount> <coach> <reason> <amount>: number of coins to add to bank, if negative is used, it will be deducted from bank <coach>: coach discord name or its part, must be unique <reason>: describe why you are changing the coach bank """ self.is_admin_channel(ctx.channel) coach = await coach_unique(coach_name, ctx) if coach is None: return reason = ' '.join(reason) + " - updated by " + str(ctx.author.name) tran = Transaction(description=reason, price=-1 * amount) coach.make_transaction(tran) msg = [ f"Bank for {coach.name} updated to **{coach.account.amount}** coins:\n", f"Note: {reason}\n", f"Change: {amount} coins" ] await self.send_message(ctx.channel, msg) await self.bank_notification( ctx, f"Your bank has been updated by **{amount}** coins - {reason}", coach)
async def reaction(self, ctx, *card_name): """User reaction card USAGE: !reaction <card_name> <card_name>: name of the reaction card """ coach = CoachService.discord_user_to_coach(ctx.author) room = ctx.channel.name if coach is None: await ctx.send( f"Coach {ctx.author.mention} does not exist. Use !newcoach to create coach first." ) return get_coach_deck_for_room_or_raise(room, coach) card_name = " ".join(card_name).strip() card = CardService.get_card_from_coach(coach, card_name) if card and card.template.card_type == "Reaction": msg = [ f"**{coach.short_name()}** plays **{card.get('name')}**: {card.get('description')}" ] notification = f"Card **{card.get('name')}** removed from your collection" db.session.delete(card) db.session.expire(coach, ['cards']) reason = f"Reaction card {card.template.name} used in {room} tournament" tran = Transaction(description=reason, price=0) coach.make_transaction(tran) await self.send_message(ctx.channel, msg) await self.bank_notification(ctx, notification, coach) else: raise ValueError(f"Reaction card {card_name} was not found!!!") return
def process(cls, coach, amount, reason): """Process transaction and notifies the coach on discord""" transaction = Transaction(description=reason, price=amount) coach.make_transaction(transaction) msg = f"<@{coach.disc_id}>: Your bank has been updated by **{-1*amount}** coins - {reason}" Notificator("bank").notify(msg) return True
def unregister(cls,tournament,coach,admin=False,refund=True): # check for status if tournament.status not in ["OPEN","FINISHED"] and not admin: raise RegistrationError(f"Coach cannot resign from running tournament!!!") # check if coach is registered ts = TournamentSignups.query.filter_by(tournament_id= tournament.id, coach_id = coach.id).all() if len(ts)<1: raise RegistrationError(f"Coach {coach.short_name()} is not registered to {tournament.name}!!!") try: db.session.delete(ts[0]) if refund: reason = f"{tournament.name} resignation - refund {tournament.fee} coins" t = Transaction(description=reason,price=-1*tournament.fee) coach.make_transaction(t) db.session.commit() if refund and tournament.fee>0: coach_mention=f'<@{coach.disc_id}>' fee_msg = f" - refund {tournament.fee} coins" else: coach_mention=coach.short_name() fee_msg="" NotificationService.notify(f'{coach_mention} successfuly resigned from {tournament.id}. {tournament.name}{fee_msg}') except Exception as e: raise RegistrationError(str(e)) return True
def new_coach(name, discord_id): coach = Coach.create(str(name), discord_id) pack = PackService.new_starter_pack(coach=coach) tran = Transaction(pack=pack, price=pack.price, description=PackService.description(pack)) coach.make_transaction(tran) CoachService.award_bonus(coach) return coach
def register(cls,tournament,coach,admin=False): # check for status if tournament.status != "OPEN" and not admin: raise RegistrationError(f"Tournamnent {tournament.name} signups are not open!!!") # check if coach is not registered ts = TournamentSignups.query.filter_by(tournament_id= tournament.id, coach_id = coach.id).all() if len(ts)>0: raise RegistrationError(f"Coach {coach.short_name()} is already registered to {tournament.name}!!!") # check if the coach is not signed to multiple tournaments, only exception is FastTrack Dev and Boot/Regular Development if tournament.type=="Imperium": ts = coach.tournaments.filter_by(type="Imperium").all() if len(ts)>0: raise RegistrationError(f"Coach cannot be registered to more than 1 Imperium tournament!!!") else: ts = coach.tournaments.filter(Tournament.type!="Imperium").all() if len(ts)>1: raise RegistrationError(f"Coach cannot be registered to more than 2 Development tournaments!!!") if len(ts)==1: etour = ts[0] if not ((etour.mode=="Boot Camp" or etour.mode=="Regular") and tournament.mode=="Fast-Track") and not ((tournament.mode=="Boot Camp" or tournament.mode=="Regular") and etour.mode=="Fast-Track"): raise RegistrationError(f"Coach cannot be registered to {tournament.type} {tournament.mode} tournament and {etour.type} {etour.mode} tournament at the same time!!!") # check for free slots signups = tournament.coaches.filter(TournamentSignups.mode != 'reserve').all() reserves = tournament.coaches.filter(TournamentSignups.mode == 'reserve').all() if len(signups) == tournament.coach_limit: if len(reserves) == tournament.reserve_limit: raise RegistrationError(f"{tournament.name} is full !!!") else: register_as = "reserve" else: register_as = "active" # tournament is open, has free slot and coach is not signed to it yet try: signup = TournamentSignups(mode=register_as) signup.coach = coach signup.tournament = tournament db.session.add(signup) reason = f"{tournament.name} signup - cost {tournament.fee} coins" t = Transaction(description=reason,price=tournament.fee) coach.make_transaction(t) db.session.commit() if tournament.fee>0: coach_mention=f'<@{coach.disc_id}>' else: coach_mention=coach.short_name() NotificationService.notify(f'{coach_mention} successfuly signed to {tournament.id}. {tournament.name} - fee {tournament.fee} coins') except Exception as e: raise RegistrationError(str(e)) return signup
def unregister(cls, tournament, coach, admin=False, refund=True): """ Unregister coach from tournament, admin flag for admin action, refund flag if it should be refunded """ # check for status if tournament.status not in ["OPEN", "FINISHED"] and not admin: raise RegistrationError( f"Coach cannot resign from running tournament!!!") # check if coach is registered signups = TournamentSignups.query \ .filter_by(tournament_id=tournament.id, coach_id=coach.id).all() if not signups: raise RegistrationError( f"Coach {coach.short_name()} is not registered to {tournament.name}!!!" ) try: # collection cards for card in signups[0].deck.cards: if refund: card.decrement_use() if tournament.type == "Development": card.in_development_deck = False else: card.in_imperium_deck = False # squad cards if refund: for card in signups[0].deck.squad.cards: card.decrement_use() db.session.delete(signups[0]) if refund: reason = f"{tournament.name} resignation - refund {tournament.fee} coins" tran = Transaction(description=reason, price=-1 * tournament.fee) coach.make_transaction(tran) db.session.commit() if refund and tournament.fee > 0: coach_mention = f'<@{coach.disc_id}>' fee_msg = f"Refund: {tournament.fee} coins" else: coach_mention = coach.short_name() fee_msg = "" Notificator("bank").notify( f'{coach_mention} successfuly resigned from tournament. {fee_msg}' ) except Exception as exp: raise RegistrationError(str(exp)) return True
async def auto_cards(cls, pack, ctx): """Routine to process auto cards from the pack""" for card in pack.cards: if card.get('name') in AUTO_CARDS.keys(): reason = "Autoprocessing " + card.get('name') amount = AUTO_CARDS[card.get('name')] msg = f"Your card {card.get('name')} has been processed. You were granted {amount} coins" tran = Transaction(description=reason, price=-1 * amount) db.session.delete(card) pack.coach.make_transaction(tran) await cls.bank_notification(ctx, msg, pack.coach) return
def level(coach): """Level high command""" hc = coach.high_command # check if max level if len(HC_PRICES) == hc.level - 1: raise HighCommandError(MAX_LEVEL_ERROR) hc.level += 1 reason = f"Updated High Command to level {hc.level}" tran = Transaction(description=reason, price=HC_PRICES[hc.level - 2]) coach.make_transaction(tran) Notificator("bank").notify(f"{coach.short_name()}: {reason}") return True
def commit_duster(cls,coach): duster = cls.get_duster(coach) if len(duster.cards)<10: raise DustingError("Not enough cards flagged for dusting. Need 10!!!") reason = f"{duster.type}: {';'.join([card.name for card in duster.cards])}" t = Transaction(description=reason,price=0) cards = duster.cards for card in cards: db.session.delete(card) duster.status="COMMITTED" coach.make_transaction(t) NotificationService.notify(f"<@{coach.disc_id}>: Card(s) **{' ,'.join([card.name for card in cards])}** removed from your collection by {duster.type}") return True
async def ransom(self, ctx): """Pay ransom for the kidnapped player""" coach = CoachService.discord_user_to_coach(ctx.author) if coach is None: await ctx.send( f"Coach {ctx.author.mention} does not exist. Use !newcoach to create coach first." ) return reason = 'Ransom' amount = -5 tran = Transaction(description=reason, price=-1 * amount) coach.make_transaction(tran) msg = [ f"Bank for {coach.name} updated to **{coach.account.amount}** coins:\n", f"Note: {reason}\n", f"Change: {amount} coins" ] await self.send_message(ctx.channel, msg) await self.bank_notification( ctx, f"Your bank has been updated by **{amount}** coins - {reason}", coach) return
from web import db, create_app from models.data_models import Coach, Account, Transaction, Pack, Card import imperiumbase as ib from datetime import datetime app = create_app() app.app_context().push() # for each coach for coach_data in ib.Coach.all(): coach = Coach(name=coach_data.name) acc = Account(amount=coach_data.account.cash, coach=coach) for transaction in coach_data.account.transactions: tr = Transaction(confirmed=transaction.confirmed, price=transaction.price) tr.date_created = datetime.utcfromtimestamp(transaction.created_at) tr.date_confirmed = datetime.utcfromtimestamp(transaction.confirmed_at) if isinstance(transaction.comodity, ib.Pack): tr.description = transaction.comodity.description() p = transaction.comodity if hasattr(p, 'team'): team = p.team else: team = None pack = Pack(pack_type=p.pack_type, price=p.price, team=team) pack.coach = coach pack.transaction = tr for card in p.cards: cc = Card(name=card["Card Name"], description=card["Description"], card_type=card["Type"],
def process(cls, order): stock_modifier = 1 app = db.get_app() if order.operation == "buy": # sets the order stock price at the time of processing order.share_price = order.stock.unit_price funds = order.user.account().amount if order.buy_funds and order.buy_funds < funds: funds = order.buy_funds if order.stock.unit_price: share = Share.query.join(Share.user, Share.stock).filter( User.id == order.user.id, Stock.id == order.stock.id).one_or_none() shares = funds // order.stock.unit_price # if shares limited and they are less than max use them instead if order.buy_shares and shares > order.buy_shares: shares = order.buy_shares possible_shares = app.config['MAX_SHARE_UNITS'] if share: possible_shares -= share.units if possible_shares < shares: shares = possible_shares order.final_shares = shares order.final_price = shares * order.stock.unit_price if shares: if share: share.units = Share.units + shares else: share = Share() share.stock = order.stock share.user = order.user share.units = shares order.success = True order.result = f"Bought {order.final_shares} {order.stock.code} share(s) for {round(order.final_price, 2)} {app.config['CREDITS']}" tran = Transaction(order=order, price=order.final_price, description=order.result) else: order.success = False order.result = f"Not enough funds to buy any shares of {order.stock.code} or {app.config['MAX_SHARE_UNITS']} share limit reached" else: order.success = False order.result = "Cannot buy stock with 0 price" order.processed = True if order.operation == "sell": stock_modifier = -1 # sets the order stock price at the time of processing order.share_price = order.stock.unit_price share = Share.query.join(Share.user, Share.stock).filter( User.id == order.user.id, Stock.id == order.stock.id).one_or_none() if share: units = share.units left = False if order.sell_shares and order.sell_shares < units: units = order.sell_shares left = True funds = units * order.stock.unit_price order.final_shares = units order.final_price = funds share.units = Share.units - units if not left: db.session.delete(share) order.success = True order.result = f"Sold {order.final_shares} {order.stock.code} share(s) for {round(order.final_price, 2)} {app.config['CREDITS']}" tran = Transaction(order=order, price=-1 * order.final_price, description=order.result) else: order.success = False order.result = f"No shares of {order.stock.code} left to sell" order.processed = True if order.success: try: order.user.make_transaction(tran) except TransactionError as exc: order.success = False order.result = str(exc) order.stock.change_units_by(stock_modifier * order.final_shares) db.session.commit() return order
async def admincard(self, ctx, action: str, coach_name: str = None, *cards): """Adds or removes cards from coach, or updates card database USAGE 1: Add or remove cards from coach !admincard <action> <coach> <card>;...;<card> <action>: add or remove <coach>: coach discord name or its part, must be unique <card>: Exact card name as is in the All Cards list, if mutliple cards are specified separate them by **;** USAGE 2: Updates card database from the master sheet !admincard update """ if action not in ["add", "remove", "update"]: raise ValueError("Incorrect action") if not cards and not coach_name and action in ["add", "remove"]: raise ValueError("Missing arguments") if action == "update": await ctx.send(f"Updating...") CardService.update() await ctx.send(f"Cards updated!!!") return else: coach = await coach_unique(coach_name, ctx) if coach is None: return card_names = [card.strip() for card in " ".join(cards).split(";")] if action == "add": pack = PackService.admin_pack(0, card_names, coach) # situation when some of the cards could not be found if len(card_names) != len(pack.cards): msg = [] msg.append(f"Not all cards were found, check the names!!!\n") for card in card_names: if card in [ card.get('name').lower() for card in pack.cards ]: found = True else: found = False found_msg = "**not found**" if not found else "found" msg.append(f"{card}: {found_msg}") await self.send_message(ctx.channel, msg) return reason = f"{action.capitalize()} {';'.join([str(card.get('name')) for card in pack.cards])} - by " + str( ctx.author.name) tran = Transaction(pack=pack, description=reason, price=0) coach.make_transaction(tran) msg = [] msg.append( f"**{PackService.description(pack)}** for @{coach.name} - **{pack.price}** coins:\n" ) # message sent to admin so display the hidden cards msg.append( f"{PackHelper.format_pack(pack.cards, show_hidden=True)}") msg.append(f"**Bank:** {coach.account.amount} coins") await self.send_message(ctx.channel, msg) # message sent to discord so hide the names await self.bank_notification( ctx, f"Card(s) **{', '.join([card.get('name', show_hidden=False) for card in pack.cards])}** added to your collection by {str(ctx.author.name)}", coach) await self.auto_cards(pack, ctx) CoachService.check_collect_three_legends_quest(coach) return if action == "remove": removed_cards = [] unknown_cards = [] for name in card_names: card = CardService.get_card_from_coach(coach, name) if card: removed_cards.append(card) db.session.delete(card) db.session.expire(coach, ['cards']) else: unknown_cards.append(name) reason = f"{action.capitalize()} {';'.join([card.get('name') for card in removed_cards])} - by " + str( ctx.author.name) tran = Transaction(description=reason, price=0) coach.make_transaction(tran) if removed_cards: msg = [] msg.append(f"Cards removed from @{coach.name} collection:\n") msg.append( f"{PackHelper.format_pack(removed_cards, show_hidden=True)}" ) await self.send_message(ctx.channel, msg) await self.bank_notification( ctx, f"Card(s) **{', '.join([card.get('name') for card in removed_cards])}** removed from your collection by {str(ctx.author.name)}", coach) if unknown_cards: msg = ["**Warning** - these cards have been skipped:"] for name in unknown_cards: msg.append(f"{name}: **not found**") await self.send_message(ctx.channel, msg) return
def register(cls, tournament, coach, admin=False): """Register coach to tournament, admin flag specifies if admin is doing the action""" # check for status if tournament.status != "OPEN" and not admin: raise RegistrationError( f"Tournamnent {tournament.name} signups are not open!!!") # check if coach is not registered singups = TournamentSignups.query.filter_by( tournament_id=tournament.id, coach_id=coach.id).all() if singups: raise RegistrationError( f"Coach {coach.short_name()} is already registered to {tournament.name}!!!" ) # check if the coach is not signed to multiple tournaments # only exception is FastTrack Dev and Boot/Regular Development if tournament.type == "Imperium": singups = coach.tournaments.filter_by(type="Imperium").all() if singups: raise RegistrationError( f"Coach cannot be registered to more than 1 Imperium tournament!!!" ) # Dev tournaments limited to 1 for Fast Tracks and 2 for Regulars elif tournament.type == "Development": if tournament.mode == "Fast Track": singups = coach.tournaments.filter( Tournament.type == "Development", Tournament.mode == "Fast Track").all() if singups: raise RegistrationError( f"Coach cannot be registered to more than \ 1 Fast Track Development tournament!!!") if tournament.mode == "Boot Camp": singups = coach.tournaments.filter( Tournament.type == "Development", Tournament.mode == "Regular").all() if singups: raise RegistrationError( f"Coach cannot be registered to Boot Camp and Regular Development tournament at the same time!!!" ) if tournament.mode == "Regular": singups = coach.tournaments.filter( Tournament.type == "Development", Tournament.mode == "Regular").all() if len(singups) > 1: raise RegistrationError( f"Coach cannot be registered to more \ than 2 Regular Development tournaments!!!") singups = coach.tournaments.filter( Tournament.type == "Development", Tournament.mode == "Boot Camp").all() if singups: raise RegistrationError( f"Coach cannot be registered to Boot Camp \ and Regular Development tournament at the same time!!!" ) # check for free slots signups = tournament.coaches.filter( TournamentSignups.mode != 'reserve').all() reserves = tournament.coaches.filter( TournamentSignups.mode == 'reserve').all() if len(signups) == tournament.coach_limit: if len(reserves) == tournament.reserve_limit: raise RegistrationError(f"{tournament.name} is full !!!") register_as = "reserve" else: register_as = "active" # tournament is open, has free slot and coach is not signed to it yet try: signup = TournamentSignups(mode=register_as) signup.coach = coach signup.tournament = tournament db.session.add(signup) reason = f"{tournament.name} signup - cost {tournament.fee} coins" tran = Transaction(description=reason, price=tournament.fee) # deck deck = Deck(team_name="", mixed_team="", tournament_signup=signup) db.session.add(deck) # high command hc = HighCommandSquad() hc.command = coach.high_command hc.deck = deck db.session.add(hc) coach.make_transaction(tran) if tournament.fee > 0: coach_mention = f'<@{coach.disc_id}>' fee_msg = f'Fee: {tournament.fee} coins' else: coach_mention = coach.short_name() fee_msg = "" Notificator("bank").notify( f'{coach_mention} successfuly signed to tournament. {fee_msg}') # if tournament is full initiate update in extra thread, this will recreate free tournaments if needed if tournament.is_full(): Notificator("admin").notify("!admincomp update") except Exception as exc: raise RegistrationError(str(exc)) return signup
async def __run_admin(self): # if not started from admin-channel if not self.__class__.is_admin_channel(self.message.channel): await self.reply([f"Insuficient rights"]) return if self.args[0] == "!adminstock": if len(self.args) != 2: await self.reply([f"Wrong number of parameters"]) return if self.args[1] not in ["update"]: await self.reply( [f"Wrong parameter - only *update* is allowed"]) return await self.short_reply("Updating...") StockService.update() await self.short_reply("Done") if self.args[0] == "!adminmarket": if len(self.args) != 2: await self.reply([f"Wrong number of parameters"]) return if self.args[1] not in ["close", "open", "status"]: await self.reply([ f"Wrong parameter - only *status*, *open* and *close* are allowed" ]) return if self.args[1] == "open": OrderService.open() msg = "Done" if self.args[1] == "close": OrderService.close() msg = "Done" if self.args[1] == "status": if OrderService.is_open(): msg = "Market is open" else: msg = "Market is closed" await self.short_reply(msg) if self.args[0] == "!adminlist": # require username argument if len(self.args) == 1: await self.reply(["Username missing"]) return users = User.find_all_by_name(self.args[1]) msg = [] if not users: msg.append("No users found") await self.reply(msg) for user in users: msg1, msg2, msg3, msg4 = self.list_messages(user) await self.reply(msg1) await self.reply(msg2, block=True) await self.reply(msg3) await self.reply(msg4, block=True) if self.args[0] == '!adminbank': # require username argument if len(self.args) < 4: await self.reply(["Not enough arguments!!!\n"]) await self.short_reply(self.__class__.adminbank_help()) return # amount must be int if not is_number(self.args[1]) or float(self.args[1]) > 100000000: await self.reply( ["<amount> is not number or is too high!!!\n"]) return user = await self.user_unique(self.args[2]) if user is None: return amount = float(self.args[1]) reason = ' '.join( str(x) for x in self.message.content.split(" ") [3:]) + " - updated by " + str(self.message.author.name) tran = Transaction(description=reason, price=-1 * amount) try: user.make_transaction(tran) except TransactionError as e: await self.transaction_error(e) return else: msg = [ f"Bank for {user.name} updated to **{round(user.account().amount,2)}** {app.config['CREDITS']}:\n", f"Note: {reason}\n", f"Change: {amount} {app.config['CREDITS']}" ] await self.reply(msg) await self.bank_notification( f"Your bank has been updated by **{amount}** {app.config['CREDITS']} - {reason}", user) return if self.args[0] == '!adminshare': # require username argument if len(self.args) < 5: await self.reply(["Not enough arguments!!!\n"]) await self.short_reply(self.__class__.adminshare_help()) return stocks = Stock.query.filter_by(code=self.args[1]).all() if not stocks: await self.short_reply( f"<stock> __{self.args[1]}__ not found!!!") return if len(stocks) > 1: emsg = f"<stock> __{name}__ is not **unique**!!!\n" emsg += "Select one: " for stock in stocks: emsg += stock.code emsg += " " await self.short_reply(emsg) return stock = stocks[0] # amount must be int if not represents_int(self.args[2]) or int( self.args[2]) > app.config['MAX_SHARE_UNITS']: await self.reply([ f"{self.args[2]} is not whole number or is higher than {app.config['MAX_SHARE_UNITS']}!!!\n" ]) return user = await self.user_unique(self.args[3]) if user is None: return amount = int(self.args[2]) reason = ' '.join( str(x) for x in self.message.content.split(" ") [4:]) + " - updated by " + str(self.message.author.name) tran = Transaction(description=reason, price=0) try: if amount > 0: done = StockService.add(user, stock, amount) else: done = StockService.remove(user, stock, -1 * amount) if not done: await self.short_reply( f"User {user.short_name()} does not own any shares of __{self.args[1].upper()}__!!!" ) return user.make_transaction(tran) except TransactionError as e: await self.transaction_error(e) return else: msg = [ f"{stock.code} shares for {user.name} has been updated.\n", f"Note: {reason}\n", f"Change: {amount} shares" ] await self.reply(msg) await self.bank_notification( f"Your {stock.code} shares has been updated by **{amount}** - {reason}", user) return if self.args[0] == '!adminpoints': # require username argument if len(self.args) < 4: await self.reply(["Not enough arguments!!!\n"]) await self.short_reply(self.__class__.adminpoints_help()) return # amount must be int if not represents_int(self.args[1]): await self.reply([f"{self.args[1]} is not whole number!!!\n"]) return user = await self.user_unique(self.args[2]) if user is None: return amount = int(self.args[1]) reason = ' '.join( str(x) for x in self.message.content.split(" ") [3:]) + " - updated by " + str(self.message.author.name) try: user.award_points(amount, reason) db.session.commit() except Exception as e: await self.transaction_error(e) return else: msg = [ f"Points for {user.name} has been updated.\n", f"Note: {reason}\n", f"Change: {amount} points" ] await self.reply(msg) await self.bank_notification( f"Your points has been updated by **{amount}** - {reason}", user) return
def award_bonus(coach): bonus = CoachService.late_join_bonus(datetime_start()) if bonus > 0: tran = Transaction(description="Latejoiner bonus", price=-1 * bonus) coach.make_transaction(tran)
async def genpack(self, ctx, pack_type:str, subtype:str=None): """Generates packs""" if not check_gen_command(pack_type, subtype): raise discord.ext.commands.CommandError("Invalid usage!") coach = CoachService.discord_user_to_coach(ctx.author) if coach is None: await ctx.send(f"Coach {ctx.author.mention} does not exist. Use !newcoach to create coach first.") return pp_count = db.session.query(Pck.id).filter_by(coach_id=coach.id, pack_type="player").count() if pack_type == "player": first = True if pp_count == 0 else False pack = PackService.generate(pack_type, team=subtype, first=first, coach=coach) elif pack_type in ["training","special", "hc"]: pack = PackService.generate(pack_type, coach=coach) elif pack_type == "booster": pack_type = "booster_budget" if not subtype else f"booster_{subtype}" pack = PackService.generate(pack_type, coach=coach) duster = coach.duster duster_on = False duster_txt = "" if pp_count > 0 and duster and duster.status == "COMMITTED": if (pack_type == "player" and duster.type == "Tryouts" or pack_type == "training" and duster.type == "Drills" or pack_type == "special" and duster.type == "Drills"): duster_on = True duster_txt = f" ({duster.type})" db.session.delete(duster) free_packs = coach.get_freepacks() if pack_type in ["player"] and not duster_on: if pack_type in free_packs: pack.price = 0 coach.remove_from_freepacks(pack_type) else: raise TransactionError( "You need to commit Tryouts or earn the pack through" + " Achievements to be able to generate this pack!" ) if pack_type in ["training", "special"] and not duster_on: raise TransactionError( "You need to commit Drills to be able to generate this pack!" ) if pack_type in ["booster_budget", "booster_premium"]: if pack_type in free_packs: pack.price = 0 coach.remove_from_freepacks(pack_type) tran = Transaction(pack=pack, price=pack.price, description=PackService.description(pack)) coach.make_transaction(tran) title = f"**{PackService.description(pack)}** for **{ctx.message.author.name}** - **{pack.price}** coins{duster_txt}" description = f"**Bank:** {coach.account.amount} coins" pieces = PackHelper.format_pack_to_pieces(pack.cards) await self.auto_cards(pack, ctx) CoachService.check_collect_three_legends_quest(coach) efs = [] efs.append({ 'name': "Cards:", 'value': pieces['cards'], 'inline': False, }) for desc in pieces['descriptions']: efs.append({ 'name': desc['name'], 'value': desc['description'], 'inline': False, }) embed = { 'embed_title': title, 'embed_desc': description, 'thumbnail_url': 'https://cdn2.rebbl.net/images/cards/dice_small.png', 'embed_fields': efs, } await self.send_embed(embed, ctx)