Package: aioviberbot
Viber Python Bot Async APIThis is async version ofviberbotpackage. Fully compatible with sync package version.
Use this library to develop a bot for Viber platform.The library is available onGitHubas well as a package onPyPI.This package can be imported using pip by adding the following to yourrequirements.txt:aioviberbot==0.5.0LicenseThis library is released under the terms of the Apache 2.0 license. SeeLicensefor more information.Library Prerequisitespython >= 3.7.0An Active Viber account on a platform which supports Public Accounts/ bots (iOS/Android). This account will automatically be set as the account administrator during the account creation process.Active Public Account/bot - Create an accounthere.Account authentication token - unique account identifier used to validate your account in all API requests. Once your account is created your authentication token will appear in the account’s “edit info” screen (for admins only). Each request posted to Viber by the account will need to contain the token.Webhook - Please use a server endpoint URL that supports HTTPS. If you deploy on your own custom server, you'll need a trusted (ca.pem) certificate, not self-signed. Read ourblog poston how to test your bot locally.ContributingIf you think that there's a bug or there's anything else needed to be changed and you want to change it yourself, you can always create a new Pull request.Please make sure that your change doesn't break anything and all the unit tests passes.Also, please make sure that the current tests cover your change, if not please add tests.We are using pytest, so if you want to run the tests from the commandline just follow the relevant steps after cloning the repo and creating your branch:# installing the dependencies:  
python setup.py develop

