Example #1
0
def set_settings(guild, person, target, wallet, setting_name, value):
    if not setting_name in config[
            "wallet_settings"] and not setting_name.startswith("print-"):
        return (False, "invalid setting name")
    value = (value.lower() == "true")
    found_wallet = methods.get_wallet(guild, wallet)
    found_target = methods.get_wallet(guild, target)
    if not found_wallet[0]:
        return (False, "wallet does not exist")
    if not found_target[0]:
        return (False, "target does not exist")
    guild_collection = db[str(guild.id)]
    account = guild_collection.find_one({"id": found_wallet[1].id})
    if not account:
        return (False, "wallet does not have an accound")
    can_access = False
    if person.guild_permissions.administrator:
        can_access = True
    if not can_access:
        return (False, "you cannot edit the settings of this wallet")
    temp = account
    print(temp, setting_name)
    if not "permissions" in temp:
        temp["permissions"] = {}
    if temp["permissions"] is None:
        temp["permissions"] = {}
    if not setting_name in temp["permissions"]:
        temp["permissions"][setting_name] = {"true": [], "false": []}
    if not "true" in temp["permissions"][setting_name]:
        temp["permissions"][setting_name] = {"true": [], "false": []}
    if value:
        if found_target[1].id in temp["permissions"][setting_name]["true"]:
            return (False, "setting already true")
        temp["permissions"][setting_name]["true"].append(found_target[1].id)
        try:
            temp["permissions"][setting_name]["false"].remove(
                found_target[1].id)
        except:
            pass

    else:
        if found_target[1].id in temp["permissions"][setting_name]["false"]:
            return (False, "setting already false")
        temp["permissions"][setting_name]["false"].append(found_target[1].id)
        try:
            temp["permissions"][setting_name]["true"].remove(
                found_target[1].id)
        except:
            pass
    guild_collection.update_one({"id": found_wallet[1].id},
                                {"$set": {
                                    "permissions": temp["permissions"]
                                }})
    return (True, "settings successfully changed")
Example #2
0
def set_money(guild, amount, wallet):
    #server_members = list(map(lambda member:member.id, guild.members))
    #s#erver_roles = list(map(lambda role: role.id, guild.roles))
    if ("-" in amount):
        amount_array = amount.split("-")
        print(amount.split("-"))
        amount = amount_array[0]
        currency = amount_array[1]
    if 'currency' in locals():
        if (not methods.valid_item(currency)):
            return (False, "invaid item name")
    if (not amount.isdigit()):
        return (False, "incorrect ammount")
    guild_collection = db[str(guild.id)]
    to_wallet = methods.get_wallet(guild, wallet)
    if (not to_wallet[0]):
        return to_wallet
    found_wallet = methods.find_create(to_wallet[1].id, guild)
    if 'currency' in locals():
        guild_collection.update_one(
            {"id": to_wallet[1].id},
            {"$set": {
                f'balance-{currency}': int(amount)
            }})
        return (True, f'balance was set to {amount}')
    guild_collection.update_one({"id": to_wallet[1].id},
                                {"$set": {
                                    "balance": int(amount)
                                }})
    return (True, f'balance was set to {amount}')
Example #3
0
 async def convert(self, ctx, wallet):
     if wallet is None:
         wallet = ctx.author.mention
     get_wallet_result = methods.get_wallet(ctx.guild, wallet)
     if not get_wallet_result[0]:
         raise BadArgument(f'person {wallet} does not exist in this guild')
     db_wallet = methods.find_create(get_wallet_result[1].id, ctx.guild)
     #print("db_wallet:", db_wallet)
     return db_wallet
