Meet Marvin, our Twitter meta-bot

August 26th, 2010 by ger

It all started with a small Twitter project for a client. Then we began thinking about different ideas for twitter bots (not many of them became an actual product but we had a lot of ideas at that time).

It didn’t take too much time to realize that implementing each bot from scratch didn’t make sense. Specially when changes from Twitter’s side have an important impact on each developed bot (like deprecating basic authentication in favor of OAuth).

So we decided to create Marvin: our own meta-bot in charge of handling everything except creating the tweet itself.

Design and Implementation

The idea was to simplify the process of creating a new Twitter bot. Marvin will handle all the repetitive tasks and let each bot concentrate on doing what needs to be done and nothing else.

What does Marvin offer to us:

  • OAuth authentication
  • Logging
  • Data persistence
  • Debugging
  • More to come…

We implemented Marvin using oauth-python-twitter which provides us with a simple API to communicate with Twitter. Instead of wrapping this API within Marvin, we let each bot use it directly since that gives us a lot of flexibility and it’s very simple to use. We might review this in the future to allow a more powerful debug mechanism.

A bot is implemented as a simple python module which must define the consumer key and consumer secret for the application (defined in Twitter) and implement a run method that will be executed by Marvin:

# Twitter application configuration
# These are fake keys!
CONSUMER_KEY = "j28Rup5fr4thUwruXAP2f"
CONSUMER_SECRET = "j28Rup5fr4thUwruXAP2fj28Rup5fr4thUwruXAP2f"

from datetime import datetime

def run(twitter, data, log):
    # Create your tweet, probably getting information
    # from some external source
    count = data.get("count", 1)
    message = "Tweet number %d: Marvin has something to tell you..." % count

    # Post the message using oauth-python-twitter API
    log.info("Tweetting: " + message)
    twitter.PostUpdate(message)

    # Save the count number for the next execution
    data["count"] = count + 1

As you can see, implementing a bot is very simple since we only have to worry about the tweet and nothing else!

One of the features implemented by Marvin is data persistence. Normally, a bot will have to save information from one execution to the next and we need to provide a way of doing that easily. In the previous example we stored the count number just to show you how it’s done.

To solve that problem we use pickle, a Python module for serializing and deserializing objects. As expected, Marvin will handle saving and restoring the data for you. You just need to store what you need there and read it in the next executing…

Running Marvin

Once Marvin has successfully logged in to an account (for a particular bot instance) we tell him to execute the actual bot process using the following command:

ger@piazzolla:~/projects/marvin$ python marvin.py run bot

In this example, our bot is implemented in bot.py module.

To execute the bot periodically we decided to use cron, which led us to the next section…

Why cron?

We thought about using an in-process task scheduler for Python, like APScheduler but cron’s simplicity and stability was a really apealing reason for us.
With cron running Marvin is as simple as adding this line to the cron’s table:

*/1 * * * * cd $MARVIN_HOME; python marvin.py run bot

In this example Marvin will execute the bot every single minute (don’t worry, we won’t do that!)

We haven’t dismissed APScheduler for future versions, but for now we are very happy with the results we get from using cron.

How to handle OAuth authentication with a command line bot?

Using OAuth from command line is not as simple as it seams. From a web application you are normally redirected to Twitter were you authorize it to access your Twitter account. Everything is simple and with a couple of clicks you are ready to go. But we don’t have a web application or a web browser to be redirected!

The solution for us was to use PIN-based OAuth mechanism created by Twitter. We just tell Marvin that we want to login using the following command:

ger@piazzolla:~/projects/marvin$ python marvin.py login bot
Authorization URL: http://twitter.com/oauth/authorize?&oauth_consumer_key=FjZYXIe7z8X6rRHvXjGzrA&oauth_signature_method=HMAC-SHA1
Enter OAuth PIN:

Using this approach we need to open the authorization URL, allow the application to access Twitter (defined by CONSUMER_KEY and CONSUMER_SECRET) and enter the given PIN as shown below:

Enter OAuth PIN: 9823410
Marvin logged in successfully. You can now start using your bot!

Marvin will use this PIN to retrieve the access token from Twitter and will save it for us. Using this access token we will be able to access the authorized Twitter account transparently.

Is this all?

Definitely not. We are planning to add more features to Marvin, like autofollow based on different queries, automated DM responses and much more. You’ll be hearing more about this once we implemented these new features.

Also, based on the reaction we get from this post, we might consider publishing Marvin as the first devartis’ open-source project.

We now invite you all to follow @futbolar, our first bot implemented using Marvin.

We’re moving!