# run the unit tests
pytest tests/Let's get started!InstallingCreating a basic Viber bot is simple:Install the library with pippip install aioviberbotImportaioviberbot.apilibrary to your projectCreate a Public Account or bot and use the API key fromhttps://developers.viber.comConfigure your bot as described in the documentation belowStart your web serverCallset_webhook(url)with your web server urlA simple Echo BotFirstly, let's import and configure our botfromaioviberbotimportApifromaioviberbot.api.bot_configurationimportBotConfigurationbot_configuration=BotConfiguration(name='PythonSampleBot',avatar='http://viber.com/avatar.jpg',auth_token='YOUR_AUTH_TOKEN_HERE',)viber=Api(bot_configuration)Create an HTTPS serverNext thing you should do is starting a https server.
and yes, as we said in the prerequisites it has to be https server. Create a server however you like, for example withaiohttp:fromaiohttpimportwebasyncdefwebhook(request:web.Request)->web.Response:request_data=awaitrequest.read()logger.debug('Received request. Post data:%s',request_data)# handle the request herereturnweb.json_response({'ok':True})if__name__=='__main__':app=web.Application()app.router.add_route('POST','/webhook',webhook),web.run_app(app)Setting a webhookAfter the server is up and running you can set a webhook.
Viber will push messages sent to this URL. web server should be internet-facing.awaitviber.set_webhook('https://mybotwebserver.com:443/')LoggingThis library uses the standard python logger. If you want to see its logs you can configure the logger:logger=logging.getLogger('aioviberbot')logger.setLevel(logging.DEBUG)handler=logging.StreamHandler()formatter=logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')handler.setFormatter(formatter)logger.addHandler(handler)Do you supply a basic types of messages?Well, funny you ask. Yes we do. All the Message types are located inaioviberbot.api.messagespackage. Here's some examples:fromaioviberbot.api.messagesimport(TextMessage,ContactMessage,PictureMessage,VideoMessage,)fromaioviberbot.api.messages.data_types.contactimportContact# creation of text messagetext_message=TextMessage(text='sample text message!')# creation of contact messagecontact=Contact(name='Viber user',phone_number='0123456789')contact_message=ContactMessage(contact=contact)# creation of picture messagepicture_message=PictureMessage(text='Check this',media='http://site.com/img.jpg')# creation of video messagevideo_message=VideoMessage(media='http://mediaserver.com/video.mp4',size=4324)Have you noticed how we created theTextMessage? There's all bunch of message types you should get familiar with.Text MessageUrl MessageContact MessagePicture MessageVideo MessageLocation MessageSticker MessageRich Media MessageKeyboard MessageCreating them is easy! Every message object has it's own unique constructor corresponding to it's API implementation, click on them to see it!
Check out the full API documentation for more advanced uses.Let's add it all up and reply with a message!fromaiohttpimportwebfromaioviberbotimportApifromaioviberbot.api.bot_configurationimportBotConfigurationfromaioviberbot.api.messages.text_messageimportTextMessagefromaioviberbot.api.viber_requestsimportViberConversationStartedRequestfromaioviberbot.api.viber_requestsimportViberMessageRequestfromaioviberbot.api.viber_requestsimportViberSubscribedRequestviber=Api(BotConfiguration(name='PythonSampleBot',avatar='http://viber.com/avatar.jpg',auth_token='YOUR_AUTH_TOKEN_HERE'))asyncdefwebhook(request:web.Request)->web.Response:request_data=awaitrequest.read()signature=request.headers.get('X-Viber-Content-Signature')ifnotviber.verify_signature(request_data,signature):raiseweb.HTTPForbiddenviber_request=viber.parse_request(request_data)ifisinstance(viber_request,ViberMessageRequest):# echo messageawaitviber.send_messages(viber_request.sender.id,[viber_request.message],)elifisinstance(viber_request,ViberSubscribedRequest):awaitviber.send_messages(viber_request.user.id,[TextMessage(text='Thanks for subscribing!')],)elifisinstance(viber_request,ViberConversationStartedRequest):awaitviber.send_messages(viber_request.user.id,[TextMessage(text='Thanks for starting conversation!')],)returnweb.json_response({'ok':True})asyncdefset_webhook_signal(app:web.Application):awaitviber.set_webhook('https://mybotwebserver.com/webhhok')if__name__=='__main__':app=web.Application()app.on_startup.append(set_webhook_signal)app.router.add_route('POST','/webhook',webhook),web.run_app(app)As you can see there's a bunch ofRequesttypes here's a list of them.Viber APIApi classfrom aioviberbot import ApiApiinit(bot_configuration, client_session).set_webhook(url, webhook_events)⇒List of registered event_types.unset_webhook()⇒None.get_account_info()⇒object.verify_signature(request_data, signature)⇒boolean.parse_request(request_data)⇒ViberRequest.send_messages(to, messages)⇒list of message tokens sent.broadcast_messages(broadcast_list, messages)⇒list of message tokens sent.get_online(viber_user_ids)⇒dictionary of users status.get_user_details(viber_user_id)⇒dictionary of user's data.post_messages_to_public_account(to, messages)⇒list of message tokens sentNew Api()ParamTypeDescriptionbot_configurationobjectBotConfigurationclient_sessionobjectOptionalaiohttp.ClientSession, pass if you want to use your own session for api requestsApi.set_webhook(url)ParamTypeDescriptionurlstringYour web server urlwebhook_eventslistoptional list of subscribed eventsReturnsList of registered event_types.event_types=awaitviber.set_webhook('https://example.com/webhook')Api.unset_webhook()ReturnsNone.awaitviber.unset_webhook()Api.get_account_info()Returns anobjectwith the following JSON.account_info=awaitviber.get_account_info()Api.verify_signature(request_data, signature)ParamTypeDescriptionrequest_datastringthe post data from requestsignaturestringsent as headerX-Viber-Content-SignatureReturns abooleansuggesting if the signature is valid.ifnotviber.verify_signature(awaitrequest.read(),request.headers.get('X-Viber-Content-Signature')):raiseweb.HTTPForbiddenApi.parse_request(request_data)ParamTypeDescriptionrequest_datastringthe post data from requestReturns aViberRequestobject.There's a list ofViberRequest objectsviber_request=viber.parse_request(awaitrequest.read())Api.send_messages(to, messages)ParamTypeDescriptiontostringViber user idmessageslistlist ofMessageobjectsReturnslistof message tokens of the messages sent.tokens=awaitviber.send_messages(to=viber_request.sender.id,messages=[TextMessage(text='sample message')],)Api.broadcast_messages(broadcast_list, messages)ParamTypeDescriptionbroadcast_listlistlist of Viber user idsmessageslistlist ofMessageobjectsReturnslistof message tokens of the messages sent.tokens=awaitviber.broadcast_messages(broadcast_list=["ABB102akPCRKFaqxWnafEIA==","ABB102akPCRKFaqxWna111==","ABB102akPCRKFaqxWnaf222==",],messages=[TextMessage(text='sample message')],)Api.post_messages_to_public_account(to, messages)ParamTypeDescriptionsenderstringViber user idmessageslistlist ofMessageobjectsReturnslistof message tokens of the messages sent.tokens=awaitviber.post_messages_to_public_account(sender=viber_request.sender.id,messages=[TextMessage(text='sample message')],)Api.get_online(viber_user_ids)ParamTypeDescriptionviber_user_idsarray of stringsArray of Viber user idsReturns adictionary of users.users=awaitviber.get_online(['user1id','user2id'])Api.get_user_details(viber_user_id)ParamTypeDescriptionviber_user_idsstringViber user idTheget_user_detailsfunction 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.user_data=awaitviber.get_user_details('userId')Request objectParamTypeNotesevent_typestringaccording toEventTypesenumtimestamplongEpoch of request timeViberRequest.event_type ⇒string.timestamp ⇒longViberConversationStartedRequest objectInherits fromViberRequestConversation 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 adeep link.This event isnotconsidered 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. Seesending a welcome messagebelow for more information.ParamTypeNotesevent_typestringalways equals to the value ofEventType.CONVERSATION_STARTEDmessage_tokenstringUnique ID of the messagetypestringThe specific type ofconversation_startedevent.contextstringAny additional parameters added to the deep link used to access the conversation passed as a stringuserUserProfilethe user started the conversationUserProfilesubscribedbooleanIndicates whether a user is already subscribedViberConversationStartedRequestmessage_token ⇒stringtype ⇒stringcontext ⇒stringuser ⇒UserProfileViberDeliveredRequest objectInherits fromViberRequestParamTypeNotesevent_typestringalways equals to the value ofEventType.DELIVEREDmessage_tokenstringUnique ID of the messageuser_idstringUnique Viber user idViberDeliveredRequestmessage_token ⇒stringuser_id ⇒stringViberFailedRequest objectInherits fromViberRequestParamTypeNotesevent_typestringalways equals to the value ofEventType.FAILEDmessage_tokenstringUnique ID of the messageuser_idstringUnique Viber user iddescstringFailure descriptionViberFailedRequestmessage_token ⇒stringuser_id ⇒stringdesc ⇒stringViberMessageRequest objectInherits fromViberRequestParamTypeNotesevent_typestringalways equals to the value ofEventType.MESSAGEmessage_tokenstringUnique ID of the messagemessageMessageMessageobjectsenderUserProfilethe user started the conversationUserProfileViberMessageRequestmessage_token ⇒stringmessage ⇒Messagesender ⇒UserProfileViberSeenRequest objectInherits fromViberRequestParamTypeNotesevent_typestringalways equals to the value ofEventType.SEENmessage_tokenstringUnique ID of the messageuser_idstringUnique Viber user idViberSeenRequestmessage_token ⇒stringuser_id ⇒stringViberSubscribedRequest objectInherits fromViberRequestParamTypeNotesevent_typestringalways equals to the value ofEventType.SUBSCRIBEDuserUserProfilethe user started the conversationUserProfileViberSubscribedRequestuser ⇒UserProfileViberUnsubscribedRequest objectInherits fromViberRequestParamTypeNotesevent_typestringalways equals to the value ofEventType.UNSUBSCRIBEDuser_idstringUnique Viber user idViberUnsubscribedRequestget_user_id() ⇒stringUserProfile objectParamTypeNotesidstring---namestring---avatarstringAvatar URLcountrystringcurrently set inCONVERSATION_STARTEDevent onlylanguagestringcurrently set inCONVERSATION_STARTEDevent onlyMessage ObjectCommon Members forMessageinterface:ParamTypeDescriptiontimestamplongEpoch timekeyboardJSONkeyboard JSONtrackingDataJSONJSON Tracking Data from Viber ClientCommon Constructor ArgumentsMessageinterface:ParamTypeDescriptionoptionalKeyboardJSONWriting Custom KeyboardsoptionalTrackingDataJSONData to be saved on Viber Client device, and sent back each time message is receivedTextMessage objectMemberTypetextstringmessage=TextMessage(text='my text message')URLMessage objectMemberTypeDescriptionmediastringURL stringmessage=URLMessage(media='http://my.siteurl.com')ContactMessage objectMemberTypecontactContactfromaioviberbot.api.messages.data_types.contactimportContactcontact=Contact(name='Viber user',phone_number='+0015648979',avatar='http://link.to.avatar')contact_message=ContactMessage(contact=contact)PictureMessage objectMemberTypeDescriptionmediastringurl of the message (jpeg only)textstringthumbnailstringmessage=PictureMessage(media='http://www.thehindubusinessline.com/multimedia/dynamic/01458/viber_logo_JPG_1458024f.jpg',text='Viber logo')VideoMessage objectMemberTypeDescriptionmediastringurl of the videosizeintthumbnailstringdurationintmessage=VideoMessage(media='http://site.com/video.mp4',size=21499)LocationMessage objectMemberTypelocationLocationfromaioviberbot.api.messages.data_types.locationimportLocationlocation=Location(lat=0.0,lon=0.0)location_message=LocationMessage(location=location)StickerMessage objectMemberTypesticker_idintmessage=StickerMessage(sticker_id=40100)FileMessage objectMemberTypemediastringsizelongfile_namestringmessage=FileMessage(media=url,size=size_in_bytes,file_name=file_name)RichMediaMessage objectMemberTyperich_mediastring(JSON)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": "<b>example</b> button","TextOpacity": 10,"TextSize": "regular"}]}"""SAMPLE_ALT_TEXT='upgrade now!'message=RichMediaMessage(rich_media=SAMPLE_RICH_MEDIA,alt_text=SAMPLE_ALT_TEXT)KeyboardMessage objectMemberTypekeyboardJSONtracking_dataJSONmessage=KeyboardMessage(tracking_data=tracking_data,keyboard=keyboard)Sending a welcome messageThe Viber API allows sending messages to users only after they subscribe to the account. However, Viber will allow the account to send one “welcome message” to a user as the user opens the conversation, before the user subscribes.The welcome message will be sent as a response to aconversation_startedcallback, which will be received from Viber once the user opens the conversation with the account. To learn more about this event and when is it triggered seeConversation startedin the callbacks section.Welcome message flowSending a welcome message will be done according to the following flow:User opens 1-on-1 conversation with account.Viber server sendconversation_startedeven to PA’s webhook.The account receives theconversation_startedand responds with an HTTP response which includes the welcome message as the response body.The welcome message will be a JSON constructed according to the send_message requests structure, but without thereceiverparameter. An example welcome message would look like this:asyncdefwebhook(request:web.Request)->web.Response:request_data=awaitrequest.read()viber_request=viber.parse_request(request_data)ifisinstance(viber_request,ViberConversationStartedRequest):awaitviber.send_messages(viber_request.user.id,[TextMessage(text='Welcome!')],)returnweb.json_response({'ok':True})CommunityJoin the conversation onGitter.