Skip to content

Instantly share code, notes, and snippets.

@sehrishnaz
Created November 22, 2021 10:22
Show Gist options
  • Save sehrishnaz/71088470fd1058322650c5baa88e2297 to your computer and use it in GitHub Desktop.
Save sehrishnaz/71088470fd1058322650c5baa88e2297 to your computer and use it in GitHub Desktop.
Automate Facebook Post to Groups using Graph API and Python
import json
from facebook import GraphAPI
import pandas as pd
import time
import secrets
import random
def read_creds(filename):
'''
Store API credentials in a safe place.
If you use Git, make sure to add the file to .gitignore
'''
with open(filename) as f:
credentials = json.load(f)
return credentials
credentials = read_creds('credentials.json')
graph = GraphAPI(access_token=credentials['access_token'])
message = '''
Add your message here.
'''
# get groups whihc you have joined
post = graph.get_object(id='me',fields='groups')
my_groups = post['groups']['data']
print('----------',post['groups']['data'])
# post in groups after below seconds
post_after = [600, 720, 840, 900]
groups = []
for mg in my_groups:
if 'privacy' in mg:
if mg['privacy'] != 'CLOSED':
groups.append(mg['id'])
else:
groups.append(mg['id'])
# open the file
df = pd.read_excel("links_description.xlsx", sheet_name=0)
for lp in range(df.shape[0]):
post = random.randint(0,df.shape[0]-1)
message = df.tag[post] + '\n' + df.description[post] + '\n'
link = df.link[post]
wait_sec = secrets.choice(post_after)
random_group = secrets.choice(groups)
print('******Auto Posting Start After %s Seconds*******' % (wait_sec))
time.sleep(wait_sec)
print('1111111',random_group,df.link[post])
graph.put_object(random_group, 'feed', message=message, link=link)
print('******Link Posted*******',post)
@sehrishnaz
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment