Вайбер бот на питоне

Viber Python Bot Async API

This is async version of viberbot package. Fully compatible with sync package version. Use this library to develop a bot for Viber platform.

The library is available on GitHub as well as a package on PyPI.

This package can be imported using pip by adding the following to your requirements.txt :

This library is released under the terms of the Apache 2.0 license. See License for more information.

Library Prerequisites

  1. python >= 3.7.0
  2. An 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.
  3. Active Public Account/bot — Create an account here.
  4. 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.
  5. 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 our blog post on how to test your bot locally.
Читайте также:  Глобальные стили

Contributing

If 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!

Installing

Creating a basic Viber bot is simple:

  1. Install the library with pip pip install aioviberbot
  2. Import aioviberbot.api library to your project
  3. Create a Public Account or bot and use the API key from https://developers.viber.com
  4. Configure your bot as described in the documentation below
  5. Start your web server
  6. Call set_webhook(url) with your web server url

A simple Echo Bot

Firstly, let’s import and configure our bot

Next 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 with aiohttp :

After 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.

This library uses the standard python logger. If you want to see its logs you can configure the logger:

Well, funny you ask. Yes we do. All the Message types are located in aioviberbot.api.messages package. Here’s some examples:

    Have you noticed how we created the TextMessage ? There's all bunch of message types you should get familiar with.

Creating 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!

 As you can see there's a bunch of Request types here's a list of them.

Viber API

Api class

from aioviberbot import Api

  • Api
    • init(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 sent

    New Api()

    Param Type Description
    bot_configuration object BotConfiguration
    client_session object Optional aiohttp.ClientSession , pass if you want to use your own session for api requests

    Api.set_webhook(url)

    Param Type Description
    url string Your web server url
    webhook_events list optional list of subscribed events

    Returns List of registered event_types .

    Источник

    Viber Python Bot API

    Use this library to develop a bot for Viber platform. The library is available on GitHub as well as a package on PyPI.

    This package can be imported using pip by adding the following to your requirements.txt :

    Important note for bot developers: Viber’s bot platform is open and free for developers to create bots in our ecosystem. Once you’ve created your bot you are welcome to share it with your Viber contacts or promote it outside Viber on your website or social media channels. Please note that Viber is not responsible for promoting your bot.

    License

    This library is released under the terms of the Apache 2.0 license. See License for more information.

    Library Prerequisites

    1. python >= 2.7.0
    2. An Active Viber account on a platform which supports bots (iOS/Android). This account will automatically be set as the account administrator during the account creation process.
    3. .Active bot — Create an account here.
    4. 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.
    5. 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 our blog post on how to test your bot locally.

    Let’s get started!

    Installing

    Creating a basic Viber bot is simple:

    1. Install the library with pip pip install viberbot
    2. Import viberbot.api library to your project
    3. Create a bot and use the authentication token from https://partners.viber.com/account/create-bot-account
    4. Configure your bot as described in the documentation below
    5. Start your web server
    6. Call set_webhook(url) with your web server url

    A simple Echo Bot

    Firstly, let’s import and configure our bot

    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)

    Create an HTTPS server

    Next 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 with Flask :

    from flask import Flask, request, Response app = Flask(__name__) @app.route('/incoming', methods=['POST']) def incoming(): logger.debug("received request. post data: ".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)

    Setting a webhook

    After 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.

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

    Logging

    This library uses the standard python logger. If you want to see its logs you can configure the logger:

    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)

    Do you supply a basic types of messages?

    Well, funny you ask. Yes we do. All the Message types are located in viberbot.api.messages package. Here’s some examples:

    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)

    Have you noticed how we created the TextMessage ? There’s a all bunch of message types you should get familiar with.

    Creating 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!

    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: ".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: ".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)

    As you can see there’s a bunch of Request types here’s a list of them.

    Viber API

    Api class

    • Api
      • init(bot_configuration)
      • .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
      • .get_online(viber_user_ids) ⇒ dictionary of users status
      • .get_user_details(viber_user_id) ⇒ dictionary of user’s data

      Источник

Оцените статью