Monday, December 8, 2014

Send Direct Message to Twitter


Send Direct Message to Twitter with out using third party API


1. Need register and get both key from twitter devolper site.

TwitterConsumerKey
TwitterConsumerSecretKey

    1.1. Registration time you mention the call back url.

    TwitterCallBackUrl


2. Your model
    public class TwitterAPIKey
    {
        public string ConsumerKey { get; set; } //TwitterConsumerKey
        public string ConsumerSecretKey { get; set; } //TwitterConsumerSecretKey
        public string oAuthToken { get; set; }
        public string oAuthTokenSecret { get; set; }
        public string ScreenName { get; set; }
        public string twUserId { get; set; }
        public string oAuthAccessToken { get; set; }
        public string oAuthVerifier { get; set; }
    }

3. Direct message: Postmethod

    3.1. Image for Direct message:



   3.2. Code for Post:
public JsonResult SendDirectMessageToMultipleUser(string[] screenname, string message)
        {
            TwitterAPIKey _twitterAPIKey = new TwitterAPIKey();
            var oAuthConsumerKey = Utility.GetAppSettings("TwitterConsumerKey");
            var oAuthConsumerSecret = Utility.GetAppSettings("TwitterConsumerSecretKey");
            if (screenname != null && !string.IsNullOrEmpty(message))
            {
                string screenName = screenname != null ? String.Join(",", screenname) : string.Empty;
                string[] screen_name = screenName.ToString().Split(',');
                if (screen_name != null && screen_name.Count() > 0)
                {
                    foreach (string sname in screen_name)
                    {
                        TwitterUser _user = this._coreService.getTokenByName(sname); //twitter user detail from your db(oAuthAccess token and oAuthTokenSecret)
                        _twitterAPIKey.ConsumerKey = oAuthConsumerKey;
                        _twitterAPIKey.ConsumerSecretKey = oAuthConsumerSecret;
                        _twitterAPIKey.oAuthToken = _user.oAuthAccessToken;
                        _twitterAPIKey.oAuthTokenSecret = _user.oAuthTokenSecret;
                        _twitterAPIKey.ScreenName = sname;
                        string responseResult = string.Empty;
                        //postDirectMessage
                        responseResult = PostDirectMessageToTwitter(message, _twitterAPIKey);
                    }
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            return Json(false, JsonRequestBehavior.AllowGet);
        }

        private string PostDirectMessageToTwitter(string message, TwitterAPIKey twitterToken)
        {
            //The twitter json url to post the direct message
            var oauth_token = twitterToken.oAuthToken; //Access token
            var oauth_token_secret = twitterToken.oAuthTokenSecret; //Access token secret
            var oauth_consumer_key = twitterToken.ConsumerKey;
            var oauth_consumer_secret = twitterToken.ConsumerSecretKey;
            var screen_name = twitterToken.ScreenName;
            var oauth_version = "1.0";
            var oauth_signature_method = "HMAC-SHA1";
            var oauth_nonce = Convert.ToBase64String(
            new ASCIIEncoding().GetBytes(
            DateTime.Now.Ticks.ToString()));
            var timeSpan = DateTime.UtcNow
            - new DateTime(1970, 1, 1, 0, 0, 0, 0,
            DateTimeKind.Utc);
            var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
            var resource_url = "https://api.twitter.com/1.1/direct_messages/new.json";
            var text = message;
            var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
            "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}&text={7}";
            var baseString = string.Format(baseFormat,
            oauth_consumer_key,
            oauth_nonce,
            oauth_signature_method,
            oauth_timestamp,
            oauth_token,
            oauth_version,
            screen_name,
            Uri.EscapeDataString(text)
            );
            baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url),
            "&", Uri.EscapeDataString(baseString));
            var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
            "&", Uri.EscapeDataString(oauth_token_secret));
            string oauth_signature;
            using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
            {
                oauth_signature = Convert.ToBase64String(
                hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
            }
            var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_signature_method=\"{1}\", oauth_timestamp=\"{2}\", oauth_nonce=\"{3}\", " +
                "oauth_version=\"{4}\", oauth_token=\"{5}\", oauth_signature=\"{6}\"";
            var authHeader = string.Format(headerFormat,
            Uri.EscapeDataString(oauth_consumer_key),
            Uri.EscapeDataString(oauth_signature_method),
            Uri.EscapeDataString(oauth_timestamp),
            Uri.EscapeDataString(oauth_nonce),
            Uri.EscapeDataString(oauth_version),
            Uri.EscapeDataString(oauth_token),
            Uri.EscapeDataString(oauth_signature)
            );
            var postBody = "text=" + Uri.EscapeDataString(text) + "&screen_name=" + Uri.EscapeDataString(screen_name);
            ServicePointManager.Expect100Continue = false;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
            request.Headers.Add("Authorization", authHeader);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            using (Stream stream = request.GetRequestStream())
            {
                byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
                stream.Write(content, 0, content.Length);
            }
            var responseResult = "";
            try
            {
                //success posting
                WebResponse objWebResponse = request.GetResponse();
                StreamReader objStreamReader = new StreamReader(objWebResponse.GetResponseStream());
                responseResult = objStreamReader.ReadToEnd().ToString();
            }
            catch (Exception ex)
            {
                //throw exception error
                responseResult = "Twitter Direct Message Post Error: " + ex.Message.ToString() + ", authHeader: " + authHeader;
            }
            return responseResult;
        }

No comments:

Post a Comment