Vineet Jangir
Vineet Jangir

Reputation: 11

How to implement direct message using twitter API in c#?

I want to access direct messages using Twitter API. What do we require to fetch direct message like URL, Header, type of authentication?

var fullUrl = "https://api.twitter.com/1.1/direct_messages/events/list.json";
            var _timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0);
            var timestamp = Convert.ToInt64(_timeSpan.TotalSeconds).ToString(CultureInfo.InvariantCulture);

            var _oauthNonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(
                 DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture)));

            // Add all the OAuth headers we'll need to use when constructing the hash.
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("oauth_consumer_key", consumerKey);
            data.Add("oauth_signature_method", "HMAC-SHA1");
            data.Add("oauth_timestamp", timestamp);
            data.Add("oauth_nonce", _oauthNonce);
            data.Add("oauth_token", accessToken);
            data.Add("oauth_version", "1.0");

            // Generate the OAuth signature and add it to our payload.
            data.Add("oauth_signature", GenerateSignature(fullUrl, data));

            // Build the OAuth HTTP Header from the data.
            string oAuthHeader = GenerateOAuthHeader(data);

            using (var http = new HttpClient())
            {
                http.DefaultRequestHeaders.Add("Authorization", oAuthHeader);

                var httpResp = await http.GetAsync(fullUrl);
                var respBody = await httpResp.Content.ReadAsStringAsync();

                return respBody;
            }

but getting "Authorization required response".

Upvotes: 1

Views: 420

Answers (1)

cdev
cdev

Reputation: 5371

Please follow instructions here. https://developer.twitter.com/en/docs/authentication/oauth-1-0a/authorizing-a-request

Specially, when creating signature, your question doesn't have the code for creating signature.

Follow this for it https://developer.twitter.com/en/docs/authentication/oauth-1-0a/creating-a-signature

If you use correct values, then there is no issue in your code.

Upvotes: 0

Related Questions