Section 12.1. Hacks 91100: Introduction


12.1. Hacks 91100: Introduction

Skype has an Application Programming Interface (API) that you can use to both extend Skype's functionality and use its services. For this chapter, you won't need to be a programmer, but you should be willing to roll up your sleeves and do some scripting. You will be using only simple tools readily available on your machine, though you might have to download a component or two from the Web to interface those tools to the Skype API.

This chapter will not discuss the SkypeNET API because, at the time of this writing, it had been announced but was not yet released. If you are curious, the SkypeNET API enables other third-party applications to use Skype's chat (instant messaging) and online presence infrastructure without having to run the Skype client (as opposed to add-ons that use the Skype API, which must have a running Skype client on the same machine to work).

We will be using scripting in three different, though complementary, ways. You can mix the three methods to accomplish what one alone cannot do. First, we will use scripting to control the Skype application, specifically through its native GUI. Second, we will use the Skype API by sending the Skype application simple text-like messages, and receiving text-like messages in return. At the heart of the Skype API is a simple, message-based "send-action-reply" protocol and we'll be using it, albeit at a simple level. Third, we will be using shell (command) scripts to automate things.

I hope the scripts in this chapter are useful as they are, but don't be afraid to hack around with them and experiment on your own. Consider these scripts as starting points for your own scripts, and as a stimulus to your imagination when inventing new scripts.

At the time of this writing, the Skype API was available only for the Windows, Linux, and Mac OS X platforms. Moreover, not all features of the API were available on all platforms and for all language bindings. For that reason, a handful of the scripts contain within them the word experimental, in anticipation that API support is imminent (as of the time of this writing), or that Skype has announced it will support it in the very near future. Skype's API is developing at a rapid pace, but that's no excuse for not using it now, as it already has some great features. Moreover, if you're waiting for the Skype API to reach some kind of stasis, you might have a very long wait! Experimental scripts do run and don't do anything bad, it's just that they may not work exactly as described; all other scripts work fine on the versions of Skype on which they were tested (see the Preface). If a script doesn't work for you, the first thing you should do is determine whether an updated script has been posted to the book's web site, http://www.oreilly.com/catalog/SkypeHacks/index.html. You can download all scripts in this chapter from that web site.

12.1.1. The Skype API

Even though we're going to use the Skype API at a rather high level, there are distinct advantages to having an understandingeven if only at a conceptual levelof its inner workings. What follows is an overview of the Skype API from the scripting perspective.

The Skype API is conceptually divided into two parts: the Skype Phone API and the Skype Access API. The former is intended for hardware devices that connect to Skype, and therefore is beyond the scope of this chapter and will not be discussed further. Our focus will be on the Skype Access API, which allows an external applicationthat we'll refer to as an add-onto extend Skype's functionality and use its services.

The choice of the term add-on, rather than, say, add-in or plug-in is a deliberate one. The latter two terms characteristically mean a code module that runs in the same memory space as the application that they extend. Skype is highly unusual in that add-ons that use the Skype API reside outside the memory space of Skype on Windows, Linux, and AppleScript on Mac OS X, and inside on Mac OS X for Cocoa and Carbon (I clarify this distinction in more detail shortly). Even so, the term add-on seems a better term to use for software that extends Skype's functionality, especially because such software is often associated with hardware that you add on to your computer.

At the core of the Skype API is a simple text-message-based protocol. Messages flow to and fro between an add-on and the Skype application, in a send-action-response fashion. The add-on sends a message requesting that Skype perform some action, and Skype responds to the add-on by sending back a message indicating success or failure (see Figure 12-1).

Figure 12-1. A simple Skype API message exchange on Windows


Though the message exchange protocol is the same on all platforms, the mechanism by which messages are exchanged is different depending on the platform. Here's a brief summary of how messages are exchanged on each platform that supports the Skype API:


Windows

Messages are exchanged between the add-on and Skype by using Windows messages (which are normally messages sent to and from Windows to control their behavior), and which is the underlying method of coordinating activity within the Windows Manager (the program which controls the windows on your screen).


Linux

