📜 ⬆️ ⬇️

API VKontakte and XDocument for the smallest

Good time of day.

I want to talk again about the simplest ways to work with the VK API and I really hope that this article can be a starting point for novice developers. We will work with a rather diverse method of messages.getHistory, and using XDocument to get a photo. Anyone who has learned to pass authorization and wants to try out working with the API, please under the cat.

Let's start?

So, we logged in, got a token. What's next? I want to give an example with a rather interesting method that will help beginners to get comfortable in the world of the VKontakte API. If you did not find the method mentioned above in the list of basic methods , then go here and see a large list of various possibilities. We will begin work with one of them.

Our task for today is to receive all messages with the user, process xml nodes and download photos from all correspondence. It looks like the node that we need

')
Obviously, the description contains almost all the detailed information about the method. So let's consider:
Description:
Returns the message history for the specified user or group conversation.

Result:
Returns an array of message objects - personal messages in the specified dialog with the user or group conversation. Each message object contains a set of fields, a description of which is available here.


We have as many as 6 parameters, 2 of which are required. More about each:

uid is probably the most important parameter. The server needs to know with which user we want to get the message history.
chat_id is an optional parameter if we specified uid .
offset - the offset for the sample. Simply put, that parameter, without which we will not be able to receive a large correspondence due to the limitation of 200 messages in one reply.
count is the number of messages we want to receive from the server. Remember to limit to 200 messages per request.
start_mid - message identifier starting from which subsequent messages should be received. Please do not confuse with count . In this argument, we enter the message id, not its sequence number.
rev - from which message we need correspondence. Last or first. 0 by default, which means reverse chronological order.

The most necessary

Not bad, huh? Let's try it out.
I remind you that we will work with LINQ to XML. We connect the required namespace

using System.Xml.Linq; 


Now we have access to a very powerful, in my opinion, XML parser. So let's announce it

 XDocument doc; 


Everything worked out? Then we continue. We remember that if we have a very large correspondence, then we need to use the offset and specify the offset parameter. Then create a counter that will increase by 200 each iteration. And also, create a counter for the dynamic names of photos when saving

 int m=0; int k=0; 


Of course, let's not forget about WebClient, which will help us download a photo.

 WebClient src_client = new WebClient(); 


I think it’s worth creating a separate folder so as not to clog all other program files with nostalgic photos.
 Directory.CreateDirectory("img/"); 


I hope you still get it. And now the fun part. Now we will make a request to the server and indicate to it the arguments that we need to achieve our task.

 doc = XDocument.Load("https://api.vk.com/method/messages.getHistory.xml?uid=123456&offset=" + m + "&count=200&access_token=" + token); 


First, note that we have specified the format of the .xml data we receive for the messages.getHistory method. It usually returns JSON that LINQ to XML cannot handle. We also specified the uid of the user with whom we want the story. And of course the offset , which we will change every time, until we reach the end. count set the one you need. But remember that no more than 200, and then the server gets tired and goes to rest will return us an error. And of course we will specify a token.

Work with XML

Now consider the cycle itself. I do not pretend to optimized code and I understand that it can be shortened, but I want to show the detailed work of the parser with similar XML.

 while (true) { doc = XDocument.Load("https://api.vk.com/method/messages.getHistory.xml?uid=12345&offset=" + m + "&count=200&access_token=" + token);//   xml      foreach (XElement el in doc.Root.Elements())//    { //         if (el.Name.ToString() == "message") { foreach (XElement el_msg in el.Elements())//    message { //     if (el_msg.Name == "attachment") { foreach (XElement el_attch in el_msg.Elements()) { //     ,   ,    if (el_attch.Name == "photo") { foreach (XElement el_photo in el_attch.Elements()) { //     if (el_photo.Name == "src_xbig") { //    img/ src_client.DownloadFile(el_photo.Value, "img/img" + k + ".jpg"); k++; } } } } } } } } //      count m += 200; } 


LINQ

Thanks to Atreides07 for the LINQ version. Unfortunately, I did not think to write it right away.
 while (true) { var doc = XDocument.Load("https://api.vk.com/method/messages.getHistory.xml?uid=12345&offset=" + m + "&count=" + n + "&access_token=" + token);//   xml      var photoElements= doc.Root.Elements("message") .SelectMany(el => el.Elements("attachment") .SelectMany(el_msg => el_msg.Elements("photo") .SelectMany(elAttch => elAttch.Elements("src_xbig")))); foreach (var el_photo in photoElements) { //    img/ src_client.DownloadFile(el_photo.Value, "img/img" + k + ".jpg"); k++; } //      count m += n; } 


Xpath

 using System.Xml.XPath; 

I also think that it is worth showing the version with XPath.
  //   XPathDocument document_x = new XPathDocument("https://api.vk.com/method/messages.getHistory.xml?uid=12345&offset=" + m + "&count=200&access_token=" + token); XPathNavigator navigator = document_x.CreateNavigator(); //  string str_exp = "//message//attachment//photo//src_big"; XPathExpression expres = XPathExpression.Compile(str_exp); XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable); expres.SetContext(manager); XPathNodeIterator nodes = navigator.Select(expres); while (nodes.MoveNext())//    src_client.DownloadFile(nodes.Current.ToString(), "img/imj" + k + ".jpg");//  

Of course, do not forget about the cycle and the increase in m.

That's all. Open the folder where we ran our program, find the folder img and enjoy the result.

Conclusion

As we can see, working with the VKontakte API is quite simple, and with the convenient features of LINQ to XML, it becomes more detailed and more understandable. Hope you enjoyed it. Thanks for reading.

Please indicate any shortcomings in the article. Will be studying.

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


All Articles