Week #3 Challenge: Twitter API

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

69 Replies - 31263 Views - Last Post: 24 September 2010 - 01:50 AM

#1 Core   User is offline

  • using System.Linq;
  • member icon

Reputation: 784
  • View blog
  • Posts: 5,101
  • Joined: 08-December 08

Week #3 Challenge: Twitter API

Post icon  Posted 17 January 2010 - 03:03 PM

TWITTER API APPLIED

Posted Image

CHALLENGE: Try working with the Twitter API to build an application that simplifies a specific task of your own.

INTRODUCE THE LANGUAGE/TECHNOLOGY: Twitter grows as a service exponentially, so does the number of applications that are using Twitter to achieve various goals. Countless Twitter clients, web applications that post tweets from blogs and whatnot. I've been working extensively with the Twitter API for a few months and I can say that it is not that hard as it seems, if you dive into it. I've released two projects of mine, that are using the Twitter API as their foundation (dotTweet - a Twitter API wrapper for .NET and PerformanceTweet - an application that sends computer performance reports via Twitter).

IDEAS:
  • An application that reads a specific RSS feed and posts links to articles found there on Twitter
  • An application that informs others about the weather in your city
  • An application that automatically retweets posts with a specific hashtag
  • An application that searches for tweets containing a specific phrase
RESOURCES:
There are more resources for Twitter API developers than you think. Even here on DIC, we do have some interesting code snippets and tutorials. When you start, it is a good idea to look at the official Twitter API documentation. In this way, you will get yourself familiar with what the Twitter API can do and how it is implemented.

There are some tips for those who want to use the Twitter API as well.

If you are a C# (or .NET) developer, you might want to take a look at these code snippets:
Post an update to a Twitter account
Get Twitter user image URL
Twitter API: Create friendship
Twitter API: Destroy direct message
Twitter API: Destroy status
Twitter API: Get global updates
Twitter API: Get mentions
Twitter API: Get rate limit status
Twitter API: Get recent public timeline
Twitter API: Get trending topics
Twitter API: Get user mentions
Twitter API: Send direct message
Twitter API: Update profile image
Twitter API: Update profile info

For Ruby developers, take a look at this code snippet that retrieves the list of public statuses.

For Java developers, take a look at Twitter4J - a library that allows you to access the Twitter API without any additionals dependencies (JARs). Or, there is JTwitter.

If you are thinking about building an automated Twitter bot, then take a look at this article.

For Haskell guys, there is hs-twitter. And of course, for Clojure users there is clojure-twitter (thanks to Raynes for providing the link).

For those developers who use Python, there is python-twitter. And there is Python Twitter Tools.

Twitter API calls can also be implemented in Perl thanks to Net::Twitter (link provided by dsherohman).

Now, if you feel like you need a tutorial, here is one for the PHP guys:
Building an Automated Twitter Bot with Twitters API functionality

If you are interested in using Twitter with OAuth in PHP, definitely check out this topic.

If you don't feel like writing every single Twitter API call from scratch (not me), take a look at TweetSharp, which is another good Twitter API wrapper for .NET developers. Sometimes it is also good to check out the Twitter Development Talk group as the primary source of Twitter API updates and implementation samples.

HOW TO GET STARTED:
Basically all you need to get started you already have. An IDE (or text editor) for your language of choice is going to be enough. You will need some knowledge about what XML, ATOM and JSON are. Although you don't need to be an expert in these, it will speed up your work a bit if you will know the fundamentals. You will also need some experience working with HTTP requests. The rest of the Twitter API is mainly about correctly building these request and processing the responses accordingly.

To show you how easy it is to implement some Twitter API calls, take a look at these C# code samples.

Here is how to verify whether the friendship beetween two users exists (User A is following User B ):
		/// <param name="username">Twitter account username.</param>
		/// <param name="password">Twitter account password.</param>
		/// <param name="userA">The main user.</param>
		/// <param name="userB">The user to check for friendship.</param>
		public static bool Friendship_Exists(string username, string password, string userA, string userB)
		{
			try
			{
				XmlUrlResolver xmlResolver = new XmlUrlResolver();
				xmlResolver.Credentials = new NetworkCredential(username, password);

				XmlReaderSettings xmlSettings = new XmlReaderSettings();
				xmlSettings.XmlResolver = xmlResolver;

				XmlReader feedReader = XmlReader.Create("http://twitter.com/friendships/exists.xml?user_a=" + userA + "&user_b=" + userB, xmlSettings);
				XmlDocument xmlDocument = new XmlDocument();
				xmldocument.Load(feedReader);

				string friends = xmldocument.SelectSingleNode("/friends").InnerText;
				bool rValue = Convert.ToBoolean(friends);
				return rValue;
			}
			catch
			{
				return null;
			}
		}



