Example #1
0
    def do(self):
        super().do()
        if len(self.args) == 0:
            return f"""Available packs: {', '.join([f"{k.capitalize()}: {database.packs[k]['cost']}" for k in database.packs.keys()])}"""
        if len(self.args) == 1:
            if database.get_user(self.sender.id) is None:
                return "forgot to do !start"
            elif self.args[0] not in database.packs.keys():
                return f"Valid packs include: {str([k for k in database.packs.keys()])}"
            elif database.get_balance(self.sender) - database.packs[self.args[0]]["cost"] < 0:
                return "please do not put yourself in debt"
            else:
                count = database.packs[self.args[0]]["count"]
                pack = database.buy_pack(self.sender, self.args[0], count)
                if pack:
                    embed = discord.Embed(title=f"{(self.args[0]).capitalize()}: Discovery", color=discord.Color.green())
                    # change the values so they work in discord.py
                    embed.set_author(name=self.sender.name, icon_url=self.sender.avatar_url)

                    b = np.array(pack)
                    a = [f"{util.escape_underscore(s[0])} :: {s[1]} :: {s[2]}" for s in b[:, 2:]]
                    embed.add_field(name="Cards", value="\n".join(a), inline=False)
                    return None, embed
        else:
            return f"command {self.name} has too many or too few arguments ( {self.args})"
Example #2
0
    def account(self):
        """
        Screen shown after logging in
        """
        while True:
            print('1. Balance')
            print('2. Add income')
            print('3. Do transfer')
            print('4. Close Account')
            print('5. Log out')
            print('0. Exit')
            choice = input()

            if choice == '1':
                balance = database.get_balance(BankingSystem.current_user)
                print(f"\nBalance: {balance[0]}\n")
            elif choice == '2':
                print('\nEnter income: ')
                self.add_income()
            elif choice == '3':
                print('\nTransfer')
                print('Enter card number:')
                self.do_transfer()
            elif choice == '4':
                self.close_account()
                break
            elif choice == '5':
                BankingSystem.current_user = ""
                print('\nYou have successfully logged out!\n')
                break
            elif choice == '0':
                print('\nBye!')
                sys.exit()
            else:
                print('\nPlease enter either 1, 2, or 0 to exit.\n')
Example #3
0
 def deposit(self, amount): 
   if not self.logged_in():
     raise NotLoggedInError()
   if self.account_type == AccountManager.SRND:
     increase_balance(self.rfid, amount)
     self.balance = get_balance(self.rfid)
   #If guest
   else:
     self.balance += amount
Example #4
0
 def do(self):
     super().do()
     if len(self.args) == 0:
         balance = database.get_balance(self.sender)
         if balance or isinstance(balance, Number):
             return f"You have {balance} moneys"
         else:
             return "forgot to do !start"
     else:
         return f"command {self.name} has too many arguments ( {self.args})"
Example #5
0
 def withdraw(self, amount, descript = None):
   if not self.logged_in():
     raise NotLoggedInError()
   if self.balance < amount:
     raise InsufficientFunds()
   if self.account_type == AccountManager.SRND:
     decrease_balance(self.rfid, amount)
     self.balance = get_balance(self.rfid)
   #If guest
   else:
     self.balance -= amount
Example #6
0
 def do_transfer(self, connection, login_card_number):
     """
     This method is for performing transfer.
     It validates reciever's card number and sender's balance
     """
     transfer_card_number = input("\nTransfer\nEnter card number:\n")
     if self.validate_card_number(connection, transfer_card_number, login_card_number):
         transfer_amount = int(input("\nEnter how much money you want to transfer:\n"))
         if transfer_amount > database.get_balance(connection, login_card_number):
             print("\nNot enough money!")
         else:
             database.transfer_balance(connection, transfer_card_number, login_card_number, transfer_amount)
             print("\nSuccess!")