Example #4
0
def print_money(person, guild, wallet, amount):
    currency = ""
    if "-" in amount:
        currency = f'-{amount.split("-")[1]}'
        amount = amount.split("-")[0]

        if not methods.valid_item(currency[1:]):
            return (False, "invalid item name")
    try:
        amount = int(amount)
    except:
        return (False, "invalid amount")

    guild_collection = db[str(guild.id)]
    wallet_id = methods.get_wallet(guild, wallet)
    if not wallet_id[0]:
        return (False, "invalid wallet name")
    can_print = False
    if person.guild_permissions.administrator:
        can_print = True
    account_of_printing = methods.find_create(wallet_id[1].id, guild)
    if account_of_printing is None:
        c_result = create(guild, wallet)
        if not c_result[0]:
            return (False, c_result[1])
        account_of_printing = c_result[2]
        #return (False,"can't find doesn't exist")
    if "permissions" in account_of_printing:
        if "print" in account_of_printing["permissions"]:
            if person.id in account_of_printing["permissions"]["print"][
                    "true"]:
                can_print = True
            for role in person.roles:
                if role.id in account_of_printing["permissions"]["print"][
                        "true"]:
                    can_print = True
        if currency != "":
            if f'print{currency}' in account_of_printing["permissions"]:
                if person.id in account_of_printing["permissions"][
                        f'print{currency}']["true"]:
                    can_print = True
                for role in person.roles:
                    if role.id in account_of_printing["permissions"][
                            f'print{currency}']["true"]:
                        can_print = True
    if "printer" in person.roles:
        can_print = True
    if not can_print:
        return (False, "you do not have permission to print")
    guild_collection.update_one({"id": account_of_printing["id"]},
                                {"$inc": {
                                    f'balance{currency}': amount
                                }})
    return (True, "transfer successful")
Example #5
0
def create(guild, wallet_ping):
    print("created called with", wallet_ping)
    guild_collection =db[str(guild.id)]
    get_wallet_result = methods.get_wallet( guild, wallet_ping)
    
    #print(get_wallet_result)
    server_config =  guild_collection.find_one({
            "type":"server",
            "id"  : guild.id
    })
    if server_config is not None:
        default_balance =server_config["default_balance"]
    else:
        guild_collection.insert_one({
            "type":"server",
            "id":guild.id,
            "default_balance": config["default_balance"]
        })
        default_balance = config["default_balance"]
    if(get_wallet_result[0]):
        if guild_collection.find_one({ "id":get_wallet_result[1].id}):
            return (False, "account already exists")
        for person in guild.members:
            if(person.id == get_wallet_result[1].id):
                found_person = person
        for role in guild.roles:
            if(role.id == get_wallet_result[1].id):
                found_role = role
        if(get_wallet_result[2] == "person"):
            return_wallet = guild_collection.insert_one({
                "name"   :found_person.name,
                "id"     :found_person.id,
                "type"   :"personal",
                "balance": int(default_balance)
             })
            #return_wallet = guild_collection.find_one({"_id":return_wallet.inserted_id})
        else:
            return_wallet = guild_collection.insert_one({
                "name"   :found_role.name,
                "id"     :found_role.id,
                "type"   :"role",
                "balance": int(default_balance)
             })
        return_wallet = guild_collection.find_one({"_id":return_wallet.inserted_id})
        print("create will return", return_wallet)
        return (True, "created",return_wallet)
    else:
        return (False, "doesn't exist")
 def send_api():
     data = request.json
     print(data)
     guild = discord.utils.find(lambda m: int(m.id) == int(data["guild"]), bot.guilds)
     #member = discord.utils.find(lambda m: m.id == data.person_id, guild.members)
     res =send(int(data["person_id"]), guild, data["from_wallet"], data["to_wallet"], data["amount"])
     guild_collection =db[str(guild.id)]
     new_found_id = get_wallet(guild,data["to_wallet"])[1].id
     print(new_found_id,"new_found_id")
     new_wallet=guild_collection.find_one({"id":new_found_id})
     print(new_wallet,"new_wallet")
     del new_wallet["_id"]
     return {
         "success":res[0],
         "message":res[1],
         "new_balance":new_wallet
     }