August 4th, 2010 by ger
Big day for devartis! We are moving to our new offices, and we couldn’t be more thrilled about it. Until now we were basically nomads, constantly moving from Fernando’s house to German’s and to Claudio’s and so on… We even worked from Llavallol! At Poli’s place.
This is finally over and now we have a stable place to work.
The office is really nice, located in a quiet neighborhood in Palermo. It has some features that make us very happy, like many whiteboards, a running machine and even a climbing wall!
In case you want to visit us or mail us something, our new address is:
Soler 3982 1°, Palermo
Buenos Aires
Argentina

Mushroom.es Launched

May 17th, 2010 by devartis

Today devartis is proud to announce the launch of our latest web development: mushroom.es

Mushroom is a graphic and audiovisual production company, featuring the most innovative artists in the European continent.

Home page

mushroom.es home page

During the last few months we worked together with boldsensation and the creative staff at Mushroom to create their new portfolio web site built on top of jQuery and Django technologies. The site makes intensive use of JS and AJAX to achieve a rich user experience.

News

mushroom.es news page

In the backend, a powerful and flexible administrator gives Mushroom full control over the portfolio allowing them to change and customize their site with no technical knowledge.

To summarize, we are very happy with the result and with the fact that we were able to create a dynamic and highly interactive site using only standard and open technologies like JavaScript without the need to appeal to Flash. Finally, we invite you to evaluate the results by yourself and make your own conclusions.

A first glance over Wolfram|Alpha's Webservice API

October 21st, 2009 by poli

A few days ago Wolfram|Alpha announced the release of their Webservice API to allow the usage of their computational knowledge engine on user’s applications. The API allows clients to submit free-form queries which return information in a variety of formats.

As you might know, Wolfram|Alpha is not a search engine, but an answer engine that answers free-form queries and computational requests by computing answers using structured data. This contrasts from traditional search engines that return as an answer a list of documents or web pages that might or not contain the answer the user is looking for. Wolfram|Alpha also is capable of processing and answering natural language queries (as it’s predecessor START) such as What is the second largest southamerican country by area?

In order to be able to use the API you must first apply for an Application ID, which is a string that identifies an application that uses the API, and it must be supplied in all calls to the API. There is no free of charge API availability as of today: Wolfram|Alpha offers three different licensing plans each having different pricing and request limits.

The request, apart from the query text, can be configured with a rich variety of options that are out of scope of this post entry. These options allow users to control timeouts for the queries, to control which result components (pods) will be processed and also to specify which ones should be to be retrieved asynchronously. The API request can be geo-localized as users can feed the engine with a location description such as “Buenos Aires, Argentina”, a latitude-longitude pair (-34.61,-58.37) or an IP address if you wish to propagate the IP of the user interacting with your application to the engine.

The REST-style API provides structured XML output formatted as image, text, audio or styled HTML. These output formats are known as Visual Representations. The main information unit in the response is the pod, which is corresponds to a result category and contains one or more subpods which is the unit that contains the actual information. A simplified xml response looks like:

<?xml version='1.0' encoding='UTF-8'?>
<queryresult success='true' error='false' numpods='5'
    datatypes='DNAString' timedout='' timing='0.914' parsetiming='0.167'>
 <pod title='Input interpretation' scanner='Identity' position='100' error='false' numsubpods='1'>
  <subpod title=''>
   <plaintext>GATTACACCAGGATAAC (genome sequence)</plaintext>
  </subpod>
 </pod>
... pods deleted for brevity ...
</queryresult>

Several language bindings for the API are available and others are being developed. The python binding is composed by a WolframAlphaEngine object that allows creating a WolframAlphaQuery which can be processed by the engine to obtain a WolframAlphaQueryResult. This result object is composed by Pod objects that can be iterated to get the desired information. Some examples of the python binding in action are included in the API distribution:

import wap

appid = 'XXXX' # Use your app id
waeo = wap.WolframAlphaEngine(appid)
waeq = wap.WolframAlphaQuery('who are you?', appid)
waeq.ScanTimeout = '3.0'
waeq.Async = False
waeq.ToURL() # After configuring the waeq must call ToURL()

result = waeo.PerformQuery(waeq.Query) # result is in xml format
waeqr = wap.WolframAlphaQueryResult(result)

for pod in waeqr.Pods():
  waep = wap.Pod(pod)
  print '\n%s: (%d subpods)' % (waep.Title(), waep.NumSubpods())

After a quick overview the API looks very promising for commercial applications that can take advantage of Wolfram|Alpha’s advanced computation capabilities. Nevertheless it would be great to see what would happen if guys at Wolfram provide free-of-cost access for free software applications.

Musikalisches Würfelspiel – Hacking music composition

September 25th, 2009 by fer

I’ve been playing music instruments for a long time in my life, never seriously though. Lately I’ve been taking piano lessons and also decided to get a little further in music theory and composition.

So I started reading whatever books and lessons I could find. The book Harmony by Walter Piston is very easy to read if you are in a beginning level of music theory and want to learn about harmony. Something caught my attention in this book. At the beginning of chapter III (Mayor mode harmonic progressions) there’s a table that says:

The following table is based in the observation of common uses of the compositors.

  • The I degree is followed by the IV or V, sometimes the VI, and less frequently the I or III.
  • The II degree is followed by the V, sometimes the IV or the VI, and less frequently the I or III.
  • The III degree is followed by the VI, sometimes the IV, and less frequently the I, the II or the V.
  • ….

A chord progression is a series of musical chords based on a root chord (I) establishing a tonality. The degrees of the progression represent the distance to the root chord in the scale. i.e. If the root chord is C the IV degree is F and the V is G. So this table sets a pattern for building chord progressions based on common uses by the compositors.

Being a software developer is hard not to see this table as a set of business rules. So when I read this I wondered: What if I could program this almost accurate business rules and randomly generate mayor chord progressions? And what if, based on the generated chord progression, I could randomly generate a melody over it? What if I don’t? This would be fun to try anyway, I would be learning music and programming at the same time, so no loss.

Before going to the computer I decided to prove the concept in a simpler way, I picked my guitar and a six-sided dice and wrote on a paper the following table:

1, 2, 3 use general rule
4, 5 use “sometimes” rule
6 use “less frecuently” rule

And when I had to choose between various options I threw the dice again. The first random generated progression I got was: C – F – G – F. Not bad at all. Actually it shouldn’t be a surprise that the progression sounded nice to the ear since what this rules tend to do is to have a C – F – G – C progression as ideal. You will find thousands of hits that made it with this (I-IV-V) progression, Twist and shout by The Beatles, Beverly Hills by Weezer, Wild Thing  by The Troggs, Auto rojo by Vilma Palma, etc.

I decided to use an array of arrays for the progression rules, having the current chord as an index the elements inside that position will give me the candidates for the next chord. For the frecuency I repeated the most frequent elements.

C_SCALE = ['C', 'D', 'E', 'F', 'G', 'A', 'B']
F_PROG = [[5, 5, 5, 4, 4, 4, 6, 6, 1, 3],
    [5, 5, 5, 4, 4, 6, 6, 1, 3],
    [6, 6, 6, 4, 4, 1, 2, 5],
    [5, 5, 5, 1, 1, 2, 2, 3, 6],
    [1, 1, 1, 4, 4, 6, 6, 2, 3],
    [2, 2, 2, 5, 5, 3, 3, 4, 4, 1],
    [1, 1, 1, 3, 3, 3, 6, 6, 2, 4]]

def get_next_chord(chord):

    index = C_SCALE.index(chord)
    candidates = F_PROG[index]
    return C_SCALE[random.choice(candidates)-1]

So now that I had a working concept I started looking for python libraries to make sounds with the computer. However I decided to go with midi libraries since using the speaker would make my songs sound like a golden axe weapon.
The library I used is PMIDI no particular reason but that it works and its easy.

For the melody I decided to use my basic knowledge about improvisation.  The rules are, use any note of the scale of the root chord, but it’s always beter to use notes of the chord. Also, we dont want to “jump” too much between notes, say from C to A and then back to D, etc. So I added a rule to make it unlikely for this to happen and try to stay in a 3-note range.

You can listen here, what you’ve been waiting for, an example of the results. I hope you like it! And if you do you can see the source code in here.

So what does Musikalisches Würfelspiel mean? Actually when I did a little research I found this concept is not new, this name was given to a music dice game to generate random minuets in the 18th century. Also Wolfram made a very interesting online version of this kind of program which is called Wolfram Tones so you can check out the not-so-interesting-as-my songs in their site.

Welcome!

September 16th, 2009 by devartis

In this blog people working at devartis will be posting our experiences, company news and events and also development stuff and hacks we want to share. We are restless and curious and we want to keep the doors of our company open so here you’ll find what are we on to.
You will find posts of some of the technologies devartis is working with such as Python, Ruby, iPhone apps, etc.
We expect to update this blog every two weeks so stay tuned or subscribe to the RSS. You may also follow us on twitter and we will let you know when we post.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes