Friday, September 12, 2014

Find strings in your facebook chat history

Hi,

I've lost a number which my friend gave in facebook chat. But I couldn't remember when he gave it. So, rather than checking all those previous messages manually, I ended up writing a program which would search for a string in facebook chat history.

So, there are three steps involved in this program:

1. Find the id of that conversation
2. Request to the graph api
3. Iterate through the paged responses

To accomplish the first task, send a request to 'user/inbox' node of the graph api. You would find a list of conversations each with it's own id. Find your desired one. It's possible to come up with a program to find it automatically, however, I'm gonna settle for this much for now.

Now, define these three functions:

import requests
from facepy import GraphAPI
import re

def search_in_message(message):
    for m in message['data']:
        try:
            matched_obj = re.match('(\d+)', m['message'], flags=0)
            if matched_obj:
                print m['message']
                print m['created_time']
                print matched_obj.group()
        except KeyError:
            continue
def get_message_from_graph(graph, stream_id, limit, since):
    return graph.get(stream_id + '/comments?limit='+str(limit)+'&since='+str(since))

def get_next_page(next_url):
    return requests.get(next_url).json()
Each methods should be self explanatory. However, we can achieve different results, like a specific number, pattern, string in the messages just by modifying the search_in_message function. I've given it the shape to find numbers in the conversation. The later parts are pretty straightforward:
token = 'your_secret_token'
graph = GraphAPI(token)

paged_messages = get_message_from_graph(graph, 'your_conversation_id', your_limit, your_since_timestamp)

while paged_messages['paging']['next']:
    print paged_messages['paging']['next']
    search_in_message(paged_messages)
    paged_messages = get_next_page(paged_messages['paging']['next'])

No comments:

Post a Comment