Example #7
0
def main():
    parser = argparse.ArgumentParser(description="SmartWallet - script "
                                     "using database to manage "
                                     "your costs")
    parser.add_argument("-s",
                        "--supply",
                        metavar='N',
                        type=int,
                        help="a float number of sum")
    parser.add_argument("-b",
                        "--balance",
                        action="store_true",
                        help="get balance from wallet")
    parser.add_argument("-H",
                        "--history",
                        type=int,
                        nargs='?',
                        const=0,
                        help="get history")
    parser.add_argument("-d",
                        "--discard",
                        nargs=2,
                        metavar="data",
                        help="set purchase")
    args = parser.parse_args()
    if args.supply:
        db.supply(db.cursor, args.supply)
        print("Successful supplying!")
    elif args.balance:
        bal = db.get_balance(db.cursor)
        print("You have {0} UAN".format(bal))
    elif args.history or args.history == 0:
        res = db.get_history(db.cursor, args.history)
        if res:
            for i in res:
                print("{1} := {2}".format(*i))
        else:
            print("There is no info yet")
    elif args.discard:
        try:
            n = int(args.discard[0])
        except ValueError:
            print("N is not a number")
            exit(1)
        db.discard(db.cursor, n, args.discard[1])
        print("Successful discarding!")
    else:
        print("Print `--help` or `-h` to find out arguments")
Example #8
0
def purchase():
    form = forms.PurchaseForm(request.form)
    balance = database.get_balance(session.get('username'))

    if request.method == 'POST':
        try:
            database.perform_transcation("MINE", session.get('username'),
                                         form.balance.data)
            flash('You have successfully purchased your balance!', 'success')
        except Exception as e:
            flash(str(e), 'danger')
        return redirect(url_for('dashboard'))

    return render_template('purchase.html',
                           title="Purchase",
                           form=form,
                           balance=balance)
Example #9
0
 def log_in(self, rfid):
   if self.account_type == AccountManager.GUEST:
     return False
   if rfid == settings.TESTING_RFID:
     self.account_type = AccountManager.TEST
     self.username = settings.TESTING_USERNAME
     self.rfid = rfid
     self.balance = settings.TESTING_BALANCE
     return True
   else:
     self.rfid = rfid
     self.username = get_username(rfid)
     if self.username == None:
       print "Invalid credentials"
       print "RFID = " + rfid
       return False
     self.account_type = AccountManager.SRND
     self.balance = get_balance(rfid)
     return True
Example #10
0
 def login_choices(self, connection, login_card_number):
     """
     Provides menu after successful login 
     """
     while True:
         login_choice = input(LOGIN_PROMPT)
         if login_choice == "1":
             print("\nBalance: {}".format(database.get_balance(connection, login_card_number)))
         elif login_choice == "2":
             self.add_income(connection, login_card_number)
         elif login_choice == "3":
             self.do_transfer(connection, login_card_number)
         elif login_choice == "4":
             database.delete_account(connection, login_card_number)
             break
         elif login_choice == "5":
             print("\nYou have successfully logged out!")
             break
         else:
             print("\nBye!")
             quit()
Example #11
0
 def do(self):
     super().do()
     if len(self.args) == 2:
         user = self.message.mentions[0]
         if database.get_user(user.id) is None:
             return "That user did not type !start, leave him alone"
         if user is self.sender:
             return "sad lawl trying to pay yourself (didn't work)"
         pay_amount = int(self.args[1])
         if pay_amount < 0:
             return ":thinking:"
         if database.get_balance(self.sender) - pay_amount < 0:
             return "not allowed to give yourself debt"
         if database.add_balance(self.sender,
                                 -pay_amount) and database.add_balance(
                                     user, pay_amount):
             return f"Transaction completed: you paid {pay_amount} from you to {user.mention}"
         else:
             return "forgot to do !start"
     else:
         return f"command {self.name} has too many or too little arguments ( {self.args})"
Example #12
0
def dashboard():
    form = forms.TransactionForm(request.form)
    balance = database.get_balance(session.get('username'))
    blockchain = database.get_blockchain().chain
    current_time = time.strftime('%H:%M:%S, %A, %d  %B %Y')

    if request.method == 'POST':
        try:
            database.perform_transcation(session.get('username'),
                                         form.username.data, form.balance.data)
            flash('Transction has been completed successfully!', 'success')
        except Exception as e:
            flash(str(e), 'danger')
        return redirect(url_for('dashboard'))

    return render_template('dashboard.html',
                           title="Dashboard",
                           session=session,
                           form=form,
                           balance=balance,
                           blockchain=blockchain,
                           current_time=current_time)
