You love twitter? You love Linq too? Then you are gonna adore LinqToTwitter.
LINQ to Twitter is a LINQ Provider for the Twitter micro-blogging service. It uses standard LINQ syntax
for queries and includes method calls for changes via theTwitter API.
LinqToTwitter is one of the most inspiring applications out there made with C# by @JoeMayo. You can download it from here : http://linqtotwitter.codeplex.com/. It is open source and several projects are using it already.
Today I want to show how simple it is to develop your own twitter based application using LinqToTwitter, as for an example we will build a simple retweet / hash bot, like the ones we find on twitter for example hashandroid, hashphp, hashcss and more.
You can use for example such bots to retweet every tweet mentioning your domain name, your own name, your trademark or even your favorite movie. A valuable tool for business too.
Download LinqToTwitter, then start a new Visual Studio solution, we will use C# as the language.
First we need to add a reference to the LinqToTwitter DLL and System.Configuration (Solution Explorer –> References –> Add a Reference).
The code is so simple actually, I will explain as long as we go through the code, you can find the complete source code in the attached file from here.
To be sure our bot won’t retweet tweets that are already processed we will read the ID of the tweet from the configuration file like follows
// Start fetching tweets from the last one we fetched before, to not retweet duplicate tweets
// We do this by searching for tweeting having an ID >= to lastTweetID
saved in the App.config
var lastTweetID = getLastTweetID();
private static string getLastTweetID()
{
return ConfigurationManager.AppSettings["lastTweetID"];
}
Once the last tweet ID retrieved, we fetch all the tweets that have a specified string and are emitted after our lastTweetID:
List<AtomEntry> lstTweets = SearchTwitter(twitterCtx, "martani_net"
, Convert.ToUInt64(lastTweetID));
The function SearchTwitter returns the list of tweets satisfying the criteria,we pass the term to search for and the last tweetID.
private static List<AtomEntry> SearchTwitter(TwitterContext twitterCtx, string searchWrd, ulong lastTweetID)
{
var queryResults =
from search in twitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == searchWrd &&
search.PageSize == 10 &&
search.SinceID == lastTweetID
select search;
foreach (var search in queryResults)
{
return search.Entries.ToList();
}
return null;
}
Now that we have the list of tweets we save the most recent tweet ID so that the next time we fetch only new tweets:
var lastTweet = lstTweets.First();
lastTweetID = lastTweet.ID.Substring(lastTweet.ID.LastIndexOf(':') + 1);
// Save the lastest tweet ID in the App.config file.
saveLastTweetID(lastTweetID);
This is the function that saves the lastTweetID in the app.config file (actually this didn’t work for me!! any help?)
private static void saveLastTweetID(string lastTweetID)
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["lastTweetID"].Value = lastTweetID;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
Everything is ready now, we have just to retweet the new tweets with a little change in their form :
foreach (var entry in lstTweets)
{
//Console.WriteLine(entry.ID);
string via = " (via @" + GetShortName(entry.Author.Name) + ")";
string contentWithoutHTML = DeleteHTML(entry.Content);
string newTweet = contentWithoutHTML.Substring(0,
Math.Min(contentWithoutHTML.Length, 140 - via.Length))
+ via;
// skip tweets that we already retweeted before
if (AlreadyTwittered(contentWithoutHTML))
continue;
twitterCtx.UpdateStatus(newTweet);
//Console.WriteLine(newTweet);
}
Here we are fetching the user name and storing it in the via variable. we use the GetShortName function to get only the user name and not it’s real name. For example entry.Author.Name returns “martani_net (Martani Fakhrou)” so our function returns only “martani_net”
private static string GetShortName(string longName)
{
return longName.Substring(0, longName.IndexOf(' '));
}
Then we get the content of the tweet without any HTML, we use a simple regular expression to delete any html specific tags:
private static string DeleteHTML(string text)
{
Regex reg = new Regex("<[^>]*>");
return reg.Replace(text, "");
}
Then we compose the new tweet which is the content without HTML + the “via (username)” footer. Here we have to be aware that our tweet doesn’t exceed 140 chars which mean the true length of the content can’t exceed 140 – the length of the footer (via @something)
Still one trick to take care of, our retweeted tweets will be fetched also, which means we have to take them away, for this we use the function AlreadyTwittered as follows :
private static bool AlreadyTwittered(string p)
{
// if the tweet ends with ")" and have the string " (via" then
// we might have retweeted it already
// this is a poor cretaria, just for examples here.
if (p.EndsWith(")") && p.IndexOf(" (via") != -1)
return true;
else
return false;
}
Well this is all, we can now send our new tweet to twitter with the following statement
twitterCtx.UpdateStatus(newTweet);
Of course you have to handle also how this program will execute periodically, each 10 minutes for example.
If you intend to use AOuth then you have to setup your application on twitter to get the secret and API key, otherwise you can use the old authentication system, and yeah LinqToTwitter handle all this for you :).
Download
I have a lot of tricks to do with LinqToTwitter, and from those, a bot available publically to make users able to set their hashtags or specific words to build their own bot with just few clicks, but I can’t make it to sell an ASP.NET hosting and make my projects real :), any help will be appreciated of course.
Twinq test :