Publish to a Facebook group with requests / Python without the API

1
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import datetime
import json
import logging
import re
import random
import requests
import shutil
from pyquery import PyQuery as pq


def main(username, password, page, imgurURL):

    logging.basicConfig(filename='imgur2fb.log', level=logging.DEBUG)

    session = requests.session()

    uid, dtsg = login(session, username, password)

    grupoID = "580864492030176" #(Fijo)

    postToFacebook(session, dtsg, grupoID, "Prueba 55",uid)


def login(session, username, password):

    '''
    Login to Facebook
    '''

    # Navigate to the Facebook homepage
    response = session.get('https://facebook.com')

    # Construct the DOM
    dom = pq(response.text)

    # Get the lsd value from the HTML. This is required to make the login request
    lsd = dom('[name="lsd"]').val()

    # Perform the login request
    response = session.post('https://www.facebook.com/login.php?login_attempt=1', data={
        'lsd': lsd,
        'email': username,
        'pass': password,
        'default_persistent': '0',
        'timezone': '-60',
        'lgndim': '',
        'lgnrnd': '',
        'lgnjs': '',
        'locale':'en_GB',
        'qsstamp': ''
    })

    '''
    Get the users ID and fb_dtsg token. The fb_dtsg token is required when making requests as a logged in user. It
    never changes, so we only need to grab this token once.

    If the login was successful a cookie 'c_user' is set by Facebook. If the login failed, the 'c_user' cookie
    will not be present. This will raise an exception.
    '''
    try:
        uid = session.cookies['c_user']
        dtsg = re.search(r'(type="hidden" name="fb_dtsg" value="([0-9a-zA-Z-_:]+)")', response.text).group(1)

        dtsg = dtsg[dtsg.find("value")+6:]
        dtsg = dtsg[1:-1]

    except KeyError:
        raise Exception('Login Failed!')

    return uid, dtsg


def postToFacebook(session, dtsg, pageID, message,uID):

    data = {        #'composertags_place_name': '',

          '__a':'1',
          '__af':'iw',
          '__be':'-1',
          '__dyn':'',
          '__pc':'EXP3:DEFAULT',
          '__req':'',
          '__rev':'',
          '__user':uID,

        'album_id':'',  
        'attachment':'',    
        'audience':'',
        'backdated_date[year]':'',
        'backdated_date[month]':'',
        'backdated_date[day]': '',
        'backdated_date[hour]':'',  
        'backdated_date[minute]':'',      
        'boosted_post_config':'',   
        'composer_entry_time':'', #Tenia un valor
        'composer_session_duration':'', # Tenia un valor
        'composer_session_id':'',
        'composer_source_surface':'group',
        'composertags_city':'',
        'composertags_place':'',
        'direct_share_status':'0',
        'fb_dtsg': dtsg,    
        'feed_topics':'',
        'future_date':'',    
        'future_time':'',   
        'is_explicit_place': 'false',
        'is_forced_reshare_of_post':'',
        'is_markdown':'false',
        'is_profile_badge_post':'false',
        'is_q_and_a':'false',
        'is_react': 'true',
        'logging':'', # Tenia un valor
        'multilingual_specified_lang':'',
        'num_keystrokes':'', # Tenia un valor
        'num_pastes':'0',
        'post_surfaces_blacklist':'',
        'privacyx':'',
        'prompt_id':'',
        'prompt_tracking_string':'',
        'ref':'group',
        'scheduled': 'false',
        'scheduled_publish_time':'',
        'sponsor_relationship':'0',
        'target_type':'group',
        'xc_disable_config[xc_disable_link]':'',
        'xc_sticker_id':'0',
        'xhpc_aggregated_story_composer':'false',
        'xhpc_composerid':'', # tenia un valor
        'xhpc_context': 'profile',  
        'xhpc_finch': 'false',
        'xhpc_fundraiser_page':'false',
        'xhpc_ismeta': '1',
        'xhpc_message_text': message,
        'xhpc_message': message,
        'xhpc_modal_composer':'false',
        'xhpc_origintopicfeedid':'',
        'xhpc_publish_type':'1', 
        'xhpc_socialplugin':'false',
        'xhpc_targetid': pageID,
        'xhpc_timeline': 'false',
        'xhpc_topicfeedid':'',
    }

    response = session.post('https://www.facebook.com/ajax/updatestatus.php?av='+str(uID)+'&dpr=1',
                            data=data,

                            headers = {'Content-Type':'application/x-www-form-urlencoded'})

try:
    main(username='******', password='*******', page='*****', imgurURL='imgurURL=http://imgur.com/search?q=funny')
except Exception, e:
    logging.exception(e)
    print e

I have this code partly done by me, partly based on a code to post on a Facebook page that does not work anymore. Log in well, answer 200, but return this error message when posting

  

for (;;); {"__ ar": 1, "__ sf": "iw", "error": 1367001, "errorSummary": "I do not know   You can post in this biography "," errorDescription ":" The message   could not be posted to this   Timeline. "," Payload ": null," bootloadable ": {}," ixData ": {}," lid ":" 6409190691856604279 "}

