# HG changeset patch # User Mikael Berthe # Date 1353866491 -3600 # Node ID 62248d5fbb2451cbddf845fc2a03e00217a13952 # Parent 31f967ba9e1fc020b366eb5e16d1e786e07d7f1d Add shortenurl module, based on isbear's code This code is derivated from the lua example script shortenurl.lua in isbear's lua module for mcabber. diff -r 31f967ba9e1f -r 62248d5fbb24 mcbot/cmds/shortenurl.lua --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mcbot/cmds/shortenurl.lua Sun Nov 25 19:01:31 2012 +0100 @@ -0,0 +1,62 @@ + +-- This module is derivated from isbear's shortenurl function: +-- http://hg.lilotux.net/mod-mcabber-lua/file/tip/examples/shortenurl.lua +-- +-- * Copyright (C) 2012 Myhailo Danylenko +-- * Copyright (C) 2012 Mikael Berthe +-- + +require "libs.shcmd" + +local json = require 'json' + +local shortenurl = { ["desc"] = "URL shortener", + } + +local encodeoptions = { + strings = { + encodeSet = '\\"%z\1-\031', -- do not escape /, google does not understand that + } +} + +local shell_escape = function (str) + if str then + return "'" .. str:gsub("'", "'\\''") .. "'" + else + return "''" + end +end + +local curlcommand = "curl -s https://www.googleapis.com/urlshortener/v1/url -H 'Content-type: application/json' -d %s" + +function shortenurl.cmd (url) + + if ( not url ) or ( not url:match ( '%w' ) ) then + return nil, 'You must specify an URL' + end + + local replystring = '' + + local targeturl = json.encode( { longUrl = url }, encodeoptions ) + local data = shcmd(curlcommand:format(shell_escape(targeturl))) + if data then + local reply = json.decode ( data ) + if ( type ( reply ) == 'table' ) and reply.id then + return ('Full: %s\nShort: %s'):format(url, reply.id) + else + local errmsg + if type ( reply ) == 'table' and ( type ( reply.error ) == 'table' ) then + errmsg = ('Failed to shorten url: %u %s'):format(reply.error.code, + reply.error.message) + else + errmsg = ('Failed to shorten url: Unknown response:\n%s'):format(replystring) + end + return nil, errmsg + end + return nil, "Got no data :-(" + end +end + +mcbot_register_command("shortenurl", shortenurl) + +-- vim: se ts=4 sw=4: -- diff -r 31f967ba9e1f -r 62248d5fbb24 mcbot/mcbot_engine.lua --- a/mcbot/mcbot_engine.lua Sat Nov 17 09:48:49 2012 +0100 +++ b/mcbot/mcbot_engine.lua Sun Nov 25 19:01:31 2012 +0100 @@ -34,6 +34,7 @@ require "cmds.bofh" require "cmds.xmpp" require "cmds.tvcal" +require "cmds.shortenurl" function process (line, botdata, muc, cmdprefix) local n