Tweet

From IronPython Cookbook

Using Yedda

This example requires:

  • A Twitter login.
  • A copy of the Yedda .NET Twitter Library.
import clr
clr.AddReference("Yedda.Twitter.dll")
clr.AddReference("System.Net")
from Yedda import *
from System.Net import *
ServicePointManager.Expect100Continue = False
Twitter().UpdateAsXML("Username", "Password", "Hello Twitter World!")

With just a couple of changes this can be made into a handy command line tool:

@ipy -x "%~f0" %* & goto :EOF
import sys
import clr
clr.AddReference("Yedda.Twitter.dll")
clr.AddReference("System.Net")
from Yedda import *
from System.Net import *
ServicePointManager.Expect100Continue = False
Twitter().UpdateAsXML("Username", "Password", " ".join(sys.argv[1:]))

The first line makes this a self executable script - see Self-executable_scripts for more info. Lastly change the filename to have a .cmd extension e.g. tweet.cmd . Once this is done you can call it from the command prompt like so:

tweet The IronPython Cookbook is really very handy!

Using the Framework Only

A more self-contained example that uses standard Base Class Library (BCL) and System.Net facilities follows:

# Tweet - Status update tool for twitter.com
# Copyright (c) 2009 Atif Aziz. All rights reserved.
#
# Author(s):
#
#   Atif Aziz, http://www.raboof.com
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the New BSD License, a copy of which should have
# been delivered along with this distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import sys, clr
from System import Environment
from System.Net import WebClient, NetworkCredential, ServicePointManager
from System.Collections.Specialized import NameValueCollection

#
# Usage:
#
# tweet ( "@" USERNAME ) STATUS
#

def main(args):
    arg = args and args[0] or None
    if arg and len(arg) > 1 and arg.startswith('@'):
        username = arg[1:]
        args.pop(0)
    else:
        username = Environment.GetEnvironmentVariable('TWITTER_USERNAME')
    if not username:
        raise Exception('Missing Twitter username.')
    password = Environment.GetEnvironmentVariable('TWITTER_PASSWORD')
    if not password:
        raise Exception('Missing Twitter password.')
    status = args and args.pop(0)
    if not status:
        print "Sorry, but no status, no update. Did you forget something?"
        return
    if len(status) > 140:
        raise Exception("Status is too long (%s). Limit to 140 characters." % len(status).ToString('N0'))
    ServicePointManager.Expect100Continue = False # See http://blogs.msdn.com/shitals/archive/2008/12/27/9254245.aspx
    wc = WebClient(Credentials = NetworkCredential(username, password))
    wc.Headers.Add('X-Twitter-Client', 'Pweeter')
    form = NameValueCollection()
    form.Add('status', status)
    wc.UploadValues('http://twitter.com/statuses/update.xml', form)
    print 'Status updated.'

if __name__ == '__main__':
    try:
        main(sys.argv[1:])
    except Exception, e:
        print >> sys.stderr, e

Usage is as follows:

tweet ( "@" USERNAME ) STATUS

Your Twitter account name and password needs to be set in two environment variables, namely TWITTER_USERNAME and TWITTER_PASSWORD, before running the script. If omit the first argument to the script then you are updating your own status and USERNAME is assumed to be the value of the TWITTER_USERNAME account.

Back to Contents.

TOOLBOX
LANGUAGES