Messages are exchanged between the add-on and Skype by using a message bus that is independent of the Windows Manager. This message bus is called D-BUS and is a component of the open source freedesktop. org project (http://www.freedesktop.org). D-BUS must be installed independently of Skype; that is, if you want to use the Skype API on Linux, you must install D-BUS yourself. When Skype and an add-on are connected to the same D-BUS, they can freely exchange Skype API protocol messages (see Figure 12-2).


Mac OS X

Messages are exchanged between the add-on and Skype by using the traditional AppleScript interface to implement a "send" command for scripts, and for Cocoa and Carbon add-ons through an embeddable framework. So, Mac OS X actually supports two distinctly different message-passing methods: out-of-process in the case of AppleScript by implementing a classic AppleScript send command for Skype, and in-process for Cocoa and Carbon using asynchronous delegate methods inside the add-on for Skype to pass messages back.

Figure 12-2. A simple Skype API message exchange on Linux


Skype protects itself from unauthorized add-ons by maintaining an Access Control List (ACL) of programs that the user has given explicit permission to use the Skype API. When an unrecognized add-on first tries to access Skype's API, the user is presented with a pop-up dialog that asks for permission to use the Skype API (see Figure 12-3). When you run a new script, you may have to give it permission to use the Skype API.

Figure 12-3. Giving permission to an add-on to use the Skype API


For readers who want to dig a little deeper into the Skype API, Skype has published a document, "Skype API: Description of Skype API and how to use it," which you can find at http://share.skype.com/developer_zone/documentation/documentation/.

At a minimum, a Skype add-on should initialize its interaction with Skype's API by exchanging these messages ( shows a message sent from the add-on to Skype, and shows a message sent from Skype to the add-on):

  NAME NameOfAddon  OK  PROTOCOL 5  PROTOCOL 5 … 

For Linux, during this message exchange, if this is the first time NameOfAddon has asked to use the Skype API, Skype will pop up a dialog asking the user to give permission for the add-on to access the API. OK will be returned and message passing will continue only if the user gives permission.

Here is a list of Skype API messages that will be used in this chapter (this is only a small subset of the commands that are available):


PING

Message requesting that Skype respond if it's present. If Skype is running and receives the message, it will respond with PONG.


AUDIO_IN

SET AUDIO_INSound device name sent to Skype will change the audio input device that Skype uses to the sound device specified. If no sound device is specified, this command will set audio input to the Windows default sound device. If this command is successful, Skype's reply message will be AUDIO_IN Sound device name.


AUDIO_OUT

SET AUDIO_OUT Sound device name sent to Skype will change the audio output device that Skype uses to the sound device specified. If no sound device is specified, this command will set audio output to the Windows default sound device. If this command is successful, Skype's reply message will be AUDIO_OUT Sound device name.


CALL

CALL Skypename1, Skypename2… with up to four Skype names and/or speed-dial codes will initiate calls to the specified Skype users. When more than one user is used with CALL, a conference call is created. If the command is successful, Skype will open, gain focus, and start the call(s). If you are a SkypeOut subscriber, you can use regular telephones in place of the Skype names; for example, you can dial numbers such as +442075551212.


CHAT CREATE

CHAT CREATESkypename1, Skypename2… with up to 50 Skype usernames will create a chat session. If a chat session is created successfully, Skype will respond with CHAT <chat_id> STATUS <value>, where <chat_id> is a unique identifier for the chat session and <value> indicates the type of chat session created (one-on-one chat or multiperson chat).


CHATMESSAGE

Using the <chat_id> value returned by the CHAT CREATE command, you can send messages to the chat session that has been created by sending the command CHATMESSAGE <chat_id> ChatMessage. If this command is successful, Skype will reply with CHATMESSAGE <chat_id> STATUS SENDING.


FOCUS

Sending the command FOCUS to Skype will open it and give it focus.


MESSAGE

MESSAGE Skypeuser Message will send a chat message to the named Skype user. Even though Skype lists this command as "obsolete," it remains a valid command for compatibility purposes. Thank goodness, because its replacement command, CHATMESSAGE, poses a real problem for AppleScript. CHATMESSAGE requires a chat ID, which is returned when the chat session is created, but this cannot be obtained in the case of AppleScript because Skype has provided no means by which to receive messages from Skype!


NAME

NAME SkypeAddonName will notify Skype that an add-on is requesting to use its API. If the user gives permission for the add-on to access the API, NAME SkypeAddonName (or simply OK on Linux) is returned by Skype.


PROTOCOL

PROTOCOLVersionNumber sent by an add-on to Skype enables the add-on to notify Skype of the protocol version it would like to use. Skype replies with PROTOCOL ProtocolNumber, where ProtocolNumber is the lesser of the add-on or Skype's own supported protocol number. For example, if the add-on sends PROTOCOL 3, Skype will respond with PROTOCOL 3, even though it might support PROTOCOL 5. Another add-on that requests, say, PROTOCOL 7 will find that Skype replies with PROTOCOL 5. Skype will not discard messages from newer protocol versions and will try to perform the action requested by such messages, while the add-on should ignore commands it does not understand and that are sent to it by Skype.


RINGER

SET RINGER Sound device name sent to Skype will change the call-ringing device that Skype uses to the sound device specified. If no sound device is specified, this command will set call ringing to the Windows default sound device. If this command is successful, Skype's reply message will be RINGER Sound device name.

The Skype API is most distinctly a work in progress. When you can't get something to work with the Skype API, you should not immediately assume the problem is with you. Indeed, a search of the Skype forums may quickly prove it's a problem with Skype.

For example, the following tip alone might save someone a wasted day, as it cost a day of my time to find the problem and then fix it!

Skype announced support for its API with Linux in version 1.1.0.3. However, if you install the latest version of Skype (1.2.0.11 at the time of this writing) on SuSE using the RPM installation method, you may be shocked to find that the Skype API is missing! The fix is to download the .tar.bz2 version, extract the Skype executable from that, and overwrite the SuSE version in /usr/bin with it.

The next time you have a problem with Skype, instead of stoically soldiering on against all odds, you should invest a littleor perhaps a lotof time researching the problem on the Skype forums. The odds are that it's just as likely to be a problem with Skype as it is a problem with what you are doing.


12.1.2. Windows Scripting

On Windows, we will be using Visual Basic Script, or simply VBScript, which is a subset of Microsoft's popular Visual Basic language. We'll be running VBScript using the Windows Scripting Host (WSH), which is a runtime environment for running Windows scripts.

WSH comes with Windows XP, but must be downloaded (from http://www.microsoft.com/) and installed separately for Windows 2000.


VBScripts are files with a .vbs extension and that contain VBScript code. This is not the place to teach you how to code in VBScript. For that, O'Reilly has other books that may interest you (for example, VBScript in a Nutshell [2003]), but it is important for you to know how to run VBScripts. You can run VBScripts without command-line arguments by double-clicking on their filenames in Windows Explorer, from the run line (select Start Run…), by entering their filenames (with or without the

Running VBScripts from the command line in a command prompt window can sometimes produce inconsistent results. It seems that sometimesthe command window grabs focus away from Skype before all the keystrokes have been sent to Skype. For this reason, I recommend that you run VBScripts that drive Skype's GUI (specifically, scripts that use the SendKeys command) either using the run line, or as the target of a shortcut. Also, be aware that the maximum length for a run-line command or shortcut target is 259 characters.


Some Windows scripts will use a neat COM component called ActiveS, which is available free of charge from KhaosLabs and which you can download from http://www.khaoslabs.com/actives.php. It is available in both source code and binary form under a BSD-style license.

Even though teaching you how to program in VBScript is not the purpose of this book, a few tips and tricks on hacking and making the scripts work is definitely within the book's scope. Here are a few ideas to try if you're having difficulty making a script (yours or mine) work as you want it to:


Scripting Skype's GUI

To see what your script is really doing, all you need to do is slow it down. You can do this by inserting pauses between commands, using the statement WScript.Sleep 1000, which pauses the script at that point for 1,000 milliseconds (1 second). Liberally sprinkling these throughout your script and then running it will make it look like a movie run in slow motion! And that might be enough for you to see where your script is going wrong.


Non-GUI scripting

If your script is not driving Skype's GUI, you can't actually see what's happening directly. However, by inserting commands to pop up information from time to time, you can peek at your script's inner workings. You can do this by inserting pop-up commands at important points in your code, as shown in the following script, popup.vbs:

 ' File: popup.vbs Dim objShell, num Set objShell = WScript.CreateObject("WScript.Shell") num = 1 objShell.Popup "num = " & CStr(num) num = num + 1 objShell.Popup "num + 1 = " & CStr(num) 


Scripting the Skype API with ActiveS

A good starting point for any script that uses the ActiveS component (which must be installed separately) is to use the ping_pong.vbs script as a template. First, run ping_pong.vbs and make sure it works on your machine, then gradually add commandsperiodically running the script to make sure it's still workinguntil your script is done. An interesting feature of this script is the use of the event handler, SkypeAPI_Result, which you can modify to monitor any message returned by Skype, not just PONG. One important thing to bear in mind about a script like this one is that it won't stop until it gets the appropriate response message from Skypein this case, PONG.

 ' File: ping_pong.vbs Dim objShell, objSkypeAPI Set objShell = WScript.CreateObject("WScript.Shell") Set objSkypeAPI = WScript.CreateObject("SkypeAPI.Access") objSkypeAPI.ConnectAndWait 15000 objShell.Popup objSkypeAPI.SendBlockingCommand("PING") 

Unfortunately, VBScript is no longer included in ROM with Pocket PC 2003 or Windows Mobile 2003, so you won't be able to take advantage of scripting Skype on your handheld device. Scripting for Pocket PC will not be explored in this chapter.

12.1.3. Linux Scripting

On Linux, Skype has been developed using the Qt application framework from Trolltech, http://www.trolltech.com/. Qt has a scripting interface called Qt Script for Applications (QSA), but sadly, Skype does not support it. Nor does Skype support the standard technique for application scripting for the KDE desktopnamely, Desktop COmmunication Protocol (DCOP).

This sorry state of affairs leaves us with scripting the Skype API as the only option. For this, we will be using the Python scripting language, which is commonly available on the Linux platform. There is not enough space in this book to teach you Python; indeed, not enough space to give you even a quick tutorial. To learn more about programming with Python, I suggest that you read Learning Python, Second Edition (O'Reilly, 2003).

However, I would be remiss if I didn't offer you some help in scripting Skype with Python. So, here are a few tips and tricks you might find useful:


Slow script execution

When your script is doing a lot of things very quickly, it's difficult for you to see or understand what's going on. For that reason, it helps to slow things down by putting pauses between executable statements, as in this script, pause.py:

 #!/usr/bin/env python # -*- coding: iso-8859-15 -* # File: pause.py import time def main():     print "You should see this line first…"     time.sleep(3)     print "…and this line about 3 seconds later!"     return 0 if __name__ == "__main__":     main() 


Output in a pop-up window

To see what's going on inside your script, it's sometimes useful to output stuff to the screen. This script, popup.py, shows you how to output data to the command terminal with print and to a pop-up window using SimpleDialog( ) from the Tk toolkit, which you must also have installed on your machine:

 #!/usr/bin/env python # -*- coding: iso-8859-15 -* # File: popup.py from Tkinter import * from SimpleDialog import SimpleDialog def main():      print "Here's some output to the command terminal …"     root = Tk() # Initialize windowing toolkit      SimpleDialog(root,              "…and here's some output in a popup window!",              buttons=["OK"], default=0, title="Popup Window").go()      return 0 if __name__ == "__main__":     main() 


Scripting the Skype API using Python

Here is a very simple script, ping_pong.py, which you can use as a starting point for your own scripts that use the Skype API:

 #!/usr/bin/env python # -*- coding: iso-8859-15 -* # File: ping_pong.py import dbus, sys class addon:      # Name of Skype API addon (that is, name of this script addon)      def name(self):         return 'NAME PingPong'     # Skype API protocol required by this addon     def protocol(self):         return 'PROTOCOL 1' class skype_api:     def __init__(self):         remote_bus = dbus.SystemBus()          system_service_list = remote_bus.get_service( \          'org.freedesktop.DBus').get_object('/org/freedesktop/DBus', \         'org.freedesktop.DBus').ListServices()         skype_api_found = 0         for service in system_service_list:             if service=='com.Skype.API':                 skype_api_found = 1                 break         if not skype_api_found:              sys.exit('No API-capable instance of Skype was found')         skype_service = remote_bus.get_service('com.Skype.API')          self.skype_api_object = skype_service.get_object( \          '/com/Skype', 'com.Skype.API')         this_addon = addon()         answer = self.send_message(this_addon.name())         if answer != 'OK':          sys.exit('Could not bind to Skype client')         answer = self.send_message(this_addon.protocol())         if answer != this_addon.protocol():             sys.exit(this_addon.protocol() + ' is not supported' + \                   ' by the version of Skype you are running')     def send_message(self, message):         answer = self.skype_api_object.Invoke(message)         print 'MESSAGE SENT TO SKYPE --> ' + message         print 'MESSAGE RETURNED BY SKYPE <-- ' + answer         return answer def main():     skypeapi = skype_api()      skypeapi.send_message('PING')     return 0 if __name__ == "__main__":     main() 

You can run Python scripts from the command line, like this: python script. py arg1, where arg1 and any following arguments are optional, depending on the needs of the script.

12.1.4. Mac OS X Scripting

The de facto scripting environment for the Mac is AppleScript. This wonderful, English-like scripting language has been around since 1993, and it is tightly integrated with the Mac operating system. We will be using AppleScript to control Skype through its GUI and its API.

To have AppleScript drive Skype's GUI, you must enable one of Mac OS X's universal access options. To do so, select System Preferences Universal Access, and then check the "Enable access for assistive devices checkbox.


To learn more about programming with AppleScript, I thoroughly recommend the book that I use, AppleScript: The Missing Manual (O'Reilly, 2005). In the meantime, these tips and tricks should help to send you on your way to scripting Skype using AppleScript:


Scripting Skype's GUI

AppleScript is a very powerful tool for scripting Skype through its GUI. Even though Skype can hardly claim to be AppleScript aware or even friendly (it has a miniscule dictionary of commands), by using AppleScript you can readily accomplish in a script anything you might do manually through Skype's GUI. To use AppleScript to drive the Skype GUI, you will first have to enable scripting of Apple's GUI (select System Preferences Universal Access, and then check the "Enable access for assistive devices checkbox). Also, if you're having problems with a script, it helps to slow it downmake it run in slow motionby inserting pauses between commands using delay; for example, delay 0.5 will pause script execution for half a second. It also helps to see what's going on inside a running script by displaying data and information at various points throughout the script, which you can do using the display dialog command; for example, display dialog "Point XYZ in the script has been reached" will pop up a window and display the message text.


Scripting the Skype API with AppleScript

Skype has support for only one AppleScript command: sendthat's it! This unfortunately means that you can only send commands to Skype, and that you won't receive any responses back from Skype. Like many modern-day weapons, this fire-and-forget mode of operation is fine if the intended target is hit squarely; but it's no good if you miss. Not getting anything back from Skype in response to an issued command can make scripts harder to debug. Presumably, Skype will extend its AppleScript interface to its API sometime soon to remedy the situation. In the meantime, this basic script, echo123.scpt, may prove useful as the starting point for your own scripting efforts to automate Skype, through both its API and its GUI:

 -- File: echo123.scpt -- Skype API scripting tell application "Skype"      -- Send Skype API command to chat with echo123 and have the      -- echo123 service call you back      send command "MESSAGE echo123 callme" script name "echo123"      delay 3      -- Send Skype API command to bring Skype to the foreground and      -- give it focus send command "FOCUS" script name "focus" end tell -- Skype GUI scripting tell application "System Events"     tell process "Skype"         -- Pickup the call by clicking the "Answer" button in the          -- "Quick Answer" window         click button 1 of group 1 of group 1 of window "Quick Answer"         delay 5          -- Hangup the call by clicking "Hang Up" in the "Call" menu         click menu item "Hang Up" of menu 1 of menu bar item 

"Call" of menu bar 1 end tell end tell




Skype Hacks
Skype Hacks: Tips & Tools for Cheap, Fun, Innovative Phone Service
ISBN: 0596101899
EAN: 2147483647
Year: 2005
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net