Viber Bot Python Library

repository·master·Indexed 41 days ago

https://github.com/viber/viber-bot-python

A Python library for developing bots on the Viber platform. It provides abstractions for configuring bots, handling incoming webhooks, verifying signatures, and sending various message types including Text, Picture, Video, Location, and Keyboard messages. Supports Python >= 2.7.0 and provides the Api class for managing bot interactions and ViberRequest event handling.

Tokens
3K
Snippets
12
Records
15
Agent score
2%

What's inside Viber Bot Python

  1. Understand ViberRequest event types

    master

    When you parse a request, it returns a specific subclass of ViberRequest based on the event_type. Common request objects include:

    • ViberConversationStartedRequest: Triggered when a user opens a conversation (e.g., via deep link). Allows sending one 'welcome message'.
    • ViberMessageRequest: Triggered when a user sends a message to the bot.
    • ViberSubscribedRequest: Triggered when a user subscribes to the bot.
    • ViberUnsubscribedRequest: Triggered when a user unsubscribes.
    • ViberSeenRequest: Triggered when a user sees a message.
    • ViberDeliveredRequest: Triggered when a message is delivered.
    • ViberFailedRequest: Triggered when a message fails to send.
  2. Install the viberbot library

    master

    You can install the Viber Python Bot API library using pip. For production environments, it is recommended to specify the version in your requirements.txt file.

    Prerequisites:

    • Python >= 2.7.0
    • An active Viber Public Account/bot with an authentication token.
    • An HTTPS server endpoint with a trusted (ca.pem) certificate (self-signed certificates are not supported).
    viberbot==1.0.11
  3. Send a welcome message to new users

    master

    Viber allows you to send exactly one 'welcome message' to a user when they first open a conversation, even before they have officially subscribed. This is handled by responding to the ViberConversationStartedRequest event.

    Flow:

    1. User opens conversation.
    2. Viber sends conversation_started event to your webhook.
    3. Your server receives the event and sends the welcome message as part of the logic (or as a direct API call).
    @app.route('/', methods=['POST'])
    def incoming():
    	viber_request = viber.parse_request(request.get_data())
    
    	if isinstance(viber_request, ViberConversationStartedRequest) :
    		viber.send_messages(viber_request.get_user().get_id(), [
    			TextMessage(text="Welcome!")
    		])
    
    	return Response(status=200)
  4. Handle incoming Viber requests

    master

    To process incoming messages, you should:

    1. Verify the request signature using viber.verify_signature() to ensure the request is actually from Viber.
    2. Parse the raw request data using viber.parse_request(data) to get a request object.
    3. Use isinstance() to check the type of the request (e.g., ViberMessageRequest, ViberSubscribedRequest, ViberFailedRequest) and respond accordingly.

    Example using Flask:

    from flask import Flask, request, Response
    from viberbot import Api
    from viberbot.api.bot_configuration import BotConfiguration
    from viberbot.api.messages.text_message import TextMessage
    from viberbot.api.viber_requests import ViberMessageRequest, ViberSubscribedRequest, ViberFailedRequest
    
    app = Flask(__name__)
    viber = Api(BotConfiguration(
        name='PythonSampleBot',
        avatar='http://site.com/avatar.jpg',
        auth_token='YOUR_AUTH_TOKEN_HERE'
    ))
    
    @app.route('/', methods=['POST'])
    def incoming():
        # Verify signature
        if not viber.verify_signature(request.get_data(), request.headers.get('X-Viber-Content-Signature')):
            return Response(status=403)
    
        # Parse request
        viber_request = viber.parse_request(request.get_data())
    
        if isinstance(viber_request, ViberMessageRequest):
            message = viber_request.message
            # Echo back the message
            viber.send_messages(viber_request.sender.id, [message])
        elif isinstance(viber_request, ViberSubscribedRequest):
            viber.send_messages(viber_request.get_user.id, [
                TextMessage(text="thanks for subscribing!")
            ])
        elif isinstance(viber_request, ViberFailedRequest):
            print(f"Client failed receiving message: {viber_request}")
    
        return Response(status=200)
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=443, ssl_context=('server.crt', 'server.key'))
  5. Parse incoming requests into ViberRequest objects

    master

    Use parse_request(request_data) to convert raw post data into a structured ViberRequest object. This object allows you to easily access the event_type, timestamp, and specific data associated with the event (like user profiles or message content).

    viber_request = viber.parse_request(request.get_data())
  6. Configure and manage webhooks with Api.set_webhook

    master

    Use set_webhook to register your server's URL with Viber so it can send incoming events to you. You can optionally provide a list of subscribed webhook_events.

    To remove the webhook, use unset_webhook().

    event_types = viber.set_webhook('https://example.com/incoming')
    # To remove:
    viber.unset_webhook()
  7. Configure the Viber Bot API

    master

    To initialize the bot, you must create a BotConfiguration object containing your bot's name, avatar URL, and the unique auth_token obtained from the Viber developer portal. Pass this configuration to the Api class to create your main bot instance.

    from viberbot import Api
    from viberbot.api.bot_configuration import BotConfiguration
    
    bot_configuration = BotConfiguration(
    	name='PythonSampleBot',
    	avatar='http://viber.com/avatar.jpg',
    	auth_token='YOUR_AUTH_TOKEN_HERE'
    )
    viber = Api(bot_configuration)
  8. Fetch user details and online status

    master

    Get User Details

    Use get_user_details(viber_user_id) to fetch specific data for a user. Note that this request can only be sent twice per user ID within a 12-hour period.

    Get Online Status

    Use get_online(viber_user_ids) passing an array of strings to check the status of multiple users at once.

    user_data = Api.get_user_details("userId")
    
    users = Api.get_online(["user1id", "user2id"])
  9. Verify incoming request signatures

    master

    To ensure requests are actually coming from Viber, use verify_signature. You must pass the raw post data from the request and the signature found in the X-Viber-Content-Signature HTTP header.

    if not viber.verify_signature(request.get_data(), request.headers.get('X-Viber-Content-Signature')):
    	return Response(status=403)
  10. Create various message types

    master

    The viberbot.api.messages package contains various message classes. Each class has a unique constructor to represent different media and data types.

    Common message types include:

    • TextMessage
    • ContactMessage
    • PictureMessage
    • VideoMessage
    • UrlMessage
    • LocationMessage
    • StickerMessage
    • RichMediaMessage
    • KeyboardMessage
    from viberbot.api.messages import (
        TextMessage,
        ContactMessage,
        PictureMessage,
        VideoMessage
    )
    from viberbot.api.messages.data_types.contact import Contact
    
    # creation of text message
    text_message = TextMessage(text="sample text message!")
    
    # creation of contact message
    contact = Contact(name="Viber user", phone_number="0123456789")
    contact_message = ContactMessage(contact=contact)
    
    # creation of picture message
    picture_message = PictureMessage(text="Check this", media="http://site.com/img.jpg")
    
    # creation of video message
    video_message = VideoMessage(media="http://mediaserver.com/video.mp4", size=4324)
  11. Set up a Webhook for Viber messages

    master

    Viber uses webhooks to push messages to your server. Once your HTTPS server is running and internet-facing, call set_webhook(url) with your server's URL. Viber will then send all incoming events to that endpoint.

    viber.set_webhook('https://mybotwebserver.com:443/')