😎
Templates
Google Analytics
Google Drive
Google Search
Google Sheets
Hugging Face
Johns Hopkins
Jupyter Notebooks
Metrics Store
Microsoft Teams
Microsoft Word
Naas Auth
Generate leads from posts
Tags: #linkedin #post #comments #naas_drivers #automation
Author: Alok Chilka

Input

Import libraries

1
from naas_drivers import linkedin, hubspot
2
import pandas as pd
3
import numpy as np
4
import naas
5
from datetime import datetime, timedelta
6
import requests
7
import json
Copied!

Setup your LinkedIn

1
# Lindekin cookies
2
LI_AT = "AQEFALsBAAAAAAbjCtIAAAF_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
3
JSESSIONID = "ajax:42778xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
4
5
# Enter your profile URL
6
PROFILE_URL = "<YOUR_LINKEDIN_PROFILE_URL>"
Copied!

Setup your HubSpot

👉 Access your HubSpot API key 👉 Get your HubSpot owner ID 👉 Get your HubSpot company ID from URL
1
# HubSpot API key
2
HS_API_TOKEN = "<YOUR_HUBSPOT_API_TOKEN>"
3
4
# Your company located after "reports-dashboard/" when you are connected in HubSpot https://app.hubspot.com/reports-dashboard/2474088/view/244930
5
HS_COMPANY_ID = "<YOUR_HUBSPOT_COMPANY_ID>"
6
7
#Hubspot contact URL
8
HS_CONTACT_URL = "https://app.hubspot.com/contacts/"+HS_COMPANY_ID+"/contact/"
9
10
# Contact owner => contact id to whom task needs to be assigned
11
HS_OWNER_ID = "<YOUR_HUBSPOT_API_TOKEN>" #remove double quotes from owner id (to be added as integer value)
12
13
# Time delay to set due date for tasks in days
14
time_delay = 10
15
16
# Calc timestamp
17
tstampobj = datetime.now() + timedelta(days=time_delay)
18
tstamp = tstampobj.timestamp() * 1000
19
20
hs = hubspot.connect(HS_API_TOKEN)
Copied!

Setup your email to receive notifications

1
SEND_EMAIL_TO = "<YOUR_EMAIL_ID>"
Copied!

Model

Get posts from LinkedIn feed

1
df_posts = linkedin.connect(LI_AT, JSESSIONID).profile.get_posts_feed(PROFILE_URL, count=100)
2
df_posts.head()
Copied!

Get likes from LinkedIn posts

1
def get_likes(df_posts):
2
DF_all_post_likes = pd.DataFrame()
3
for index, row in df_posts.iterrows():
4
df = linkedin.connect(LI_AT, JSESSIONID).post.get_likes(row['POST_URL'])
5
DF_all_post_likes = DF_all_post_likes.append(df)
Copied!
1
get_likes(df_posts)
Copied!

Get number of likes by profile

1
def count_likes(df):
2
to_group = ["PROFILE_URN",
3
"PROFILE_ID",
4
"FIRSTNAME",
5
"LASTNAME"]
6
#df = df.groupby(to_group, as_index=False).agg({"PROFILE_ID": "count"}).reset_index(name='count')
7
#df = df.sort_values(by="PROFILE_ID", ascending=False)
8
df2 = df.groupby(['PROFILE_ID']).size().sort_values(ascending=False).reset_index(name='LIKE_COUNT')
9
return df2
10
11
df_counts = count_likes(DF_all_post_likes)
12
df_counts
Copied!

Apply classification to get potential lead

  • Grouping the like count and classify the leads as per levels i.e. L1, L2, L3, L4. ( from highest to lowest counts of likes) with column name "POTENTIAL LEAD"
  • Group posts as per the the column "POTENTIAL LEAD"