It simply gets the credentials the user inserts and retrieves the boolean value from the generated XML file. As you see, there are no complicated processes involved.

Now, here is another sample. Let's suppose that you wrote a Twitter status update you don't like. What about deleting it? This is deon in C# this way:

		/// <summary>
		/// Destroys the status specified by the required ID parameter. 
		/// The authenticating user must be the author of the specified status.
		/// http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses%C2%A0destroy
		/// </summary>
		/// <param name="username">Twitter account username.</param>
		/// <param name="password">Twitter account password.</param>
		/// <param name="id">Twitter status ID.</param>
		public static string Statuses_Destroy(string username, string password, string id)
		{
			try
			{
				WebRequest request = HttpWebRequest.Create("http://twitter.com/statuses/destroy/" + id + ".xml");
				request.Method = "DELETE";
				request.ContentLength = 0;
				request.Credentials = new NetworkCredential(username, password);

				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
				StreamReader responseStream = new StreamReader(response.GetResponseStream());

				string responseString = responseStream.ReadToEnd();

				return responseString;
			}
			catch (Exception ex)
			{
				return ex.Message;
			}
		}



Once you specify the status ID and the credentials, it will be removed.

Is This A Good Question/Topic? 0
  • +

Replies To: Week #3 Challenge: Twitter API

#2 skyhawk133   User is offline

  • Head DIC Head
  • member icon

Reputation: 1963
  • View blog
  • Posts: 20,421
  • Joined: 17-March 01

Re: Week #3 Challenge: Twitter API

Posted 17 January 2010 - 03:30 PM

This should be a great cross-platform, cross-language challenge for those of you who haven't felt like attempting the first 2 weeks! I look forward to lots of neat little Twitter widgets, apps, etc. this week!


As you test your Twitter API apps, tag your tweets with #52WoC

I'm sure someone will create a quick little app to follow the #52WoC hash tag.
Was This Post Helpful? 0
  • +
  • -

#3 erik.price   User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Re: Week #3 Challenge: Twitter API

Posted 17 January 2010 - 03:37 PM

Awesome. I actually started developing my own Twitter implementation in Ruby this week. It is nowhere near done, but I finished about 75% of the API calls, and still need to get on parsing the XML, RSS, and JSON responses.

Anyway, my first contribution: updating your status. (ignore the notes to myself in the comments)

def postWithAuth(site, form_data)
	url = URI.parse(site)
	req = Net::HTTP::Post.new(url.path)
	req.basic_auth 'yourUser', 'yourPass'
	req.set_form_data(form_data)
	res = Net::HTTP.new(url.host, url.port).start { |http|
	  http.request(req)
	}
	case res
	when Net::HTTPSuccess, Net::HTTPRedirection
	  #phew!
	else
	  res.error!
	end
  end
def updateStatus(status, in_reply_to = nil) #need to implement geo params!
	base = "http://twitter.com/statuses/update.xml"
	status = status[0...140] #truncate to 140 chars

	form_data = Hash.new
	form_data['status'] = status
	form_data['in_reply_to_id'] = in_reply_to if in_reply_to #change this to let them use username instead of ID
	postWithAuth(base, form_data)

  end