Example #13
0
    async def on_message(self, message):
        if message.guild is None:
            await message.author.send(
                "I can only respond to messages in guilds")
            return
        message.content = message.content.replace("  ", " ")
        person_roles = list(map(lambda role: role.id, message.author.roles))
        server_members = list(
            map(lambda member: member.id, message.guild.members))
        server_roles = list(map(lambda role: role.id, message.guild.roles))
        person_id = message.author.id
        if (message.author.bot):
            return
        ##(guild, message,  person_roles,server_members,server_roles,person_id)
        trigger_msg = database.trigger_messages(message.guild, message,
                                                person_roles, server_members,
                                                server_roles,
                                                message.author.id)
        #print(trigger_msg)
        if trigger_msg is not None:
            for i in trigger_msg:
                if (i[1]):
                    if (not i[0]):
                        await message.channel.send(embed=embeds.simple_embed(
                            False,
                            f'<@!{i[2]}> your smart contract was annuled: {i[1]}'
                        ))
                    else:
                        await message.channel.send(embed=embeds.simple_embed(
                            True, f'a smart contract said: {i[1]}'))
        answer = database.answer_question(message.author, message.content,
                                          message.guild)
        if answer is not None:
            await message.channel.send(
                embed=embeds.simple_embed(answer[0], answer[1]))
        if (message.content.startswith("$")):
            if (message.content.startswith("$smart-contract")):
                if (message.content.count("```") == 2):
                    if (message.content.split("```")[0].count(" ") == 2):
                        await message.channel.send(embed=embeds.simple_embed(
                            True,
                            database.write_contract(
                                message.guild, message.author,
                                message.content.split("```")[1],
                                message.content.split(
                                    " ")[1], client, person_roles,
                                server_members, server_roles, person_id)[1]))
                        return
            if (commands.is_valid_command(message)):
                message_array = message.content.split(" ")
                message_command = message_array[0]
                if (message_command == "$help"):
                    await message.channel.send(embed=embeds.simple_embed(
                        "info", '''
- $help - shows all commands
- $send (from wallet) (to wallet) (amount) - sends an amount to a person from that wallet
- $print (wallet name) (amount) - creates an amount of money in that wallet if you have the role "printer"
- $balance (wallet name) - returns the amount of money in the wallet
- $links - show some links related to this bot
- $smart-contract (trigger) (code block) - code a smart contract
- $clear-contracts - delete all your smart contracts.
- $create (ping wallet) - create an account
- $whois (condition) - figure out who is a condition
- $send-each (from wallet) (ammount) (condition) - send each person who meets a condition
- $set-balance (ping wallet) - set the balance of a wallet for admins only
- $set-balance-each (amount) (condition) - set the balance of each person who meets a condition
- $wallet-settings (target person) (ping wallet) (setting name) (boolean) - change the setting, such as view or access, to allow certain people to do more with wallets
- $trade (wallet) (wanted currency) (giving up currency) (optional limitations) - create a trade
- $accept (message id of trade) (wallet) - accept a trade
- $quiz - start a quiz based on a subject
- $shop (item name) (price) - same as trade but only for admins and you can also offer roles as trades
- $work - get an amount of money no strings attached
- $work-conditional (level name) (work reward) (conditional) - allows admins to add levels to working and give different people different work rewards
                    '''))
                if (message_command == "$send"):
                    #send(person_roles, server_members, server_roles, person_id, guild_id, from_wallet, to_wallet, amount)
                    person_roles = list(
                        map(lambda role: role.id, message.author.roles))
                    server_members = list(
                        map(lambda member: member.id, message.guild.members))
                    server_roles = list(
                        map(lambda role: role.id, message.guild.roles))

                    send_result = database.send(message.author.id,
                                                message.guild,
                                                message_array[1],
                                                message_array[2],
                                                message_array[3])
                    await message.channel.send(embed=embeds.simple_embed(
                        send_result[0], send_result[1]))
                    #if  send_result[0]:
                    #   await message.channel.send(send_result[1])
                    #else:
                    #    await message.channel.send(f'an error occured {send_result[1]}')
                if (message_command == "$create"):
                    result = database.create(message.guild, message_array[1])
                    await message.channel.send(
                        embed=embeds.simple_embed(result[0], result[1]))

                if (message_command == "$balance"):
                    ##guild,wallet,server_members, server_roles
                    if len(message_array) == 1:
                        message_array.append(message.author.mention)
                    bal = database.get_balance(message.author, message.guild,
                                               message_array[1])
                    if (bal[0]):
                        res = ""
                        for key, value in bal[1].items():
                            if ("balance" in key):
                                res = res + f'{key}: {value}\n'
                        await message.channel.send(embed=embeds.simple_embed(
                            True, f'the balance is:\n {res}'))
                    else:
                        await message.channel.send(embed=embeds.simple_embed(
                            False, f'there was an error: {bal[1]}'))
                if (message_command == "$print"):
                    ##(discord_client, guild_id, wallet, amount)
                    result = database.print_money(message.author,
                                                  message.guild,
                                                  message_array[1],
                                                  message_array[2])
                    await message.channel.send(
                        embed=embeds.simple_embed(result[0], result[1]))
                if (message_command == "$clear-contracts"):
                    database.clear_contracts(message.guild, message.author.id)
                    await message.channel.send(embed=embeds.simple_embed(
                        "info", "your contracts were all deleted"))
                if (message_command == "$links"):
                    await message.channel.send(embed=embeds.simple_embed(
                        "info",
                        "Github - https://github.com/eulerthedestroyer/EU-Economy-Bot \n Discord link -  https://discord.gg/ghFs7ZM \n Bot link - https://discord.com/api/oauth2/authorize?client_id=716434826151854111&permissions=268503104m&scope=bot \n Web interface - https://economy-bot.atticuskuhn.repl.co"
                    ))
                if (message_command == "$config"):
                    if message.author.guild_permissions.administrator:
                        await message.channel.send(
                            embed=embeds.simple_embed(*database.set_config(
                                message.guild, message_array[1],
                                message_array[2])))
                    else:
                        await message.channel.send(embed=embeds.simple_embed(
                            False,
                            "you must be an administrator to access the config"
                        ))
                if message_command.startswith("$stats"):
                    result = methods.get_wallet(server_members, server_roles,
                                                message.guild.id,
                                                message_array[1])
                    if (result[0]):
                        print(result)
                        found_wallet = database.wallet_by_id(
                            message.guild, result[1])
                        if "record" in found_wallet:
                            fig = plt.figure(figsize=(10, 5))
                            X1 = list(found_wallet["record"].keys())
                            Y1 = list(found_wallet["record"].values())

                            plt.plot(X1, Y1, label="plot 1")
                            fig.savefig('fig.jpg',
                                        bbox_inches='tight',
                                        dpi=150)
                            await message.channel.send(
                                file=discord.File('fig.jpg'))
                            os.remove("fig.jpg")
                            #await message.channel.send(found_wallet["record"])
                        else:
                            await message.channel.send(
                                embed=embeds.simple_embed(
                                    False, "can't find any stats"))
                    else:
                        await message.channel.send("error")
                if message_command == "$whois":
                    people = methods.whois(message_array[1:], message.guild)
                    return_statement = ""
                    symbol = "\n"
                    if len(people) > 7:
                        symbol = ","
                    for index, person in enumerate(people):
                        if len(return_statement) > 700:
                            return_statement += f' and {len(people)-index} others'
                            break
                        return_statement = return_statement + f'<@{person}>{symbol}'
                    if return_statement == "":
                        return_statement = "(no people found)"
                    embedVar = discord.Embed(
                        title="Result",
                        description=f'Found {len(people)} People',
                        color=0x00ff00)
                    embedVar.add_field(name="People",
                                       value=return_statement,
                                       inline=False)
                    await message.channel.send(embed=embedVar)
                if message_command == "$send-each":
                    people = methods.whois(message_array[3:], message.guild)
                    return_statement = ""
                    successful_transfer = True
                    for person in people:
                        send_result = database.send(message.author.id,
                                                    message.guild,
                                                    message_array[1],
                                                    f'<@{person}>',
                                                    message_array[2])
                        if send_result[0]:
                            return_statement = return_statement + f'<@{person}> - success\n'
                        else:
                            return_statement = return_statement + f'<@{person}> - error: {send_result[1]}\n'
                            successful_transfer = False
                    if return_statement == "":
                        return_statement = "(no people found)"
                    if successful_transfer:
                        embedVar = discord.Embed(title="Result",
                                                 color=0x00ff00)
                    else:
                        embedVar = discord.Embed(title="Result",
                                                 color=0xff0000)

                    embedVar.add_field(name="People",
                                       value=return_statement,
                                       inline=False)
                    await message.channel.send(embed=embedVar)
                if message_command == "$set-balance":
                    if (not message.author.guild_permissions.administrator):
                        await message.channel.send(
                            "you do not have administrator permissions")
                        return
                    result = database.set_money(message.guild,
                                                message_array[2],
                                                message_array[1])
                    await message.channel.send(embed=embeds.simple_embed(
                        result[0], f'{result[0]}{result[1]}'))
                if message_command == "$set-balance-each":
                    if (not message.author.guild_permissions.administrator):
                        await message.channel.send(
                            "you do not have administrator permissions")
                        return
                    people = methods.whois(message_array[2:], message.guild)
                    return_statement = ""
                    successful_transfer = True
                    for person in people:
                        send_result = database.set_money(
                            message.guild, message_array[1], f'<@{person}>')
                        if send_result[0]:
                            return_statement = return_statement + f'<@{person}> - success\n'
                        else:
                            return_statement = return_statement + f'<@{person}> - error: {send_result[1]}\n'
                            successful_transfer = False
                    if return_statement == "":
                        return_statement = "(no people found)"
                    if successful_transfer:
                        embedVar = discord.Embed(title="Result",
                                                 color=0x00ff00)
                    else:
                        embedVar = discord.Embed(title="Result",
                                                 color=0xff0000)

                    embedVar.add_field(name="People",
                                       value=return_statement,
                                       inline=False)
                    await message.channel.send(embed=embedVar)
                if message_command == "$wallet-settings":
                    res = database.set_settings(message.guild, message.author,
                                                message_array[1],
                                                message_array[2],
                                                message_array[3],
                                                message_array[4])
                    await message.channel.send(
                        embed=embeds.simple_embed(res[0], res[1]))
                if message_command == "$trade":
                    res = database.insert_trade(message, message.author,
                                                message.guild,
                                                message_array[1],
                                                message_array[2],
                                                message_array[3],
                                                message_array[4:])
                    await message.channel.send(
                        embed=embeds.simple_embed(res[0], res[1]))
                    if res[0]:
                        await message.add_reaction("✅")
                if message_command == "$accept":
                    res = database.fulfill_trade(message_array[1],
                                                 message_array[2],
                                                 message.author, message.guild)
                    await message.channel.send(
                        embed=embeds.simple_embed(res[0], res[1]))
                if message_command == "$quiz":
                    res = database.get_question(message.author, message.guild)
                    await message.channel.send(
                        embed=embeds.simple_embed(res[0], res[1]))
                if message_command == "$shop":
                    if not message.author.guild_permissions.administrator:
                        await message.channel.send(embed=embeds.simple_embed(
                            False,
                            "you must be an administrator to configure the shop"
                        ))
                        return
                    res = database.insert_trade(message, message.author,
                                                message.guild, "admins",
                                                message_array[1],
                                                message_array[2],
                                                message_array[3:])
                    await message.channel.send(
                        embed=embeds.simple_embed(res[0], res[1]))
                    if res[0]:
                        await message.add_reaction("✅")
                if message_command == "$work":
                    res = database.work(message.author, message.guild)
                    await message.channel.send(embed=embeds.simple_embed(*res))
                if message_command == "$work-conditional":
                    if not message.author.guild_permissions.administrator:
                        await message.channel.send(embed=embeds.simple_embed(
                            False,
                            "you must be an administrator to configure conditional work rewards"
                        ))
                        return
                    res = database.work_conditions(message.guild,
                                                   message_array[1],
                                                   message_array[2],
                                                   message_array[3:])
                    await message.channel.send(embed=embeds.simple_embed(*res))
            else:
                await message.channel.send(embed=embeds.simple_embed(
                    False,
                    "not valid command. If you want a list of all commands, type '$help' "
                ))