I do not want to use the Facebook API for several reasons, one is educational, the other is that the permission to publish in a group requires review by Facebook, send them a kind of documentation / video on how the APP is used, etc. The most likely thing is that it is failing in some of all the variables posts that I have to send, but I do not find that it can be.

    
asked by Pablo 15.04.2017 в 13:32
source

1 answer

0

Well, if anyone is interested, here I managed to make a code that works but only to send text, using the mobile interface of Facebook that is simpler. Uploading with images I have not achieved yet. The id of the group is hard-coded, it can be removed by making a query to one of the websites that return the id of a group with their name.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import datetime
import json
import logging
import re
import random
import requests
import shutil
from pyquery import PyQuery as pq


def main(username, password, page):

    logging.basicConfig(filename='imgur2fb.log', level=logging.DEBUG)

    session = requests.session()

    uid, dtsg = login(session, username, password)

    grupoID = "580864492030176" #(Fijo)

    postToFacebook(session, dtsg, grupoID, "Prueba 98765",uid)


def login(session, username, password):

    '''
    Login to Facebook
    '''

    # Navigate to the Facebook homepage
    response = session.get('https://facebook.com')

    # Construct the DOM
    dom = pq(response.text)

    # Get the lsd value from the HTML. This is required to make the login request
    lsd = dom('[name="lsd"]').val()

    # Perform the login request
    response = session.post('https://www.facebook.com/login.php?login_attempt=1', data={
        'lsd': lsd,
        'email': username,
        'pass': password,
        'default_persistent': '0',
        'timezone': '-60',
        'lgndim': '',
        'lgnrnd': '',
        'lgnjs': '',
        'locale':'en_GB',
        'qsstamp': ''
    })

    '''
    Get the users ID and fb_dtsg token. The fb_dtsg token is required when making requests as a logged in user. It
    never changes, so we only need to grab this token once.

    If the login was successful a cookie 'c_user' is set by Facebook. If the login failed, the 'c_user' cookie
    will not be present. This will raise an exception.
    '''
    try:
        uid = session.cookies['c_user']
        dtsg = re.search(r'(type="hidden" name="fb_dtsg" value="([0-9a-zA-Z-_:]+)")', response.text).group(1)

        dtsg = dtsg[dtsg.find("value")+6:]
        dtsg = dtsg[1:-1]

    except KeyError:
        raise Exception('Login Failed!')

    return uid, dtsg


def postToFacebook(session, dtsg, pageID, message,uID):

    data = {
        "[0]":"",   
        "[1]":"",
        "__ajax__":"",  #AYmIVqL7VfighmiRmFWSBGl6Aucepl7b-I5RPZaAyEEk7rT-6UQQ2zOpUe433RwWQaZACpH9gA--j8otSHry0_Kmd6iZtK2QHyufgZ59eoLtwA
        "__dyn":"",#    1KQdAm1mxu4UpwDF3GAgy6K6Acgy6F8mxq2K2i5U9EowRwFzohxO3J0GwywlEf8lwJwsE2xCyoe8hwv9E887u4o2CyUb852i1gw
        "__req":"",#    e
    "__user":"100016215514801",
    "album_fbid":"0",
    "appid":"", 
    "at":"",    
    "backdated_day":"", 
    "backdated_month":"",   
    "backdated_year":"",
    "ch":"",    
    "csid":"",  #b4f44053-0da3-46b8-8c54-782fb428a624
    "fb_dtsg":dtsg, #AQEHse9gjZYA:AQGng01UK1fd
    "freeform_tag_place":"",    
    "fs":"",    
    "internal_extra":"",
    "is_backdated":"",  
    "iscurrent":"", 
    "linkUrl":"",   
    "link_no_change":"",    
    "loc":"{}",
    "m_sess":"",    
    "message":message,# prueba 88
    "npa":"",   
    "npc":"",   
    "npn":"",   
    "npp":"",   
    "npw":"",
    "npz":"",   
    "ogaction":"",  
    "oghideattachment":"",  
    "ogicon":"",    
    "ogobj":"", 
    "ogphrase":"",  
    "ogsuggestionmechanism":"",
    "rating":"0",
    "scheduled_am_pm":"",   
    "scheduled_day":"",
    "scheduled_hours":"",   
    "scheduled_minutes":"", 
    "scheduled_month":"",   
    "scheduled_year":"",
    "sid":"",   
    "source_loc":"composer_group",
    "target":pageID,
    "text_[0]":"",
    "text_[1]":"",  
    "unpublished_content_type":"0",
    "waterfall_id":"988d79257398ec678a8e287046f322ca",  # Esto cambia en cada logueo??
    "waterfall_source":"composer_group"

    }


    response = session.post('https://m.facebook.com/a/group/post/add/?gid='+pageID+'&refid=18',

                            #params=params,
                            data=data,
                            #headers = {'content-type': 'multipart/form-data'})
                            headers = {'Content-Type':'application/x-www-form-urlencoded'})

    print response


try:
    main(username='j*****', password='****', page='https://www.facebook.com/groups/linkdelgrupo')
except Exception, e:
    logging.exception(e)
    print e
    
answered by 17.04.2017 / 20:06
source