I also created a hideous Swing GUI (with JRuby) to do this. (it'll need some modification, as I put all of the methods in a class called Twitter)

edit: forgot to mention. this snippet expects proper a username and password, and will throw an exception (but not handle it) if authentication fails
fixed

include Java
require 'Twitter'

JFrame = javax.swing.JFrame
JLabel = javax.swing.JLabel
JPanel = javax.swing.JPanel
JButton = javax.swing.JButton
BorderLayout = java.awt.BorderLayout
Event = java.awt.event
JTextField = javax.swing.JTextField
JTextArea = javax.swing.JTextArea
JOptionPane = javax.swing.JOptionPane

class GUI < JFrame
  include Event.ActionListener
  def initialize(*args)
	
	super
	
	@user = JOptionPane.show_input_dialog("Please enter your username")
	@pass = JOptionPane.show_input_dialog("Please enter your password")
	
	@twit = Twitter.new(@user, @pass) #you'd need to modify this line and a few others, or create a Twitter class
	@root = JPanel.new
	@panel = JPanel.new BorderLayout.new
	@field = JTextField.new('What\'s on your mind?', 90)
	@button = JButton.new("Tweet it!")	
	

	@button.add_action_listener self
	
	@panel.add @field, BorderLayout::WEST
	@root.add @button
	
	@root.add @panel
	
	self.add @root

	self.set_size 1000, 90
	self.setResizable false
	self.set_visible true
	self.setDefaultCloseOperation JFrame::EXIT_ON_CLOSE
	
  end
  
  def actionPerformed event
	source = event.get_source
	if source == @button
	  tweet = @field.get_text
	  unless tweet[140] == nil
		res = JOptionPane.showConfirmDialog(nil,
		  "You have exceeded the maximum value for a tweet.\n"\
		  "Would you like to truncate your message to 140 characters?",
		  "Tweet Length exceeded!",
		  JOptionPane::YES_NO_CANCEL_OPTION)
		  puts res
		  if res == 0
			tweet = tweet[0...140]
		  elsif res == 1
			tweet = tweet
		  else
			return;
		  end
		  @field.set_text tweet
	  end
			begin
		@twit.updateStatus(tweet)
	  rescue
		JOptionPane.showMessageDialog(nil,"Authentication Failed! Please re-enter your\nUsername and password")
		@user = JOptionPane.show_input_dialog("Please enter your username")
		@pass = JOptionPane.show_input_dialog("Please enter your password")
		return
	  end
	  JOptionPane.show_message_dialog nil, "Updated!"
	  @field.set_text ""
	  
	end
  end
end



I know it's crap. It was my first JRuby attempt

This post has been edited by erik.price: 17 January 2010 - 04:26 PM

Was This Post Helpful? 0
  • +
  • -

#4 SixOfEleven   User is offline

  • Planeswalker
  • member icon

Reputation: 1055
  • View blog
  • Posts: 6,643
  • Joined: 18-October 08

Re: Week #3 Challenge: Twitter API

Posted 17 January 2010 - 04:43 PM

I'm sure that I'm going to try out this challenge. I might actually use my Twitter account for a change. :)
Was This Post Helpful? 0
  • +
  • -

#5 Raynes   User is offline

  • D.I.C Lover
  • member icon

Reputation: 614
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

Re: Week #3 Challenge: Twitter API

Posted 17 January 2010 - 07:44 PM

I'll write something up in Clojure soon.

@Core, for Clojure users, you can add that I have a clojure-twitter jar on clojars.org (I didn't write it, I just put it there ;)), that maven/leiningen users can pull down. It's what I'll be using for my app.

EDIT: I'll also point out that hs-twitter doesn't support OAuth (and I'm not sure if it ever will), which is why I'm not doing this in Haskell. Plus, I need to freshen up my Clojure anyways.

EDIT2: Did I mention that OAuth is a bitch to implement?

This post has been edited by Raynes: 17 January 2010 - 07:46 PM

Was This Post Helpful? 0
  • +
  • -

#6 erik.price   User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Re: Week #3 Challenge: Twitter API

Posted 17 January 2010 - 07:49 PM

View PostRaynes, on 17 Jan, 2010 - 09:44 PM, said:

EDIT2: Did I mention that OAuth is a bitch to implement?


Agreed. I was planning on trying to write up an implementation for it eventually, but Basic Auth works fine for now.
Was This Post Helpful? 0
  • +
  • -

#7 eclipsed4utoo   User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1535
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Re: Week #3 Challenge: Twitter API

Posted 17 January 2010 - 07:57 PM

View Posterik.price, on 17 Jan, 2010 - 10:49 PM, said:

View PostRaynes, on 17 Jan, 2010 - 09:44 PM, said:

EDIT2: Did I mention that OAuth is a bitch to implement?


Agreed. I was planning on trying to write up an implementation for it eventually, but Basic Auth works fine for now.


I might do a write-up on it. I've successfully implemented it in .Net.

Only problem is, it's A LOT of code. Not sure how to go about posting it.

This post has been edited by eclipsed4utoo: 17 January 2010 - 07:59 PM

Was This Post Helpful? 0
  • +
  • -

#8 Raynes   User is offline

  • D.I.C Lover
  • member icon

Reputation: 614
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

Re: Week #3 Challenge: Twitter API

Posted 17 January 2010 - 08:02 PM

View Posteclipsed4utoo, on 17 Jan, 2010 - 06:57 PM, said:

View Posterik.price, on 17 Jan, 2010 - 10:49 PM, said:

View PostRaynes, on 17 Jan, 2010 - 09:44 PM, said:

EDIT2: Did I mention that OAuth is a bitch to implement?


Agreed. I was planning on trying to write up an implementation for it eventually, but Basic Auth works fine for now.


I might do a write-up on it. I've successfully implemented it in .Net.

Only problem is, it's A LOT of code. Not sure how to go about posting it.


I imagine I could implement it, but since somebody has done it for me in Clojure, I don't have to bother. :D
Was This Post Helpful? 0
  • +
  • -

#9 erik.price   User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Re: Week #3 Challenge: Twitter API

Posted 17 January 2010 - 11:05 PM

Where's the fun in that? :P
Was This Post Helpful? 0
  • +
  • -

#10 dsherohman   User is offline

  • Perl Parson
  • member icon

Reputation: 227
  • View blog
  • Posts: 654
  • Joined: 29-March 09

Re: Week #3 Challenge: Twitter API

Posted 18 January 2010 - 04:38 AM

Two things:

1) Please add Perl's Net::Twitter to the resource list.

2) Is it cheating to use code that we've previously written and have in live production use? :D
Was This Post Helpful? 0
  • +
  • -

#11 eclipsed4utoo   User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1535
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Re: Week #3 Challenge: Twitter API

Posted 18 January 2010 - 06:46 AM

View PostRaynes, on 17 Jan, 2010 - 11:02 PM, said:

View Posteclipsed4utoo, on 17 Jan, 2010 - 06:57 PM, said:

View Posterik.price, on 17 Jan, 2010 - 10:49 PM, said:

View PostRaynes, on 17 Jan, 2010 - 09:44 PM, said:

EDIT2: Did I mention that OAuth is a bitch to implement?


Agreed. I was planning on trying to write up an implementation for it eventually, but Basic Auth works fine for now.


I might do a write-up on it. I've successfully implemented it in .Net.

Only problem is, it's A LOT of code. Not sure how to go about posting it.


I imagine I could implement it, but since somebody has done it for me in Clojure, I don't have to bother. :D


Only one person had done OAuth in .Net(Shannon Whitley). I used his library, but ended up changing about 70% of the code because it didn't support the Desktop PIN workflow.
Was This Post Helpful? 0
  • +
  • -

#12 Raynes   User is offline

  • D.I.C Lover
  • member icon

Reputation: 614
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

Re: Week #3 Challenge: Twitter API

Posted 18 January 2010 - 09:03 AM

I do believe I'm going to write an application that parses http://www.reddit.com/r/lisp/.rss and tweets new posts to Twitter.

I might do that later, or tomorrow, depending on whether or not I get this chapter done in my book in time or not.
Was This Post Helpful? 0
  • +
  • -

#13 Core   User is offline

  • using System.Linq;
  • member icon

Reputation: 784
  • View blog
  • Posts: 5,101
  • Joined: 08-December 08

Re: Week #3 Challenge: Twitter API

Posted 18 January 2010 - 03:42 PM

Quote

2) Is it cheating to use code that we've previously written and have in live production use?


It is not, if the code will not cause copyright issues. Even better - code that was tested in production environments in most of the cases is very reliable and can be re-used.

@erik.price Well good job on posting what you got!
Was This Post Helpful? 0
  • +
  • -

#14 SixOfEleven   User is offline

  • Planeswalker
  • member icon

Reputation: 1055
  • View blog
  • Posts: 6,643
  • Joined: 18-October 08

Re: Week #3 Challenge: Twitter API

Posted 18 January 2010 - 04:01 PM

Well, I tried it out. I made a little Windows application with C# that I can use to make tweets. Special thanks to gabehabe for his snippet here on DIC. :) I think I will try and add in a few more feature if I can find the time.

