Example #1
0
def main():
    args = singer.utils.parse_args([])

    account_ids = args.config.get("account_ids", [])
    access_token = args.config.get("access_token") or os.environ.get(
        "FACEBOOK_ACCESS_TOKEN")

    if not access_token:
        raise ValueError(
            f"missing required config 'access_token' or environment 'FACEBOOK_ACCESS_TOKEN'"
        )

    # use
    api = FacebookAdsApi.init(access_token=access_token, timeout=10)

    user = User("me", api=api)
    ad_accounts = cast(List[AdAccount],
                       user.get_ad_accounts(fields=["account_id", "id"]))

    all_account_ids = {
        accnt["account_id"]: accnt["id"]
        for accnt in ad_accounts
    }
    accnt_ids = []

    for account_id in account_ids:
        if account_id not in all_account_ids:
            logger.warn(
                f"invalid account id: {account_id} not in list of valid account ids: {all_account_ids.keys()}"
            )
            continue

        accnt_ids.append(all_account_ids[account_id])

    do_sync(accnt_ids, args.config, args.state)
Example #2
0
    def extract(self, short=False):
        # todo adset and ad

        me = User("me")
        accounts = list(me.get_ad_accounts(self.accs_fields))
        if short:
            accounts = [accounts[2]]
            self.insights_params["time_range"]["since"] = "2020-07-17"
            self.insights_params["time_range"]["until"] = "2020-07-23"
        campaigns = []
        for ele in accounts:
            campaigns.extend(list(ele.get_campaigns(self.camps_fields)))

        insights = {}
        for e in campaigns:
            insights[e["id"]] = list(
                e.get_insights(
                    self.insights_fields,
                    self.insights_params,
                    is_async=False,
                ))

        if self.year_start != self.year_n_week_start:
            params2 = dict(
                time_increment=7,
                time_range=dict(
                    since=self.year_start,
                    until=self.year_n_week_start,
                ),
            )
            for e in campaigns:
                insights[e["id"]] += list(
                    e.get_insights(
                        self.insights_fields,
                        params2,
                        is_async=False,
                    ))

        accounts = {ele["id"][4:]: ele["name"] for ele in accounts}
        campaigns = {ele["id"]: dict(ele) for ele in campaigns}

        ans = [
            dict(
                **campaigns[k],
                account_name=accounts[campaigns[k]["account_id"]],
                data=[dict(ele) for ele in v],
            ) for k, v in insights.items() if len(v) > 0
        ]

        Extract.write("../exports/FB_extracted.p", ans)
        return ans
Example #3
0
def lead_ad_generator():
    print("inside lead_ad_generator")

    rows = db.execute("SELECT * FROM users WHERE id = :id", id=session["id"])

    # if user does not have a valid access token, redirect to facebook login page; othwerise, launch lead_ad_generator
    # if there is no access token, user has not logged in
    if not g.user:
        print("no 'acess_token' found during call to lead_ad_generator method")
        return render_template("fblogin.html", app_id=FB_APP_ID)
    else:

        # create object and pass access_token and latest version as parameters
        FacebookAdsApi.init(access_token=g.user['access_token'],
                            api_version='v3.3')

        # Get users pages
        fields = [
            'name',
        ]
        params = {}
        pages = User(g.user['user_id']).get_accounts(
            fields=fields,
            params=params,
        )
        page_count = len(pages)

        # get users ad accounts
        FacebookAdsApi.init(access_token=g.user['access_token'],
                            api_version='v3.3')
        fields = [
            'name',
        ]
        params = {}
        ad_accounts = User(
            g.user['user_id']).get_ad_accounts(  # assuming id is the user_id
                fields=fields,
                params=params,
            )
        ad_account_count = len(ad_accounts)

        return render_template("lead_ad_generator.html",
                               user=g.user,
                               pages=pages,
                               adaccounts=ad_accounts,
                               ad_account_count=ad_account_count,
                               page_count=page_count)
Example #4
0
def page_remote_view(cts, scope, id=None, token=None):
    from oozer.common.facebook_api import PlatformApiContext, get_default_fields
    from facebook_business.adobjects.user import User

    if not token:
        scope = AssetScope.get(scope)
        token = PlatformToken.get(list(scope.platform_token_ids)[0])

    with PlatformApiContext(token.token) as fb_ctx:

        pages = User(fbid='me', api=fb_ctx.api).get_accounts()

        for page in pages:
            print(page)
Example #5
0
# Facebook.

# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from facebook_business.adobjects.user import User
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<APP_SCOPED_USER_ID>'
FacebookAdsApi.init(access_token=access_token)

fields = []
params = {}
print User(id).get_ad_accounts(
    fields=fields,
    params=params,
)
# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from facebook_business.adobjects.user import User
from facebook_business.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<ID>'
FacebookAdsApi.init(access_token=access_token)

