Monday, April 6, 2009

Twitter client for fun

I was checking the twitter APIs now that I 'm also using it and they are all quite clean (most probably because the underlying API is also clean and complete). I thought I 'd give it a try and got python-twitter http://code.google.com/p/python-twitter/
A client that just receives my latest tweets using PyQt4 was quite easy to build:
import sys
import twitter
from PyQt4.QtGui import QApplication, QMainWindow, QTabWidget, QListView
from PyQt4.QtCore import QAbstractListModel, Qt, QVariant

class TweetsModel(QAbstractListModel):
    def __init__(self, tweets = set()):
        QAbstractListModel.__init__(self)
        self.tweets = tweets

    def rowCount(self, parent):
        return len(self.tweets)

    def data(self, index, role):
        ret = QVariant()
        if ( index.isValid() and index.row() < len(self.tweets)
            and role == Qt.DisplayRole ):
            ret = QVariant(self.tweets[index.row()])
        return ret

class TweetsListView(QListView):
    def __init__(self, parent):
        QListView.__init__(self, parent)

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        
        api = twitter.Api()
        statuses = api.GetUserTimeline("pagles")
        tweets = [s.text for s in statuses]

        self.tabs = QTabWidget(self)
        self.tweetsModel = TweetsModel(tweets)
        self.tweetsList = TweetsListView(self)
        self.tweetsList.setModel(self.tweetsModel)
        self.tabs.addTab(self.tweetsList,self.tr("Tweets"))

        self.setCentralWidget(self.tabs)

class QweetApplication(QApplication):
    def __init__(self):
        QApplication.__init__(self, sys.argv)

if __name__ == "__main__":
    app = QweetApplication()
    mainwindow = MainWindow()
    mainwindow.show()
    exit(app.exec_())
Yes, my username in twitter is pagles in case you followed the code closely :-)

No comments:

Post a Comment