1
max_likes = df_counts["LIKE_COUNT"].max()
2
cluster_1 = round(max_likes * 0.1, 0)
3
cluster_2 = round(max_likes * 0.5, 0)
4
cluster_3 = round(max_likes * 0.8, 0)
Copied!
1
conditions = [
2
(df_counts["LIKE_COUNT"] <= cluster_1),
3
(df_counts["LIKE_COUNT"] > cluster_1) & (df_counts["LIKE_COUNT"] <= cluster_2),
4
(df_counts["LIKE_COUNT"] > cluster_2) & (df_counts["LIKE_COUNT"] <= cluster_3),
5
(df_counts["LIKE_COUNT"] > cluster_3)
6
]
7
8
values = ['L4', 'L3', 'L2', 'L1']
Copied!
1
df_counts['POTENTIAL_LEAD'] = np.select(conditions, values)
2
df_counts
Copied!

Get profile details based on the POST_URL above

  • filter rows from "grouped_profile_posts" dataframe based on L1, L2, & L3 levels and add data to dataframe "df_leads"
  • Iterate through dataframe "df_leads" and add items to leads_list
  • Extract EMAIL, FIRSTNAME, LASTNAME, PHONE_NUMBER, OCCUPATION from profile URL
1
df_leads = df_counts.loc[df_counts['POTENTIAL_LEAD'].isin(["L1", "L2"])]
2
df_leads
Copied!
1
leads_list = [];
2
3
r_count = 1
4
5
for index, row in df_leads.iterrows():
6
profileid = row['PROFILE_ID']
7
profileurl = "https://www.linkedin.com/in/"+profileid+"/"
8
9
PROFILECONTACTS = linkedin.connect(LI_AT, JSESSIONID).profile.get_contact(profileurl)
10
PROFILEIDENTITY = linkedin.connect(LI_AT, JSESSIONID).profile.get_identity(profileurl)
11
12
profileemail = PROFILECONTACTS.at[0,'EMAIL']
13
profilephoneno = PROFILECONTACTS.at[0,'PHONENUMBER']
14
profilename = PROFILEIDENTITY.at[0,'FIRSTNAME'] + " "+ PROFILEIDENTITY.at[0,'LASTNAME']
15
profilefirstname = PROFILEIDENTITY.at[0,'FIRSTNAME']
16
profilelastname = PROFILEIDENTITY.at[0,'LASTNAME']
17
profileoccupation = PROFILEIDENTITY.at[0,'OCCUPATION']
18
leads_list.append([profilename, profilefirstname, profilelastname, profileemail, profilephoneno, profileoccupation, profileurl])
19
r_count = r_count + 1
Copied!

Create hubspot contacts from linkedin likes

HS_CONTACT_ID_LIST
- The list to store the contact id recently created and the linkedin profile URL of associated contact
1
#to store the resulting output of create contact method
2
contact_id = ""
3
HS_CONTACT_ID_LIST = []
4
for i in leads_list:
5
profilename = i[0]
6
profilefirstname = i[1]
7
profilelastname = i[2]
8
profileemail = i[3]
9
profilephoneno = i[4]
10
profileoccupation = i[5]
11
profileurl = i[6]
12
# With send method
13
data = {"properties":
14
{
15
"linkedinbio": profileurl,
16
"firstname": profilefirstname,
17
"lastname": profilelastname,
18
"jobtitle": profileoccupation,
19
"email": profileemail,
20
"phone": profilephoneno,
21
"hubspot_owner_id": 111111086,
22
}
23
}
24
#write data to CRM ( create new contact in CRM)
25
26
contact_id = hs.contacts.send(data)
27
HS_CONTACT_ID_LIST.append([contact_id, profileurl])
Copied!
Build Email Template
- This includes the hubspot contact_id, contact URL and LinkedIN URL
1
table_header = f'<table style="border-collapse:collapse;border-spacing:0;font-family:Arial"><thead><tr><th style="border-color:black;border-style:solid;border-width:1px;padding:6px 10px;text-align:left">Contact ID</th><th style="border-color:black;border-style:solid;border-width:1px;padding:6px 10px;text-align:left">Hubspot URL</th><th style="border-color:black;border-style:solid;border-width:1px;padding:6px 10px;text-align:left">LinkedIN URL</th></tr></thead><tbody>'
2
table_body = ''
3
table_footer = '</tbody></table>'
4
5
for i in HS_CONTACT_ID_LIST:
6
hs_contact_url = HS_CONTACT_URL + i[0]
7
linkedin_url = i[1]
8
tablerow = '<tr><td style="border-color:black;border-style:solid;border-width:1px;padding:6px 10px;">'+i[0]+'</td><td style="border-color:black;border-style:solid;border-width:1px;padding:6px 10px;">'+hs_contact_url+'</td><td style="border-color:black;border-style:solid;border-width:1px;padding:6px 10px;">'+linkedin_url+'</td></tr>'
9
table_body = table_body + tablerow
10
11
table = table_header + table_body + table_footer
12
13
email_body = f'<p style="font-family:Arial">Hi there,</p><br/><p style="font-family:Arial">Following new task(s) has been created for you :</p><br/>'+table
Copied!

Output

Create tasks for user and send email notification

1
def create_task(owner_id,
2
tstamp,
3
contact_id,contact_props,contact_linkedin_url,hs_contact_url,engagement="TASK"):
4
""" owner_id=HS_OWNER_ID, tstamp=tstamp, subject=subject, body=body, status=status, engagement="TASK"
5
Engagement type = TASK | NOTE | EMAIL | MEETING | CALL
6
"""
7
8
payload = json.dumps({
9
"engagement": {
10
"active": 'true',
11
"ownerId": 111111086,
12
"type": "TASK",
13
"timestamp": tstamp
14
},
15
"associations": {
16
"contactIds": [1551],
17
"companyIds": [],
18
"dealIds": [],
19
"ownerIds": [],
20
},
21
22
"metadata": {
23
"body": "Hi there, you need to contact following user & task is already assigned to you.<br/>" + "Name :" +contact_props['firstname']+ contact_props['lastname'] + " Contact URL : " + hs_contact_url,
24
"subject": "Task created for Contact ID :"+ contact_id,
25
"status": "NOT_STARTED",
26
"forObjectType": "CONTACT"
27
}
28
});
29
url = "https://api.hubapi.com/engagements/v1/engagements"
30
params = {"hapikey": HS_API_TOKEN}
31
headers = {'Content-Type': "application/json"}
32
# Post requests
33
res = requests.post(url,data=payload,headers=headers,params=params)
34
35
# Check requests
36
try:
37
res.raise_for_status()
38
except requests.HTTPError as e:
39
raise (e)
40
res_json = res.json()
41
42
# Fetch the task id of the current task created
43
task_id = res_json.get("engagement").get("id")
44
print("🎆 Task created successfully: ", task_id)
45
46
return res_json
Copied!
1
TASK_ID_LIST = []
2
for i in HS_CONTACT_ID_LIST:
3
contact_id = i[0]
4
contact = hs.contacts.get(contact_id)
5
contact_props = contact.get('properties')
6
contact_linkedin_url = i[1]
7
hs_contact_url = HS_CONTACT_URL + contact_id
8
#print(hs_contact_url)
9
result = create_task(owner_id=HS_OWNER_ID,
10
tstamp=tstamp,
11
contact_id=contact_id ,
12
contact_props = contact_props,
13
contact_linkedin_url=contact_linkedin_url,
14
hs_contact_url = hs_contact_url,
15
engagement="TASK")
16
TASK_ID_LIST.append(result.get("engagement").get("id"))
Copied!
1
if not TASK_ID_LIST:
2
print("No tasks created")
3
else:
4
email_to = SEND_EMAIL_TO #to send the report
5
subject = "LinkedIN Leads Alert"
6
content = email_body
7
8
naas.notification.send(email_to=email_to, subject=subject, html=content)
Copied!
1
Copied!
Copy link
Edit on GitHub