Creating a full-fledged Viberbot on Django 2 and the Viber REST API. Part One - Webhook

Install Webhook for bot to work on viber and send the first POST request to the backend messenger


Based on my experience in developing for Viber and a lot of mixed opinions, I publish a series of articles on creating and launching viberbot. To understand the full picture as a whole, we will work with a clean REST API VIBER, without any wrappers.

Radio Viber proved to be too non-standard, so we will create a classic dialog bot (of which many thousands have been divorced in telegram ).

At the same time, we will see all the disadvantages and advantages of botviber and understand: what is easier to be in Russia - botviber VS bottelegram, the main differences between the bot development of these platforms.

image

With a more meager set of methods than in the cart - however, in Viber you can create much more effective UI interfaces and not limit yourself to the dull gray color of menu buttons and inline buttons.

The article is more targeted at beginners who did not manage to deal with the Viber REST API.

Within a month, 1-2 tutorial per week, anyone who wants to will learn how to create bots on the Viber messenger, with a personal admin panel, bulk-messages distribution tools, without any designers and platforms. We also create a minilanding-page (like telegram bots) to search for and promote your bot.

I recommend studying Django in parallel, who has not yet started, and the features of his work in develop and production modes.

Not enough bot - then let's start


1. Install and run Django> = 2.1 and Python> = 3.6.
create myviberbot application using the standard Django manager command:

python manage.py startapp myviberbot

Do not forget to add it to the settings.py file in this section:

#    settings.py 

DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myviberbot', #    
]
#

Suppose I linked my HTTPS domain and I want to install webhook for viber-bot at:
yourdomain.ru/webhook2020 - And you change yourdomain.ru to your domain, of course.

And we will handle all the events in the def trx_bot () function from myviberbot.views - but more about it ...

First of all, we will make the corresponding corrections to the urls.py file in the listing its full contents:

# urls.py
from django.contrib import admin
from django.urls import path
from myviberbot.views import trx_bot
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('webhook2020', trx_bot), #url    - webhook2020, 
#  ,   
    ]

If you donโ€™t go deep into Djangoโ€™s subtleties - here, in the code above, we sent absolutely all requests (request) to webhook2020 to the trx_bot function, which is located in the myviberbot project folder in the views.py file. Consider it below.

# views.py   myviberbot

from django.shortcuts import HttpResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def trx_bot(request):
    if request.method == "POST":
        viber = json.loads(request.body.decode('utf-8'))
        if viber['event'] == 'webhook':
            print(viber)
            print("Webhook  ") # -    
#       webhook
            return HttpResponse(status=200)
        else:
            print("  Webhook -   ,   POSTMAN") 
            return HttpResponse(status=500)
        return HttpResponse(status=200)

After receiving 200 OK from us, the backend viber servers are ready to work with us.

You will see the message that came to your messenger in the chat of your bot (dialogue function added or Chat 1to1 added).

But how to send a POST request to the backend Viber or install Webhook - this question is of concern to many who are used to working with telegram using the get method, but it's okay - we carefully read on:

2. I am sure that at this point, you have already received the bot token here and deployed the django application on the hosting ( VDS or Shared ) or in the local environment (in this case, the ngrok temporary tunnel will help),

a) If we are testing the project on the local machine, then we will start it with the manager team:
python manage.py runserver

After a successful start, we attach ngrok.

b) And there are a lot of ways to launch on a hosting - personally, I use passenger on beget. In the case of beget, put the version of the container with php5.6 not higher - this is advice from begetovtsev.

So - the application has started - put webhook


Whoever knows how to use the POSTMAN plugin for Chrome can skip the next paragraph and send the POST for the webhook directly from the browser.

We will create a file on the local machine with any name, for example sethook.py, not forgetting the requests library (pip install requests)

#sethook
import requests
import json
auth_token = 'xxxxxxxxx-ttttttttttttttttt-wwwwwwwwwwww' #       #.2
hook = 'https://chatapi.viber.com/pa/set_webhook'
headers = {'X-Viber-Auth-Token': auth_token}


sen = dict(url='https://yourdomain.ru/webhook2020',
           event_types = ['unsubscribed', 'conversation_started', 'message', 'seen', 'delivered'])
# sen -  body     backend  viber
#seen, delivered -  ,     ,
#         ,   )

r = requests.post(hook, json.dumps(sen), headers=headers)
# r -       viber 
print(r.json())
#   print    "status_message":"ok" -   ,
#    

We start it with the command from the working directory:
python sethook.py

That's it! Webhook is set by the POST method. You see a message that came to your chat (Dialog function added), which means that webhook is installed.

To be continued ...

In the next article we will analyze event ["conversation_started"], for the initial contact with users and initialization of interaction with them, you will find out that your viberbot knows about all users and what he does not know.

PART 2:
Creating a full-fledged Viberbot on Django 2 and the Viber REST API. Part Two - onversation_started

Materials:

Documentation of the viber REST API
Django version 2.2
Radio-miner

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


All Articles