I've made this code to extract a conversation from a Skype database file with a certain user ID, all this being specified as a command line argument.
Since Skype uses SQLite to store the messages I can use the
sqlite3 Python module to retrieve the messages.
The code first checks for the database file, opens it if it exists, parses it and finally outputs the chat either to stdout or a specified output file (it uses the partner's ID by default if nothing is provided). The output looks somewhat like what you would expect from an IRC conversation.
I'm quite satisfied with the script in general however I had several issues with unicode characters which made me have to use some "cheats". I'm not satisfied with all these
unicode() conversions, and the fact I have to specify once more at the end via
encode('utf-8') that I am indeed going to output other things than ASCII. I also think this code could be made more elegant, especially with the SQL query. If I ever want to add more options, such as sorting, I feel like putting everything in the SQL query looks ugly.
#!/usr/bin/env python2 # charset=utf-8 from __future__ import print_function import sys import sqlite3 import os.path import datetime import HTMLParser def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def eprint_use(): eprint("usage : " + sys.argv + " <file.db> <partner's skype ID> [output file]") # actual code here # first of all check argv and print the help message if it's wrong if not len(sys.argv) in [3, 4]: eprint_use() else: database_path = sys.argv partner_id = sys.argv output_path = sys.argv if len(sys.argv) == 4 else partner_id + '.txt' if not os.path.isfile(database_path): sys.exit('the file %s does not exist' % (database_path)) output_file = sys.stdout if output_path == '-' else open(output_path, 'w') connection = sqlite3.connect(database_path) cursor = connection.cursor() parser = HTMLParser.HTMLParser() cursor.execute(""" SELECT timestamp,from_dispname,body_xml FROM Messages WHERE dialog_partner='""" + partner_id + """' ORDER BY timestamp """) for row in cursor.fetchall(): timestamp = unicode(datetime.datetime.utcfromtimestamp(int(row)).strftime('%Y-%m-%d %H:%M:%S')) name_tag = unicode(row) message_body = unicode(parser.unescape(unicode(row))) output = "[%s] <%s> %s\n" % (timestamp, name_tag, message_body) output_file.write(output.encode('utf-8'))
Please keep in mind that I've barely been actively programming in Python for about a year and a half. I try to make my code as pythonic as possible, but as primarily being a C programmer I tend to neglect some of the aspects of the python language in favour of "C-tricks". If you see any such thing, please tell me as well.