Sunday, July 11, 2010

rot13 (or other scripts) with Konversation

Recently, I needed a rot13 encoder / decoder for an IRC channel. It's a simple, stupid "encryption", a Caesar algorithm with 13 letters. It's often used to mask spoilers.

Now, Konversation is an awesome IRC client for KDE, but obviously not meant to be extended by such scripts currently. Still (with much help from #konversation! :) I found a working solution which is not *too* hackish.
So, we want every incoming message prefixed with rot13: to be decrypted, and every outgoing one beginning with rot13: to be encrypted.

Crypting outgoing messages is easy. Just place this script into /usr/share/kde4/apps/konversation/scripts (or more general, $KDEDIR/apps/konversation/scripts):
#!/usr/bin/env python

import subprocess
import sys, os

message = ' '.join(sys.argv[3:])
message = message.encode('rot13')
message = "rot13:"+message

SERVER = sys.argv[1];
TARGET = sys.argv[2];

subprocess.Popen(['qdbus', 'org.kde.konversation', '/irc', 'say', SERVER, TARGET, message])
This is a quite easy python script; python already has rot13 encoding / decoding (that's the same, by the way) built in. The only sophisticated thing we do here is the last line, which tells Konversation to post the message we typed to the server ("say").
Now, we need to tell Konversation to call that script; go to Settings -> Configure Konversation -> Auto replace and add a new rule. Enable regular expression. Our regular expression could look like this: ^rot13:(.*). Our replacement pattern is  /exec rot.py %1, where %1 will be replaced by the message by Konversation. We use this message in the python script via the line ' '.join(sys.argv[3:]) (because the first 3 entries in sys.argv are things like the script name, et cetera).

Decrypting incoming messages is quite more hack-ish, as if you just do it like described above, the /exec won't be interpreted; probably for security reasons.
Thus, do the following:
Go to Configure Konversation -> Highlights. Add a new one, enable Regular expression, set the color to black. The regular expression we use for matching is the same like above; "Auto text" seems to be the replacement pattern, so we can add the same like above here, too; we just need another scriptname, rot-decrypt.py for example. Save this script in the mentioned location with the exact name you just entered: 
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import subprocess
import sys, os

message = ' '.join(sys.argv[3:])
message = message.encode('rot13')
message = "decoded:"+message

subprocess.Popen(['qdbus', 'org.kde.konversation', '/irc', 'info', message])
It is different from the encryption script in not posting a message to the server, but displaying an info ('info') locally on your screen instead. This works quite well; the only pitfall is that the info will appear in the current channel window, not in the window where the message was originally posted. But I can live with that.

No comments:

Post a Comment