### Handle Conversation Started Event and Send Welcome Message in Python Source: https://github.com/viber/viber-bot-python/blob/master/README.md This example illustrates how to handle the `conversation_started` callback from Viber. It shows how to parse the incoming request and respond with a welcome `TextMessage` to the user who initiated the conversation, adhering to the Viber API's welcome message flow. ```python @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) ``` -------------------------------- ### FileMessage Object Definition and Python Example Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the FileMessage object, used for sending files, and provides a Python example for its instantiation, including media URL, size, and file name. ```APIDOC FileMessage object: Members: media: string size: long file_name: string ``` ```Python message = FileMessage(media=url, size=sizeInBytes, file_name=file_name) ``` -------------------------------- ### VideoMessage Object Definition and Python Example Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the VideoMessage object, used for sending video messages, and provides a Python example for its instantiation, including media URL, size, thumbnail, and duration. ```APIDOC VideoMessage object: Members: media: string (url of the video) size: int thumbnail: string duration: int ``` ```Python message = VideoMessage(media="http://site.com/video.mp4", size=21499) ``` -------------------------------- ### StickerMessage Object Definition and Python Example Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the StickerMessage object, used for sending Viber stickers, and provides a Python example for its instantiation using a sticker ID. ```APIDOC StickerMessage object: Members: sticker_id: int ``` ```Python message = StickerMessage(sticker_id=40100) ``` -------------------------------- ### Create a Flask HTTPS Server for Viber Bot Webhook Source: https://github.com/viber/viber-bot-python/blob/master/README.md Example of setting up a basic Flask web server that listens for incoming POST requests at the '/incoming' endpoint. It's configured to run over HTTPS, which is a prerequisite for Viber webhooks. ```python from flask import Flask, request, Response app = Flask(__name__) @app.route('/incoming', methods=['POST']) def incoming(): logger.debug("received request. post data: {0}".format(request.get_data())) # handle the request here return Response(status=200) context = ('server.crt', 'server.key') app.run(host='0.0.0.0', port=443, debug=True, ssl_context=context) ``` -------------------------------- ### URLMessage Object Definition and Python Example Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the URLMessage object, used for sending messages containing a URL, and provides a Python example for its instantiation. ```APIDOC URLMessage object: Members: media: string (URL string) ``` ```Python message = URLMessage(media="http://my.siteurl.com") ``` -------------------------------- ### ContactMessage Object Definition and Python Example Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the ContactMessage object, used for sending contact information, and provides a Python example for its instantiation, including the Contact data type. ```APIDOC ContactMessage object: Members: contact: Contact ``` ```Python from viberbot.api.messages.data_types.contact import Contact contact = Contact(name="Viber user", phone_number="+0015648979", avatar="http://link.to.avatar") contact_message = ContactMessage(contact=contact) ``` -------------------------------- ### TextMessage Object Definition and Python Example Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the TextMessage object, used for sending plain text messages, and provides a Python example for its instantiation. ```APIDOC TextMessage object: Members: text: string ``` ```Python message = TextMessage(text="my text message") ``` -------------------------------- ### PictureMessage Object Definition and Python Example Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the PictureMessage object, used for sending image messages, and provides a Python example for its instantiation, including media URL, text, and thumbnail. ```APIDOC PictureMessage object: Members: media: string (url of the message (jpeg only)) text: string thumbnail: string ``` ```Python message = PictureMessage(media="http://www.thehindubusinessline.com/multimedia/dynamic/01458/viber_logo_JPG_1458024f.jpg", text="Viber logo") ``` -------------------------------- ### Create Various Viber Bot Message Types Source: https://github.com/viber/viber-bot-python/blob/master/README.md Examples of instantiating different message objects provided by the Viber Bot API, including `TextMessage`, `ContactMessage`, and `PictureMessage`, demonstrating how to populate them with content. ```python 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") ``` -------------------------------- ### Handle Incoming Viber Requests with Flask Source: https://github.com/viber/viber-bot-python/blob/master/README.md This comprehensive example shows how to set up a Flask application to receive and process incoming Viber requests. It includes signature verification, parsing different request types (message, subscribed, failed), and sending echo replies or subscription messages. It demonstrates integration with the `viberbot` library. ```python from flask import Flask, request, Response from viberbot import Api from viberbot.api.bot_configuration import BotConfiguration from viberbot.api.messages import VideoMessage from viberbot.api.messages.text_message import TextMessage import logging from viberbot.api.viber_requests import ViberConversationStartedRequest from viberbot.api.viber_requests import ViberFailedRequest from viberbot.api.viber_requests import ViberMessageRequest from viberbot.api.viber_requests import ViberSubscribedRequest from viberbot.api.viber_requests import ViberUnsubscribedRequest app = Flask(__name__) viber = Api(BotConfiguration( name='PythonSampleBot', avatar='http://site.com/avatar.jpg', auth_token='445da6az1s345z78-dazcczb2542zv51a-e0vc5fva17480im9' )) @app.route('/', methods=['POST']) def incoming(): logger.debug("received request. post data: {0}".format(request.get_data())) # every viber message is signed, you can verify the signature using this method if not viber.verify_signature(request.get_data(), request.headers.get('X-Viber-Content-Signature')): return Response(status=403) # this library supplies a simple way to receive a request object viber_request = viber.parse_request(request.get_data()) if isinstance(viber_request, ViberMessageRequest): message = viber_request.message # lets echo back 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): logger.warn("client failed receiving message. failure: {0}".format(viber_request)) return Response(status=200) if __name__ == "__main__": context = ('server.crt', 'server.key') app.run(host='0.0.0.0', port=443, debug=True, ssl_context=context) ``` -------------------------------- ### Add Viber Bot Python Library to requirements.txt Source: https://github.com/viber/viber-bot-python/blob/master/README.md Shows how to add the `viberbot` library as a dependency in a Python project's `requirements.txt` file, specifying version 1.0.11 for installation via pip. ```python viberbot==1.0.11 ``` -------------------------------- ### LocationMessage Object Definition and Python Example Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the LocationMessage object, used for sending geographical location information, and provides a Python example for its instantiation, including the Location data type. ```APIDOC LocationMessage object: Members: location: Location ``` ```Python from viberbot.api.messages.data_types.location import Location location = Location(lat=0.0, lon=0.0) location_message = LocationMessage(location=location) ``` -------------------------------- ### Run Viber Bot Python Library Tests Source: https://github.com/viber/viber-bot-python/blob/master/README.md Instructions for setting up development dependencies and running unit tests for the Viber Bot Python library using `pytest` after cloning the repository. ```python # installing the dependencies: python setup.py develop # run the unit tests python -m pytest ``` -------------------------------- ### Initialize Viber Bot API with Configuration Source: https://github.com/viber/viber-bot-python/blob/master/README.md Demonstrates how to import the Viber Bot API and configure a new bot instance with a name, avatar URL, and authentication token. This sets up the basic bot object for further interactions. ```python 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) ``` -------------------------------- ### Viber Bot API Class Reference Source: https://github.com/viber/viber-bot-python/blob/master/README.md Detailed API documentation for the `Api` class in the `viberbot` Python library, outlining its constructor, methods, parameters, and return types for interacting with the Viber platform. ```APIDOC Api class: __init__(bot_configuration: object) bot_configuration: BotConfiguration .set_webhook(url: string, webhook_events: list) url: Your web server url webhook_events: optional list of subscribed events Returns: List of registered event_types Example: event_types = viber.set_webhook('https://example.com/incoming') .unset_webhook() Returns: None Example: viber.unset_webhook() .get_account_info() Returns: object (with JSON as per Viber API docs) Example: account_info = viber.get_account_info() .verify_signature(request_data, signature) Returns: boolean .parse_request(request_data) Returns: ViberRequest .send_messages(to, messages) Returns: list of message tokens sent .get_online(viber_user_ids) Returns: dictionary of users status .get_user_details(viber_user_id) Returns: dictionary of user's data .post_messages_to_public_account(to, messages) Returns: list of message tokens sent ``` -------------------------------- ### Instantiate KeyboardMessage Object in Python Source: https://github.com/viber/viber-bot-python/blob/master/README.md This snippet demonstrates how to create an instance of a `KeyboardMessage` object in Python, passing in the required `tracking_data` and `keyboard` parameters. ```python message = KeyboardMessage(tracking_data=tracking_data, keyboard=keyboard) ``` -------------------------------- ### Create a Viber Video Message Source: https://github.com/viber/viber-bot-python/blob/master/README.md Demonstrates how to instantiate a `VideoMessage` object in the Viber Python bot library. This object can be used to send video content to users. ```python video_message = VideoMessage(media="http://mediaserver.com/video.mp4", size=4324) ``` -------------------------------- ### Configure Standard Python Logger for Viber Bot Source: https://github.com/viber/viber-bot-python/blob/master/README.md Shows how to set up the standard Python logging module to display debug messages from the Viber Bot library. It configures a stream handler and a formatter for console output. ```python logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) ``` -------------------------------- ### Define and Use RichMediaMessage Object in Python Source: https://github.com/viber/viber-bot-python/blob/master/README.md This snippet defines a sample JSON structure for a rich media message and demonstrates how to instantiate a `RichMediaMessage` object in Python, including the rich media content and alternative text. ```python SAMPLE_RICH_MEDIA = """{ "BgColor": "#69C48A", "Buttons": [ { "Columns": 6, "Rows": 1, "BgColor": "#454545", "BgMediaType": "gif", "BgMedia": "http://www.url.by/test.gif", "BgLoop": true, "ActionType": "open-url", "Silent": true, "ActionBody": "www.tut.by", "Image": "www.tut.by/img.jpg", "TextVAlign": "middle", "TextHAlign": "left", "Text": "example button", "TextOpacity": 10, "TextSize": "regular" } ] }""" SAMPLE_ALT_TEXT = "upgrade now!" message = RichMediaMessage(rich_media=SAMPLE_RICH_MEDIA, alt_text=SAMPLE_ALT_TEXT) ``` -------------------------------- ### KeyboardMessage Object API Reference Source: https://github.com/viber/viber-bot-python/blob/master/README.md API documentation for the `KeyboardMessage` object, detailing its members and their types. ```APIDOC KeyboardMessage object: keyboard: JSON tracking_data: JSON ``` -------------------------------- ### RichMediaMessage Object API Reference Source: https://github.com/viber/viber-bot-python/blob/master/README.md API documentation for the `RichMediaMessage` object, detailing its members and their types. ```APIDOC RichMediaMessage object: rich_media: string (JSON) ``` -------------------------------- ### ViberConversationStartedRequest Object Definition Source: https://github.com/viber/viber-bot-python/blob/master/README.md Represents a `conversation_started` event, triggered when a user initiates a conversation with the Public Account or bot. This event allows sending a single welcome message. It inherits from `ViberRequest` and includes additional properties such as `message_token`, `type`, `context`, `user` (UserProfile), and `subscribed` status. ```APIDOC ViberConversationStartedRequest object Inherits from ViberRequest Description: Conversation started event fires when a user opens a conversation with the Public Account/ bot using the “message” button (found on the account’s info screen) or using a deep link. This event is not considered a subscribe event and doesn't allow the account to send messages to the user; however, it will allow sending one "welcome message" to the user. See sending a welcome message below for more information. event_type: string - always equals to the value of EventType.CONVERSATION_STARTED message_token: string - Unique ID of the message type: string - The specific type of conversation_started event. context: string - Any additional parameters added to the deep link used to access the conversation passed as a string user: UserProfile - the user started the conversation subscribed: boolean - Indicates whether a user is already subscribed Properties: message_token: string type: string context: string user: UserProfile ``` -------------------------------- ### Message Object Common Members and Constructor Arguments Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines common properties and constructor arguments for all Viber Message objects, including timestamp, keyboard, tracking data, optional keyboard, and optional tracking data. ```APIDOC Message Object (Common Members for Message interface): Properties: timestamp: long (Epoch time) keyboard: JSON (keyboard JSON) trackingData: JSON (JSON Tracking Data from Viber Client) Common Constructor Arguments (Message interface): Arguments: optionalKeyboard: JSON (Writing Custom Keyboards) optionalTrackingData: JSON (Data to be saved on Viber Client device, and sent back each time message is received) ``` -------------------------------- ### UserProfile Object Definition Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the structure of the UserProfile object, containing details about a Viber user such as ID, name, avatar, country, and language. ```APIDOC UserProfile object: Properties: id: string name: string avatar: string (Avatar URL) country: string (currently set in CONVERSATION_STARTED event only) language: string (currently set in CONVERSATION_STARTED event only) ``` -------------------------------- ### Fetch Details of a Specific Viber User Source: https://github.com/viber/viber-bot-python/blob/master/README.md Fetches detailed information about a specific Viber user based on their unique user ID. This ID is typically obtained from callbacks. This request has a rate limit of two calls per user ID within a 12-hour period. It takes a single Viber user ID and returns a dictionary containing user data. ```APIDOC Api.get_user_details(viber_user_id) viber_user_id: string - Viber user id Description: The get_user_details function will fetch the details of a specific Viber user based on his unique user ID. The user ID can be obtained from the callbacks sent to the account regarding user's actions. This request can be sent twice during a 12 hours period for each user ID. ``` ```Python user_data = Api.get_user_details("userId") ``` -------------------------------- ### Set Viber Bot Webhook URL Source: https://github.com/viber/viber-bot-python/blob/master/README.md Illustrates how to register a webhook URL with the Viber API using the `set_webhook` method. This tells Viber where to send incoming messages and events for the bot. ```python viber.set_webhook('https://mybotwebserver.com:443/') ``` -------------------------------- ### ViberRequest Base Object Definition Source: https://github.com/viber/viber-bot-python/blob/master/README.md The base object for all incoming Viber requests, containing fundamental event information. It includes properties like `event_type` (indicating the type of event) and `timestamp` (the epoch time of the request). ```APIDOC ViberRequest object event_type: string - according to EventTypes enum timestamp: long - Epoch of request time Properties: .event_type: string .timestamp: long ``` -------------------------------- ### Verify Incoming Viber Request Signature Source: https://github.com/viber/viber-bot-python/blob/master/README.md This method verifies the authenticity of incoming Viber requests by comparing the provided signature with the request data. It is crucial for security to ensure requests originate from Viber. It takes the raw POST data and the `X-Viber-Content-Signature` header as input and returns a boolean indicating validity. ```APIDOC Api.verify_signature(request_data, signature) request_data: string - the post data from request signature: string - sent as header X-Viber-Content-Signature Returns: boolean - suggesting if the signature is valid. ``` ```Python if not viber.verify_signature(request.get_data(), request.headers.get('X-Viber-Content-Signature')): return Response(status=403) ``` -------------------------------- ### ViberSubscribedRequest Object Definition Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the structure of the ViberSubscribedRequest object, triggered when a user subscribes. It inherits from ViberRequest and includes the event type and the user's profile. ```APIDOC ViberSubscribedRequest object: Inherits from ViberRequest Properties: event_type: string (always equals to the value of EventType.SUBSCRIBED) user: UserProfile object (the user started the conversation) ViberSubscribedRequest (Simplified): user: UserProfile ``` -------------------------------- ### ViberUnsubscribedRequest Object Definition Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the structure of the ViberUnsubscribedRequest object, triggered when a user unsubscribes. It inherits from ViberRequest and includes the event type and the unique Viber user ID. ```APIDOC ViberUnsubscribedRequest object: Inherits from ViberRequest Properties: event_type: string (always equals to the value of EventType.UNSUBSCRIBED) user_id: string (Unique Viber user id) ViberUnsubscribedRequest (Simplified): get_user_id() => string ``` -------------------------------- ### ViberSeenRequest Object Definition Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the structure of the ViberSeenRequest object, indicating a message has been seen. It inherits from ViberRequest and includes the event type, message token, and the unique Viber user ID. ```APIDOC ViberSeenRequest object: Inherits from ViberRequest Properties: event_type: string (always equals to the value of EventType.SEEN) message_token: string (Unique ID of the message) user_id: string (Unique Viber user id) ViberSeenRequest (Simplified): message_token: string user_id: string ``` -------------------------------- ### ViberFailedRequest Object Definition Source: https://github.com/viber/viber-bot-python/blob/master/README.md Represents a `failed` event, indicating that a message failed to be delivered. It inherits from `ViberRequest` and includes the `message_token` of the failed message, the `user_id` of the intended recipient, and a `desc` property providing a failure description. ```APIDOC ViberFailedRequest object Inherits from ViberRequest event_type: string - always equals to the value of EventType.FAILED message_token: string - Unique ID of the message user_id: string - Unique Viber user id desc: string - Failure description Properties: message_token: string user_id: string desc: string ``` -------------------------------- ### Parse Raw Viber Request Data Source: https://github.com/viber/viber-bot-python/blob/master/README.md Parses the raw POST data from an incoming Viber request into a structured `ViberRequest` object. This object provides easy access to event details, sender information, and message content. It takes the raw request data as input and returns a `ViberRequest` object. ```APIDOC Api.parse_request(request_data) request_data: string - the post data from request Returns: ViberRequest object. ``` ```Python viber_request = viber.parse_request(request.get_data()) ``` -------------------------------- ### ViberDeliveredRequest Object Definition Source: https://github.com/viber/viber-bot-python/blob/master/README.md Represents a `delivered` event, indicating that a message has been successfully delivered to the recipient's device. It inherits from `ViberRequest` and includes the `message_token` of the delivered message and the `user_id` of the recipient. ```APIDOC ViberDeliveredRequest object Inherits from ViberRequest event_type: string - always equals to the value of EventType.DELIVERED message_token: string - Unique ID of the message user_id: string - Unique Viber user id Properties: message_token: string user_id: string ``` -------------------------------- ### ViberMessageRequest Object Definition Source: https://github.com/viber/viber-bot-python/blob/master/README.md Defines the structure of the ViberMessageRequest object, which is triggered when a message is received. It inherits from ViberRequest and includes details about the event type, message token, message content, and sender profile. ```APIDOC ViberMessageRequest object: Inherits from ViberRequest Properties: event_type: string (always equals to the value of EventType.MESSAGE) message_token: string (Unique ID of the message) message: Message object sender: UserProfile object (the user started the conversation) ViberMessageRequest (Simplified): message_token: string message: Message sender: UserProfile ``` -------------------------------- ### Post Messages to a Viber Public Account Source: https://github.com/viber/viber-bot-python/blob/master/README.md Sends one or more `Message` objects from a specified sender to a Viber Public Account. This method is used for sending messages on behalf of a user to a public account. It requires the sender's Viber user ID and a list of `Message` objects, returning a list of message tokens for the sent messages. ```APIDOC Api.post_messages_to_public_account(sender, messages) sender: string - Viber user id messages: list - list of Message objects Returns: list - of message tokens of the messages sent. ``` ```Python tokens = viber.post_messages_to_public_account(sender=viber_request.get_sender().get_id(), messages=[TextMessage(text="sample message")]) ``` -------------------------------- ### Send Messages to a Viber User Source: https://github.com/viber/viber-bot-python/blob/master/README.md Sends one or more `Message` objects to a specific Viber user ID. This function is used for direct messaging to individual users. It requires the recipient's Viber user ID and a list of `Message` objects, returning a list of message tokens for the sent messages. ```APIDOC Api.send_messages(to, messages) to: string - Viber user id messages: list - list of Message objects Returns: list - of message tokens of the messages sent. ``` ```Python tokens = viber.send_messages(to=viber_request.get_sender().get_id(), messages=[TextMessage(text="sample message")]) ``` -------------------------------- ### Check Viber User Online Status Source: https://github.com/viber/viber-bot-python/blob/master/README.md Retrieves the online status for a list of Viber user IDs. This allows checking if specific users are currently active on Viber. It takes an array of Viber user IDs and returns a dictionary mapping user IDs to their online status. ```APIDOC Api.get_online(viber_user_ids) viber_user_ids: array of strings - Array of Viber user ids Returns: dictionary of users. ``` ```Python users = Api.get_online(["user1id", "user2id"]) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.