Attached Image

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace TwitterApplication
{
    public partial class Form1 : Form
    {
        string statusUpdateURL = "http://twitter.com/statuses/update.xml";
        string statusMethod = "POST";

        public Form1()
        {
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUsername.Text))
            {
                MessageBox.Show("You must enter a user name.");
                return;
            }
            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                MessageBox.Show("You must enter a password.");
                return;
            }
            if (string.IsNullOrEmpty(txtStatus.Text))
            {
                MessageBox.Show("You must enter you status.");
                return;
            }
            UpdateStatus();
        }

        // Thanks to: Danny Battison
        private void UpdateStatus()
        {
            try
            {
                byte[] user = Encoding.UTF8.GetBytes(txtUsername.Text + ":" + txtPassword.Text);
                string userstring = Convert.ToBase64String(user);

                byte[] tweet = Encoding.ASCII.GetBytes("status=" + txtStatus.Text);

                HttpWebRequest twitterRequest = (HttpWebRequest)WebRequest.Create(statusUpdateURL);
                twitterRequest.Method = statusMethod;

                twitterRequest.ServicePoint.Expect100Continue = false;
                twitterRequest.Headers.Add("Authorization", "Basic " + userstring);
                twitterRequest.ContentType = "application/x-www-form-urlencoded";

                twitterRequest.ContentLength = tweet.Length;

                Stream requestStream = twitterRequest.GetRequestStream();
                requestStream.Write(tweet, 0, tweet.Length);
                requestStream.Close();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
            MessageBox.Show("Your Tweet was made successfully.");
        }
    }
}


Was This Post Helpful? 0
  • +
  • -

#15 Sethro117   User is offline

  • Still the sexiest mofo.
  • member icon

Reputation: 237
  • View blog
  • Posts: 2,378
  • Joined: 14-January 09

Re: Week #3 Challenge: Twitter API

Posted 18 January 2010 - 05:40 PM

I signed up for Twitter just for this. :) Im working on an app that tweets the weather conditions and forecast in the specified postal code. Should have it up later tonight.

Edit: Done, below are the images and source. I had started this project awhile back with Yahoo Weather. This weeks challenge gave me a reason to finish it. Thanks to gabehabe for his Twitter Post Snippet.

Main Form:
Attached Image

Main Form Code:
Imports System.Xml
Public Class Form1
	Dim doc As XmlDocument
	Dim ns As XmlNamespaceManager
	Dim nodes As XmlNodeList
	Dim code As String
	Private Sub btngo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
		Timer1.Enabled = True
		GetRegion(txtzip.Text)
		GetWeather(txtzip.Text)
		GetForecast(txtzip.Text)
	End Sub

	Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
		GetWeather(txtzip.Text)
		GetForecast(txtzip.Text)
	End Sub

#Region "Form Move"
	'Declare the variables
	Dim drag As Boolean
	Dim mousex As Integer
	Dim mousey As Integer

	Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
		drag = True
		mousex = Windows.Forms.Cursor.Position.X - Me.Left
		mousey = Windows.Forms.Cursor.Position.Y - Me.Top
	End Sub
	Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
		If drag = True Then
			Me.Top = Windows.Forms.Cursor.Position.Y - mousey
			Me.Left = Windows.Forms.Cursor.Position.X - mousex
		End If
	End Sub
	Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp
		drag = False
	End Sub
#End Region

	Private Sub txtzip_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtzip.KeyUp
		If e.KeyCode = Keys.Enter Then
			Call btngo_Click(sender, e)
		End If
	End Sub

	Private Sub btnSettings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSettings.Click
		Form2.Show()
	End Sub

	Private Sub picClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles picClose.Click
		Me.Close()
	End Sub
End Class



Settings Form:
Attached Image

Settings Form Code:
Public Class Form2
	Private Sub picClose_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles picClose.MouseClick
		Me.Close()
	End Sub

	Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
		My.Settings.Username = txtUsername.Text
		My.Settings.Password = txtPassword.Text
		My.Settings.ZipCode = txtZip.Text
		My.Settings.Save()
		GetRegion(txtZip.Text)
		GetWeather(txtZip.Text)
		GetForecast(txtZip.Text)
		PostTweet(txtUsername.Text, txtPassword.Text, "CURRENT CONDITIONS in " & Form1.Label2.Text & " " & Form1.lblcc.Text & ". FORECAST-" & Form1.lblforecast.Text)
	End Sub

	Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
		txtUsername.Text = My.Settings.Username
		txtPassword.Text = My.Settings.Password
		txtZip.Text = My.Settings.ZipCode
	End Sub
