-
Notifications
You must be signed in to change notification settings - Fork 324
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #265 from prostomarkeloff/master
Change examples README, update doctrings in callback_bot.py (examples)
- Loading branch information
Showing
2 changed files
with
29 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,44 +1,62 @@ | ||
# -*- coding: utf-8 -*- | ||
from flask import Flask | ||
from flask import Flask, request | ||
import vk_api | ||
from vk_api.utils import get_random_id | ||
|
||
""" | ||
Пример бота для группы ВКонтакте использующего | ||
callback-api для получения сообщений. | ||
Подробнее: https://vk.com/dev/callback_api | ||
Перед запуском необходимо установить flask (pip install flask) | ||
Запуск: | ||
$ FLASK_APP=callback_bot.py flask run | ||
При развертывании запускать с помощью gunicorn (pip install gunicorn): | ||
$ gunicorn callback_bot:app | ||
""" | ||
|
||
app = Flask(__name__) | ||
vk_session = vk_api.VkApi(token='your_group_token') | ||
vk = vk_session.get_api() | ||
|
||
access_code = "smthing code" | ||
confirmation_code = 'smthing code' | ||
|
||
""" | ||
При развертывании путь к боту должен быть секретный, | ||
поэтому поменяйте my_bot на случайную строку | ||
Например: | ||
756630756e645f336173313372336767 | ||
Сгенерировать строку можно через: | ||
$ python3 -c "import secrets;print(secrets.token_hex(16))" | ||
""" | ||
@app.route('/my_bot', methods=['POST']) | ||
def bot(): | ||
# получаем данные из запроса | ||
data = json.loads(request.data) | ||
data = request.get_json(force=True, silent=True) | ||
# ВКонтакте в своих запросах всегда отправляет поле type: | ||
if 'type' not in data.keys(): | ||
if not data or 'type' not in data: | ||
return 'not ok' | ||
|
||
# проверяем тип пришедшего события | ||
if data['type'] == 'confirmation': | ||
# если это запрос защитного кода | ||
# отправляем его | ||
return access_code | ||
return confirmation_code | ||
# если же это сообщение, отвечаем пользователю | ||
elif data['type'] == 'message_new': | ||
# получаем ID пользователя | ||
from_id = data['object']['from_id'] | ||
# отправляем сообщение | ||
vk.messages.send(message='Hello World!', random_id=0, peer_id=from_id) | ||
vk.messages.send( | ||
message='Hello World!', | ||
random_id=get_random_id(), | ||
peer_id=from_id | ||
) | ||
# возвращаем серверу VK "ok" и код 200 | ||
return 'ok' | ||
|
||
# точка входа приложения | ||
if __name__ == '__main__': | ||
# запускаем веб-сервер | ||
app.run() | ||
return 'ok' # игнорируем другие типы |