Example #14
0
    def do(self):
        super().do()
        embed = discord.Embed(descrption="Auctions", color=discord.Color.red())
        embed.set_author(name=self.sender.name, icon_url=self.client.user.avatar_url)

        page = 0
        if len(self.args) == 1:
            try:
                page = int(self.args[0])
            except ValueError:
                return f"{self.args[0]} is not a valid number"
        if len(self.args) == 0:
            # change the values so they work in discord.py
            auctions = database.all_auctions(page)
            print(auctions)
            if len(auctions) == 0:
                return "No auctions"
            cleaned_results = [f"{r[0]} :: {util.escape_underscore(r[1])} :: " 
                               f"{r[2]} :: {database.get_card_by_id(r[3])[2]}"
                               for r in auctions]
            embed.add_field(name="Auctions(id::owner::money::card)", value="\n".join(cleaned_results), inline=False)
            embed.set_footer(
                text=f"Showing page {page + 1} of {int(database.count_all_auctions() / 10) + 1}")
            return None, embed
        if self.args[0] == "accept" and self.args[1]:
            try:
                auction_id = int(self.args[1])
                if not database.check_auction(auction_id):
                    return f"{self.args[1]} is not a valid auction id!"
            except ValueError:
                return f"{self.args[1]} is not a valid auction id!"
            # here:
            auction = database.get_auction(auction_id)[0]
            print(auction)
            if database.get_balance(self.sender) >= auction[2]:
                database.remove_auction(auction[0])
                database.add_card(self.sender, auction[3])
                database.add_balance(self.sender, -auction[2])
                database.add_balance_id(auction[4], auction[2])
                return f"You earned {database.get_card_by_id(auction[3])[2]} " \
                       f"from an auction with a bid of {auction[2]}"
            else:
                return "You do not have enough money to accept that auction!"
        elif self.args[0] == "revoke" and self.args[1]:
            try:
                auction_id = int(self.args[1])
                if not database.check_auction(auction_id):
                    return f"{self.args[1]} is not a valid auction id!"
            except ValueError:
                return f"{self.args[1]} is not a valid auction id!"
            auction = database.get_auction(auction_id)[0]
            database.remove_auction(auction[0])
            database.add_card(self.sender, auction[3])
            return f"You revoked auction {auction_id}"
        elif len(self.args) == 2:
            try:
                bid_balance = int(self.args[1])
                card_id = database.get_card(self.args[0])
            except ValueError:
                return f"{self.args[1]} is not a valid number"
            if card_id is not None:
                if card_id in database.get_cards(self.sender):
                    full_card = database.get_card_by_id(card_id)
                    database.add_auction(self.sender, card_id, bid_balance)
                    c = database.remove_card(self.sender, card_id)
                    print(c)
                    if c:
                        return f"You put {full_card[2]} up for auction for {bid_balance} money"
                    else:
                        print("Error in auctioning card")
                else:
                    return f"You do not have that card!"
            else:
                return f"Invalid card"
Example #15
0
 elif choice == '2':
     print("Enter your card number:")
     user_card_number = input()
     print("Enter your PIN")
     user_pin = input()
     if not database.check_card_pin(conn, user_card_number, user_pin):
         print("Wrong card number or PIN!")
         continue
     print("You have successfully logged in!")
     while True:
         print(MENU_USER)
         choice = input()
         print()
         if choice == '1':
             print("Balance:",
                   database.get_balance(conn, user_card_number)[0])
         elif choice == '2':
             income = int(input("Enter income: "))
             database.add_income(conn, income, user_card_number)
             print("Income was added!")
         elif choice == '3':
             print('Transfer')
             receiver_card_number = input("Enter card number: ")
             if not Card.luhn_check(list(receiver_card_number)):
                 print(
                     'Probably you made a mistake in the card number. Please try again!'
                 )
                 continue
             elif not database.check_card_existance(conn,
                                                    receiver_card_number):
                 print("Such a card does not exist.")