Bulk Deleting Twitter Direct Messages

The number of direct messages I had in Twitter was starting to mount up. “I’ll have to delete those” I thought to myself. I looked around their web site but failed to find away of bulk deleting direct messages. They do, however, have an API, so I wrote the script below to do a bulk delete of DMs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using System.Xml.Linq;
using System.Xml;

namespace DeleteTwitterDMs {
    class Program {
        private static void Main() {

            //GS - Create the credentials to connect 
            //to Twitter
            NetworkCredential networkCredential = 
                new NetworkCredential(yourUserId, 
                    yourPassword);
            
            //GS - Decalare a variable to hold the 
            //xml document
            XDocument document;

            //GS - Fetch up to the first 20 direct 
            //messages
            using (WebClient client = 
                new WebClient()) {
                client.Credentials = 
                    networkCredential;
                string url = 
                    "http://twitter.com/" +
                    "direct_messages.xml";

                try {
                    using (Stream stream = 
                        client.OpenRead(url)) {
                        XmlReader reader = 
                            XmlReader.Create(stream);
                        document = 
                            XDocument.Load(reader);
                    }
                }
                catch (WebException ex) {
                    //GS - Get the response stream
                    Stream stream = ex.Response.
                        GetResponseStream();

                    //GS - Read it all
                    StreamReader reader = 
                        new StreamReader(stream);
                    string reply = 
                        reader.ReadToEnd();

                    //GS - Tell the user what's 
                    //going on
                    Console.WriteLine(
                        String.Format(
                            "Failed to retrieve " +
                            "list of direct " +
                            "messages. The server" + 
                            " returned " +
                            "the following error:" +
                            " {0}. " +
                            "The server also " +
                            "replied with: {1}",
                            ex.Message,
                            reply));
                    return;
                }
            }

            //GS - Extract the DM ids
            IEnumerable<XElement> Ids =
                from el in document
                    .Root
                    .Elements("direct_message")
                    .Elements("id")
                select el;

            //GS - for each id delete the DM
            foreach (XElement id in Ids) {
                DeleteDirectMessageById(
                    networkCredential, id);
            }

            //GS - Tell the user we're done
            Console.WriteLine(String.Format(
                "Deletion completed, {0} " +
                "messages deleted.",
                    Ids.Count()));
        }

        private static void DeleteDirectMessageById(
            NetworkCredential networkCredential, 
                XElement id) {

            //GS - Get the API URL
            string url = String.Format(
                "http://twitter.com/" +
                "direct_messages/" +
                "destroy/{0}.xml",
                id.Value);

            try {
                //GS - Create the request object
                HttpWebRequest request =
                    WebRequest.Create(url) 
                    as HttpWebRequest;

                //GS - Add the required credentials
                request.Credentials = 
                    networkCredential;

                //GS - Deleting DMs requires a 
                //POST (or DELETE)
                request.Method = "POST";

                //GS - Get the response from 
                //the server
                using (HttpWebResponse response =
                    request.GetResponse() as 
                    HttpWebResponse) {

                    //GS - Handle the response
                    if (response.StatusCode == 
                        HttpStatusCode.OK) {
                        Console.WriteLine(
                            String.Format(
                                "Message id {0} " +
                                "deleted.",
                                    id.Value));
                    }
                    else {
                        Console.WriteLine(
                            String.Format(
                                "Deleting message " +
                                "Id: {0} " +
                                "failed for the " +
                                "following " +
                                "reason: {1}",
                                id.Value,
                                response
                                .StatusDescription)
                        );
                    }
                }
            }
            catch (WebException ex) {
                Console.WriteLine(
                    String.Format(
                        "Error getting response " +
                        "from server: {0}",
                        ex.Message));
            }
        }
    }
}

Limitations

Now the script has some limitations, mostly around the limitations of the Twitter API. Firstly, you can only make 100 requests per hour. Retrieving the list of direct messages is one request and to delete each message is another request, so they can soon mount up.

Also, the Twitter API will only return you the latest 20 messages at a time, so you will have to run the script multiple times if you have more than 20 messages to delete.

Further, I’ve noticed that once you have deleted the messages, Twitter takes a little while to “catch up” and so it will return some deleted messages if you ask for the list of DMs again “too quickly”.

The script can probably do with being refactored a bit and it’s not meant to be production strength, but you can feel free to make use of it if you wish; of course there’s no warranty or anything, but you can mail (or Twitter) me about it if you want.

Digg This
Advertisements
This entry was posted in C#, Community, Developement. Bookmark the permalink.

2 Responses to Bulk Deleting Twitter Direct Messages

  1. Ann says:

    Thanks Gary,
    it is quite a weakness in twitter to be unable to delete older dm messages while keeping 20 more relevant recent ones.
    I had also noticed the irritations you mention, while deleting individual dms.

    Your script is very educational for me – seeing all this fitting together for web work. Better than a boring old tutorial. 🙂

    bcnu,
    Ann

  2. Isaac Ladwig says:

    Awesome blog post, thanks for keeping me busy!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s