Example #7
0
    async def graph(self, ctx, wallet):
        result = methods.get_wallet(ctx.guild, wallet)
        if (result[0]):
            print(result)
            found_wallet = methods.find_create(result[1].id, ctx.guild)
            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)
                return await ctx.send(file=discord.File('fig.jpg'))
                os.remove("fig.jpg")
            else:
                return await ctx.send(
                    embed=simple_embed(False, "can't find any stats"))
        else:
            await ctx.send(embed=simple_embed(False, "error"))
Example #8
0
def get_balance(person, guild, wallet):
    guild_collection = db[str(guild.id)]
    ##(server_members,server_roles,  guild_id, from_wallet)
    get_wallet_result = methods.get_wallet(guild, wallet)
    #print(get_wallet_result)

    if (get_wallet_result[0]):
        found_wallet = guild_collection.find_one(
            {"id": get_wallet_result[1].id})
        if (found_wallet is None):
            found_wallet = create(guild, wallet)[2]
        if "permissions" in found_wallet:
            if "view" in found_wallet["permissions"]:
                print(1)
                if person.id in found_wallet["permissions"]["view"]["false"]:
                    print(2)
                    return (False,
                            "you do not have permission to see this wallet")
        return (True, found_wallet)
    else:
        return (False, "doesn't exist")
Example #9
0
 async def prune(self, ctx):
     guild_collection = db[str(ctx.guild.id)]
     all_wallets = guild_collection.find({})
     return_message = ""
     deleting = []
     for wallet in all_wallets:
         if "type" in wallet:
             if wallet["type"] == "personal" or wallet["type"] == "role":
                 #print("trying", wallet["name"])
                 found = methods.get_wallet(ctx.guild, str(wallet["id"]))
                 #print("found is ", found)
                 if not found[0]:
                     return_message += f'\n deleted {wallet["name"]}'
                     deleting.append(wallet["_id"])
         # if :
         #     print("trying", wallet["name"])
         #     if wallet["type"]=="personal":
         #         if not  methods.get_wallet(ctx.guild, str(wallet["id"]))[0]:
         #             return_message+=f'\n deleted {wallet["name"]}'
     guild_collection.remove({'_id': {'$in': deleting}})
     if return_message == "":
         return_message = "deleted no one"
     return await ctx.send(embed=simple_embed(True, return_message))
Example #10
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 #11
0
 async def fulfill_trade(self, ctx, wallet, message):
     guild = ctx.guild
     person = ctx.author
     found_wallet = methods.get_wallet(guild, wallet)
     if not found_wallet[0]:
         return await ctx.send(embed=simple_embed(False, "cant find wallet")
                               )
     if not methods.can_access_wallet(guild, person.id, wallet):
         return await ctx.send(
             embed=simple_embed(False, "cannot access wallet"))
     try:
         message = int(message)
     except:
         return await ctx.send(embed=simple_embed(False, "invalid number"))
     guild_collection = db[str(guild.id)]
     found_offer = guild_collection.find_one({
         "type": "trade",
         "message_id": message
     })
     if found_offer is None:
         return await ctx.send(embed=simple_embed(False, "can't find offer")
                               )
     if "uses" in found_offer:
         if found_offer["uses"] <= 0:
             guild_collection.delete_one(
                 {"message_id": found_offer["message_id"]})
             return await ctx.send(
                 embed=simple_embed(False, "offer has been used up"))
     if "offer_time" in found_offer:
         if time.time() > found_offer["offer_time"]:
             guild_collection.delete_one(
                 {"message_id": found_offer["message_id"]})
             return await ctx.send(
                 embed=simple_embed(False, "offer has run out of time"))
     if "people_restrictions" in found_offer:
         if person.id not in methods.whois(
                 found_offer["people_restrictions"], guild):
             return await ctx.send(embed=simple_embed(
                 False,
                 "you cannot accept this offer because a restriction has bee"
             ))
     receiver = methods.find_create(found_wallet[1].id, ctx.guild)
     if f'balance{found_offer["cost_currency"]}' not in receiver:
         return await ctx.send(
             embed=simple_embed(False, "you have no money"))
     if receiver[f'balance{found_offer["cost_currency"]}'] < found_offer[
             "cost_amount"]:
         return await ctx.send(
             embed=simple_embed(False, "you don't have enough money"))
     sender = guild_collection.find_one({"id": found_offer["person"]})
     if "wallet" in found_offer:
         if f'balance{found_offer["offer_currency"]}' not in sender:
             guild_collection.delete_one(
                 {"message_id": found_offer["message_id"]})
             return await ctx.send(embed=simple_embed(
                 False,
                 "offer deleted, person does not have enough for trade"))
         if sender[f'balance{found_offer["offer_currency"]}'] < found_offer[
                 "offer_amount"]:
             guild_collection.delete_one(
                 {"message_id": found_offer["message_id"]})
             return await ctx.send(embed=simple_embed(
                 False,
                 "offer deleted, person does not have enough for trade"))
     guild_collection.update_one({"id": receiver["id"]}, {
         "$inc": {
             f'balance{found_offer["offer_currency"]}':
             -int(found_offer["offer_amount"])
         }
     })
     guild_collection.update_one({"id": receiver["id"]}, {
         "$inc": {
             f'balance{found_offer["cost_currency"]}':
             int(found_offer["cost_amount"])
         }
     })
     if " wallet" in found_offer:
         guild_collection.update_one({"id": sender["id"]}, {
             "$inc": {
                 f'balance{found_offer["offer_currency"]}':
                 int(found_offer["offer_amount"])
             }
         })
         guild_collection.update_one({"id": sender["id"]}, {
             "$inc": {
                 f'balance{found_offer["cost_currency"]}':
                 -int(found_offer["cost_amount"])
             }
         })
     if re.match(r'<@&?\d{18}>', found_offer["offer_currency"]) is not None:
         try:
             loop = asyncio.get_event_loop()
             id_role = re.findall(r'\d{18}',
                                  found_offer["offer_currency"])[0]
             print(id_role)
             id_role = int(id_role)
             role = discord.utils.get(guild.roles, id=id_role)
             print(role)
             loop.create_task(person.add_roles(role))
         except:
             return await ctx.send(
                 embed=simple_embed(False, "bad permissions"))
     if "uses" in found_offer:
         guild_collection.update_one(
             {"message_id": found_offer["message_id"]},
             {"$inc": {
                 "uses": -1
             }})
     return await ctx.send(embed=simple_embed(True, "success"))
Example #12
0
 async def insert_trade(self, ctx, wallet, offer, cost, *options):
     person = ctx.author
     guild = ctx.guild
     message = ctx.message
     if wallet != "admins":
         found_wallet = methods.get_wallet(guild, wallet)
         if not found_wallet[0]:
             return await ctx.send(embed=simple_embed(False, "bad wallet"))
         if not methods.can_access_wallet(guild, person.id, wallet):
             return await ctx.send(
                 embed=simple_embed(False, "bad wallet 2"))
     offer_currency = ""
     offer_amount = offer
     if "-" in offer:
         offer_currency = f'-{offer.split("-")[1]}'
         offer_amount = offer.split("-")[0]
         if not methods.valid_item(offer_currency[1:]):
             return await ctx.send(
                 embed=simple_embed(False, "invalid item name"))
     cost_currency = ""
     cost_amount = cost
     if "-" in cost:
         cost_currency = f'-{cost.split("-")[1]}'
         cost_amount = cost.split("-")[0]
         if not methods.valid_item(cost_currency[1:]):
             return await ctx.send(
                 embed=simple_embed(False, "invalid item name"))
     if re.match(r'<@&?\d{18}>', offer) is not None:
         offer_currency = offer
         offer_amount = "1"
     print(offer_amount, cost_amount)
     if not offer_amount.isdigit() or not cost_amount.isdigit():
         return await ctx.send(embed=simple_embed(False, "invalid amount"))
     offer_amount = int(offer_amount)
     cost_amount = int(cost_amount)
     for index, option in enumerate(options):
         if "use" in option:
             if not option.split("use")[0].isdigit():
                 return await ctx.send(
                     embed=simple_embed(False, "invalid uses"))
             uses = option.split("use")[0]
         if "time" in option:
             if not option.split("time")[0].isdigit():
                 return await ctx.send(
                     embed=simple_embed(False, "invalid time"))
             offer_time = int(option.split("time")[0]) + time.time()
         if option == "whois":
             people_restrictions = options[index:]
     guild_collection = db[str(guild.id)]
     offer_schema = {
         "type": "trade",
         "person": person.id,
         "message_id": message.id,
         "offer_currency": offer_currency,
         "offer_amount": int(offer_amount),
         "cost_currency": cost_currency,
         "cost_amount": int(cost_amount)
     }
     if "found_wallet" in locals():
         offer_schema["wallet"] = found_wallet[1].id
     if "uses" in locals():
         offer_schema["uses"] = int(uses)
     if "offer_time" in locals():
         offer_schema["offer_time"] = int(offer_time)
     if "people_restrictions" in locals():
         offer_schema["people_restrictions"] = people_restrictions
     guild_collection.insert_one(offer_schema)
     return await ctx.send(embed=simple_embed(
         True,
         f'succesful. In order to accept this trade, type "$accept {message.id} (ping wallet)", or you may react to the original message with ✅, in which case the money will be deducted from your personal account.'
     ))
Example #13
0
def send(person_id, guild, from_wallet, to_wallet, amount):
    # #print("send")
    #print("to_wallet is",to_wallet)
    if not methods.can_access_wallet(guild, person_id, from_wallet):
        return (False, "cannot access wallet")
    currency = ""
    if "-" in amount:
        currency = f'-{amount.split("-")[1]}'
        amount = amount.split("-")[0]
    percent = False
    if "%" in amount:
        percent = True
        amount = amount.split("%")[0]
    try:
        amount = int(amount)
    except:
        return (False, "invalid amount")
    guild_collection = db[str(guild.id)]
    from_wallet_id = methods.get_wallet(guild, from_wallet)
    to_wallet_id = methods.get_wallet(guild, to_wallet)
    #print(to_wallet_id,from_wallet_id)
    if (from_wallet_id[0] and to_wallet_id[0]):
        sender_account = guild_collection.find_one(
            {"id": from_wallet_id[1].id})
        reciever_account = guild_collection.find_one(
            {"id": to_wallet_id[1].id})
        if (sender_account is None):
            c_result = create(guild, from_wallet)
            if not c_result[0]:
                return (False, c_result[1])
            sender_account = c_result[2]
        if (reciever_account is None):
            c_result = create(guild, to_wallet)
            if not c_result[0]:
                return (False, c_result[1])
            reciever_account = c_result[2]

        if f'balance{currency}' not in sender_account:
            return (False, "you do not have this currency")
        if percent:
            amount = math.floor(sender_account[f'balance{currency}'] *
                                (amount / 100))
        if (sender_account[f'balance{currency}'] > amount):
            guild_collection.update_one(
                {"id": sender_account["id"]},
                {"$inc": {
                    f'balance{currency}': -amount
                }})
            guild_collection.update_one(
                {"id": reciever_account["id"]},
                {"$inc": {
                    f'balance{currency}': amount
                }})
            log_money(
                guild,
                f'<@{person_id}> sent {amount} from {from_wallet_id[1].mention } to {to_wallet_id[1].mention}'
            )
            return (
                True,
                f'transfer successful. you send {amount}, making your balance '
                + str(sender_account[f'balance{currency}']) + f' {currency}')

        else:
            return (False, f'insuffiecent funds for transfer.')
    else:
        return (False, "cannot find wallet")

    pass