End Class


Finally Module1, which holds the GetWeather, GetForecast, GetRegion and the PostTweet:
Imports System.Xml
Imports System.IO
Imports System.Net
Imports System.Web
Module Weather
	Dim doc As XmlDocument
	Dim ns As XmlNamespaceManager
	Dim nodes As XmlNodeList
	Dim code As String
	Sub GetRegion(ByVal ZipCode As String)
		' Create a new XmlDocument  
		doc = New XmlDocument()
		' Load data  
		doc.Load("http://xml.weather.yahoo.com/forecastrss?p=" & ZipCode)
		' Set up namespace manager for XPath  
		ns = New XmlNamespaceManager(doc.NameTable)
		ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0")
		' Get forecast with XPath  
		nodes = doc.SelectNodes("/rss/channel/yweather:location", ns)
		For Each node As XmlNode In nodes
			Form1.Label2.Text = node.Attributes("city").InnerText & ", " _
			& node.Attributes("region").InnerText & " " & ZipCode + " - " _
			+ node.Attributes("country").InnerText
		Next
	End Sub
	Sub GetWeather(ByVal ZipCode As String)
		' Create a new XmlDocument  
		doc = New XmlDocument()
		' Load data  
		doc.Load("http://xml.weather.yahoo.com/forecastrss?p=" & ZipCode)
		' Set up namespace manager for XPath  
		ns = New XmlNamespaceManager(doc.NameTable)
		ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0")
		' Get forecast with XPath  
		nodes = doc.SelectNodes("/rss/channel/item/yweather:condition", ns)
		For Each node As XmlNode In nodes
			code = node.Attributes("code").InnerText
			Form1.lblcc.Text = node.Attributes("text").InnerText & ", " & node.Attributes("temp").InnerText & "F"
			Form1.PictureBox1.ImageLocation = "http://l.yimg.com/a/i/us/we/52/" & code & ".gif"
		Next
	End Sub
	Sub GetForecast(ByVal ZipCode As String)
		' Create a new XmlDocument  
		doc = New XmlDocument()
		' Load data  
		doc.Load("http://xml.weather.yahoo.com/forecastrss?p=" & ZipCode)
		' Set up namespace manager for XPath  
		ns = New XmlNamespaceManager(doc.NameTable)
		ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0")
		' Get forecast with XPath  
		nodes = doc.SelectNodes("/rss/channel/item/yweather:forecast", ns)
		For Each node As XmlNode In nodes
			Form1.lblforecast.Text = node.Attributes("day").InnerText + ": " _
			+ node.Attributes("text").InnerText + ", " + node.Attributes("low").InnerText + "F - " _
			+ node.Attributes("high").InnerText + "F"
		Next
	End Sub

	Public Sub PostTweet(ByVal username As String, ByVal password As String, ByVal tweet As String)
		If tweet.Length > 140 Then
			MsgBox("Tweet is over 140 Characters.", MsgBoxStyle.Exclamation, "Characters Exceeded")
		ElseIf tweet.Length <= 140 Then
			Try
				' encode the username/password
				Dim user As String = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes((username & ":") + password))
				' determine what we want to upload as a status
				Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes("status=" & tweet)
				' connect with the update page
				Dim request As HttpWebRequest = DirectCast(WebRequest.Create("http://twitter.com/statuses/update.xml"), HttpWebRequest)
				' set the method to POST
				request.Method = "POST"
				request.ServicePoint.Expect100Continue = False
				' thanks to argodev for this recent change!
				' set the authorisation levels
				request.Headers.Add("Authorization", "Basic " & user)
				request.ContentType = "application/x-www-form-urlencoded"
				' set the length of the content
				request.ContentLength = bytes.Length
				' set up the stream
				Dim reqStream As Stream = request.GetRequestStream()
				' write to the stream
				reqStream.Write(bytes, 0, bytes.Length)
				' close the stream
				reqStream.Close()
			Catch ex As Exception

			End Try
		End If
	End Sub
End Module



I also added to show the user, if their tweet would be over the 140 character limit.

This post has been edited by Sethro117: 18 January 2010 - 07:35 PM

Was This Post Helpful? 2

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »