📜 ⬆️ ⬇️

Twitter app. Sending tweets and private messages

First you need to add all the cubes ...

image

If you have the will of fate to write a twitter application, but you still do not know where to start, then I hope this post will help you build a logical chain of actions that, in the end, will lead to an application that can send tweets to the tape and personal messages to users.
')


And now the points:

1. First you need an account on Twitter . Not yet? Then it is worth registering.
We remember or restore your login and password in memory and proceed to the next item.

2. Now let's go to the Twitter Developers website, where, for authorization, we will use
tritter login and password . Once the authorization is successful, you need to select in the account menu
point "My applications" and on the page that opens, click on the button image

image

After you fill in all the fields and create an application, 2 keys will be assigned to it (the application):
Consumer key and
Consumer secret
They are available in the OAuth settings section of the Details tab of your application.

image

3. The next step in creating a twitter application is to write OAuth authorization. This is described in detail in the article on Twitter with your own hands on C #. Part 1: OAuth authorization . You will need to build an application
from this article. If everything goes well, then in the end you will pass OAuth authorization and you will be assigned 2 more important values:
Access token and
Access token secret
They are also available in the Your access token section of the Details tab of your application. Also, pay attention to the Access level field in the same section. In order for the application to be able to post tweets and send private messages, it must be set to Read, write, and direct messages . If this is not the case, then you need to configure Access on the Settings tab and re-authorize OAuth.

image

If you open your Twitter account, go to the settings and open the "Applications" menu, then your app should be listed there, registered on Twitter Developers :

image

4. Now we remember the keys that we received in the first stages:
Consumer key
Consumer secret
Access token
Access token secret

Create a class MessageSender, which will be engaged in sending messages:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.Net; using System.IO; namespace TwitterOAuth { class MessageSender { private readonly string consumerKey; private readonly string consumerSecret; private readonly string oauthToken; private readonly string oauthTokenSecret; private const string headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " + "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " + "oauth_token=\"{4}\", oauth_signature=\"{5}\", " + "oauth_version=\"{6}\""; /// <summary> ///      /// </summary> public MessageSender(string consumer_key, string consumer_secret, string oauth_token, string oauth_token_secret) { this.consumerKey = consumer_key; this.consumerSecret = consumer_secret; this.oauthToken = oauth_token; this.oauthTokenSecret = oauth_token_secret; } /// <summary> ///     /// </summary> /// <param name="user">without @</param> /// <param name="text"></param> public void SendDirectMessage(string user, string text) { string post_data; string resource_url; string authHeader = GetPostDirectMessageBaseString(text, user, oauthToken, oauthTokenSecret, out post_data, out resource_url); Send(resource_url, post_data, authHeader); } /// <summary> ///    /// </summary> /// <param name="text"></param> public void SendTwit(string text) { string post_data; string resource_url; string authHeader = GetStatusBaseString(text, oauthToken, oauthTokenSecret, out post_data, out resource_url); Send(resource_url, post_data, authHeader); } private void Send(string resource_url, string post_data, string auth_header) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url); request.Headers.Add("Authorization", auth_header); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = post_data.Length; using (Stream stream = request.GetRequestStream()) { byte[] content = ASCIIEncoding.ASCII.GetBytes(post_data); stream.Write(content, 0, content.Length); } try { WebResponse response = request.GetResponse(); Console.WriteLine(response.ToString()); } catch (WebException e) { Console.WriteLine(e.Status.ToString()); } } private string GetBaseString(string oauth_token, string oauth_token_secret, string post_data, string resource_url) { 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 baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&" + post_data; var baseString = string.Format(baseFormat, consumerKey, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, oauth_version ); baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString)); //Encrypt data var compositeKey = string.Concat(Uri.EscapeDataString(consumerSecret), "&", 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))); } //Finish Auth header var authHeader = string.Format(headerFormat, Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp), Uri.EscapeDataString(consumerKey), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_version) ); return authHeader; } private string GetStatusBaseString(string status, string oauth_token, string oauth_token_secret, out string post_data, out string resource_url) { post_data = "status=" + Uri.EscapeDataString(status); resource_url = "https://api.twitter.com/1.1/statuses/update.json"; return GetBaseString(oauth_token, oauth_token_secret, post_data, resource_url); } private string GetPostDirectMessageBaseString(string text, string screen_name, string oauth_token, string oauth_token_secret, out string post_data, out string resource_url) { post_data = "screen_name=" + Uri.EscapeDataString(screen_name) + "&text=" + Uri.EscapeDataString(text); resource_url = "https://api.twitter.com/1.1/direct_messages/new.json"; return GetBaseString(oauth_token, oauth_token_secret, post_data, resource_url); } } } 


In order to send a message to the tape, call the SendTwit method ("some message"),
and to send a private message, call the method SendDirectMessage ("user", "some message")

  static void Main(string[] args) { //  MessageSender ms = new MessageSender(consumerKey, consumerSecret, oauth_token, oauth_token_secret); ms.SendTwit("I can sent twit"); //         ms.SendDirectMessage("user", "Direct message for user"); Console.ReadLine(); } 


Please note that two times the same message can not be published to the tape.

And here, in fact, the result:

image

If you want to further expand the capabilities of your application, here is the REST API v1.1 Resources Documentation . In the case of sending private messages , the code sets two parameters: screen_name and text, and resource_url is taken from the documentation: Example Request section, POST field

  private string GetPostDirectMessageBaseString(string text, string screen_name, string oauth_token, string oauth_token_secret, out string post_data, out string resource_url) { post_data = "screen_name=" + Uri.EscapeDataString(screen_name) + "&text=" + Uri.EscapeDataString(text); resource_url = "https://api.twitter.com/1.1/direct_messages/new.json"; return GetBaseString(oauth_token, oauth_token_secret, post_data, resource_url); } 


Note that between the parameters is put & , and the order of following these parameters is important for building a Signature Base String in the GetBaseString method. To check in the future the correctness of following the parameters, you can use the OAuth tool. To do this, open, for example, Send private messages , find the OAuth tool on the right, select your application in the drop-down list and click Generate Oauth signature

image

At the bottom of the page that opens, an example of the request will be written, the URI, if you click the button image This will generate a Signature base string, Authorization header, etc.

Good luck!

Source: https://habr.com/ru/post/208662/


All Articles