fields = [
]
params = {
}
print User(id).get(
  fields=fields,
  params=params,
)
from facebook_business.adobjects.user import User
from facebook_business.api import FacebookAdsApi

app_id = 'COLOCAR_AQUI_SEU_ID_DE_APP'
app_secret = 'COLOCAR_AQUI_SUA_CHAVE_SECRETA'
access_token = 'COLOCAR_AQUI_SEU_TOKEN_DE_ACESSO'

FacebookAdsApi.init(app_id, app_secret, access_token)

me = User(fbid='me')
my_accounts = list(me.get_ad_accounts())
print(my_accounts)
from facebook_business.adobjects.adset import AdSet
from facebook_business.adobjects.adcreative import AdCreative
from facebook_business.adobjects.ad import Ad
from facebook_business.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<ID>'
FacebookAdsApi.init(access_token=access_token)

# User get
fields = []
params = {}
user = User(id).get(
    fields=fields,
    params=params,
)
print 'user', user
user_id = user.get_id()
print 'user_id:', user_id, '\n'

# Get page access token and page_id
fields = [
    'access_token',
]
params = {}
pages = User(id).get_accounts(
    fields=fields,
    params=params,
)
print 'pages', pages
 def __init__(self):
     me = User(fbid='me')
     self.getaccountlist = list(me.get_ad_accounts())
Example #10
0
def facebook_output(clicks, ad_account_id, app_id, access_token, app_secret,
                    metrics, breakdown, start_date, end_date):
    if clicks is not None:
        my_ad_account = ad_account_id
        my_app_id = app_id
        my_access_token = access_token
        my_app_secret = app_secret
        my_metrics = metrics
        my_breakdown = breakdown
        my_start_date = start_date
        my_end_date = end_date
        my_action_type = 'action_type'
        my_level = 'ad'
        my_time_increment = 1
        FacebookAdsApi.init(my_app_id,
                            my_app_secret,
                            my_access_token,
                            api_version='v5.0')
        me = User(fbid="me")
        new_col_list = my_metrics
        # print(new_col_list)
        act = AdAccount(my_ad_account)
        async_job = act.get_insights(params={
            'time_range': {
                'since': my_start_date,
                'until': my_end_date
            },
            'breakdowns': list(my_breakdown),
            'action_breakdowns': my_action_type,
            'level': my_level,
            'time_increment': my_time_increment
        },
                                     fields=list(new_col_list))
        df = pd.DataFrame(async_job)
        dff = df[new_col_list]
        html.Br()
        return html.Div(
            [
                dash_table.DataTable(css=[{
                    'selector':
                    '.row',
                    'rule':
                    'margin: 0; white-space: inherit; overflow: inherit; text-overflow: inherit;'
                }],
                                     id='table',
                                     columns=[{
                                         "name": i,
                                         "id": i
                                     } for i in dff.columns],
                                     data=dff.to_dict("rows"),
                                     export_format="csv",
                                     style_cell={
                                         "fontFamily": "Arial",
                                         "size": 10,
                                         'textAlign': 'left',
                                         'width': '{}%'.format(len(
                                             dff.columns)),
                                         'textOverflow': 'ellipsis',
                                         'overflow': 'hidden'
                                     },
                                     style_table={
                                         'maxHeight': '200px',
                                         'overflowY': 'scroll',
                                         'maxWidth': '1000px',
                                         'overflowX': 'scroll'
                                     },
                                     style_header={
                                         'backgroundColor': '#ffd480',
                                         'color': 'white',
                                         'height': '10',
                                         'width': '10',
                                         'fontWeight': 'bold'
                                     },
                                     style_data={
                                         'whiteSpace': 'auto',
                                         'height': 'auto',
                                         'width': 'auto'
                                     },
                                     tooltip_data=[{
                                         column: {
                                             'value': str(value),
                                             'type': 'markdown'
                                         }
                                         for column, value in row.items()
                                     } for row in dff.to_dict('rows')],
                                     tooltip_duration=None,
                                     persistence=True,
                                     persistence_type='memory'),
            ],
            style={
                'margin-top': 20,
                'margin-left': 300,
                'display': 'table-cell',
                'verticalAlign': 'middle',
                'width': '100%'
            })
Example #11
0
from facebook_business.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<ID>'
FacebookAdsApi.init(access_token=access_token)

# Get page access token and page_id
fields = [
  'access_token',
]
params = {
}
pages = User(id).get_accounts(
  fields=fields,
  params=params,
)
print 'pages', pages
page_id = pages[0].get_id()
print 'page_id:', page_id, '\n'

# Switch access token to page access token
FacebookAdsApi.init(access_token=pages[0].access_token)
# Page feed create
fields = [
]
params = {
  'message': 'This is a test value',
}
pagepost = Page(page_id).create_feed(
  fields=fields,