⬆️ ⬇️

We write chat bot for VKontakte on python using longpoll

Now bots have become commonplace and are at every turn, but if you need your bot on the social network vkontakte, then it is easy to implement.



We will need:



  1. Python
  2. VK Api
  3. A wish


Well, quite straight for beginners



How to install Python?
Download , run the installer.



Where to write this code?
To a text document with a .py extension



And what to write?
Yes, even a notebook. I personally recommend Notepad ++



How to run?
Through the command line.

python \.py



How does it work?



It's very simple, in vk api there is such a thing, called longpool , it works like this:
Long Polling is a technology that allows you to receive data about new events using the "long requests". The server receives the request, but sends a response to it not immediately, but only when a certain event occurs (for example, a new message arrives), or the specified timeout expires.
Speaking Russian, we send a request to the server, and he, in turn, pokes at VKontakte if something happens there, for example, a message comes to us and he runs and tells us about it. From this and we will dance.

')

Technical implementation



First of all, we need to prove to Vkontakte that we are us, and not anyone else. This is done very simply.



 import vk_api import requests session = requests.Session() login, password = ' , email  ', ' ' vk_session = vk_api.VkApi(login, password) try: vk_session.auth(token_only=True) except vk_api.AuthError as error_msg: print(error_msg) return 


Remark, guys from VK recommend using a phone number as a login because otherwise, you can run into an anti-robot check, the one where you are asked to enter the missing digits from the phone number.



If the bot will sit in a group, then the authorization looks different.



 import requests import vk_api vk_session = vk_api.VkApi(token='      ') 




- What is a token?

- Such a thing from tsiferok and letters that you need to get in the settings of the group. To do this, simply open the “Community Management” section (“Manage the Page” if you have a public page), select the “Work with API” tab and click “Create Access Key”.



Now we call longpool.



 from vk_api.longpoll import VkLongPoll, VkEventType longpoll = VkLongPoll(vk_session) vk = vk_session.get_api() for event in longpoll.listen(): if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text: # longpoll,    : if event.text == '  ' or event.text == '  ': #    if event.from_user: #    vk.messages.send( #  user_id=event.user_id, message=' ' ) elif event.from_chat: #    vk.messages.send( #  chat_id=event.chat_id, message=' ' ) 


Messages can be not only the text you specify. For example:



 import datetime vk.messages.send( user_id=event.user_id, message=' : ' + str(now.strftime("%H:%M")) ) 


And you can attach pictures.



 attachments = [] from vk_api import VkUpload upload = VkUpload(vk_session) image_url = '  ' image = session.get(image_url, stream=True) photo = upload.photo_messages(photos=image.raw)[0] attachments.append( 'photo{}_{}'.format(photo['owner_id'], photo['id']) ) vk.messages.send( user_id=event.user_id, attachment=','.join(attachments), message=' ' ) 


You can come up with many more interesting things, but then think for yourself, and I just say that: links can be divided into parts. For example:



 image_url = 'http://.com/uploads/' + event.text + '.png' 


and no one forbade us to receive a response from the user on the example of Wikipedia:



 import wikipedia #  wikipedia.set_lang("RU") if event.text == '' or event.text == '' or event.text == '' or event.text == '' or event.text == 'Wikipedia' or event.text == 'wikipedia' or event.text == 'Wiki' or event.text == 'wiki': #          ...  wiki if event.from_user: #   KC vk.messages.send( user_id=event.user_id, message=' ' # " " ) elif event.from_chat: #    vk.messages.send( chat_id=event.chat_id, message=' ' # " " ) for event in longpoll.listen(): if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text: # longpoll if event.from_user: vk.messages.send( #    user_id=event.user_id, message='   : \n' + str(wikipedia.summary(event.text)) # "   "      api Wikipedia     ) break #   elif event.from_chat: #    vk.messages.send( chat_id=event.chat_id, message='   : \n' + str(wikipedia.summary(event.text)) # "   "      api Wikipedia     ) break #   continue 


Links to examples and documentation



An example of a bot working on DuckDuckGo api

Examples of using VK api (common)

Documentation on VK api One , Two



At this I say goodbye to you. Good coding.

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



All Articles