Bot for VK on Python with MySQL in an hour, part 1
In this tutorial I want to show how to make the simplest bot with a fairly large basic functionality.
So, let's begin.
What do we need?
- Python since version 2.7 (All code was tested on versions 2.7.16 and 3.7.3)
- PyMySQL Module
- Vk_api module
- Requests module
- Vkontakte group (Attention! The bot will work precisely from the side of the group, and not from the side of the person’s account)
- Database (including user data, etc.)
Connection
First, we’ll connect all the libraries:
import vk_api
from vk_api.utils import get_random_id
from from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
import pymysql.cursors
import requests
Now you can begin to configure the bot and database.
In my case, all the data is in the config.py file. You can prescribe them anywhere. It will not affect the functionality in any way.
Database connection
To do this, create a function using the PyMySQL module:
def get_connection():
connection = pymysql.connect(host='you_host',
user='you_user',
password='you_password',
db='you_db'
charset='utf8mb4',
cursorclass=mymysql.cursors.DictCursor)
return connection
This function will return data for further work with the database. Accordingly, we substitute our data where we see "you_".
Configure bot connection
To begin, we need to go to the settings of our group:

Select the Work with API tab and create an access key (in the future it will be useful for us to connect to the bot.

Go to the “Long Poll API” tab and enable it. And also select the latest available version

Go to the "Event Types" and also include everything that you need. For example, I have included everything

And the last. Go to "Messages"> "Settings for the bot" and enable the possibility of bots. Now you can go to the program itself.

Connecting a bot to a group
Now we will register the connection of the bot to long poll and the verification of actions from the side of VK:
vk_session = vk_api.VkApi(token="Ваш ключ, который вы создали на странице настроек")
#пример vk_session = vk_api.VkApi(token = "a6f87v8c9a9sa87a7af9a0f9f9v8a6s6c5b5m6n8bds09asc8d7b87d87bd87n"
vk = vk_session.get_api()
longpoll = VkBotLongPoll(vk_session, "id вашей группы Вконтакте")
#пример longpoll = VkBotLongPoll(vk_session, "637182735")
for event in longpoll.listen(): #Проверка действий
if event.type == VkBotEventType.MESSAGE_NEW:
Now we have included the bot itself, which will receive incoming messages and analyze them for further work.
Work with a bot
Let's add a bot function to respond to any of our messages with our messages. To do this, after the last line we write this:
if event.type == VkBotEventType.MESSAGE_NEW: # последняя строчка
#проверяем не пустое ли сообщение нам пришло
if event.obj.text != '':
#проверяем пришло сообщение от пользователя или нет
if event.from_user:
vk.messages.send(
user_id=event.obj.from_id,
random_id=get_random_id(),
message=event.obj.text)
Now about the vk.messages.send () method. This is the standard method of the vk_api module. You can read about the methods on the official Vkontakte documentation (the link will be below).
It allows you to send messages to users.
The user_id argument indicates to which account this message should be sent. In our case, event.obj.from_id points to the account that just sent us a message. That is, we send a message to the person who sent it to us.
This argument is required!
The random_id argument is needed so that Vkontakte does not send messages 2 times. This argument is required! Message
argumentactually indicates what message we should send. Event.obj.text stores information about what text in the message we received. This argument is also required.
You can read more about the arguments to this method on the official Vkontakte page.
Launch
Now our bot is ready and we can start it. After starting, you can safely write to the bot and see the result.
Total
This part 1 is over. We learned to turn on the bot. Configure it, as well as send messages.
In part 2 we will analyze how to use the PyMySQL library to enter messages into the database and so on.
Thank you for reading!
Useful resources
Official apk documentation Vkontakte
Official page on PyMySQL module