Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send message from Viber bot to subscribed user

I'm trying to send the message from the Viber bot to subscribed user. I can get the subscribed User ID, however when I send the message, I get 500 error.

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

app = Flask(__name__)

viber = Api(BotConfiguration(
    name='PythonSampleBot',
    avatar='http://www.clker.com/cliparts/3/m/v/Y/E/V/small-red-apple-hi.png',
    auth_token='xxx-xxx-xxx'
))


@app.route('/', methods=['POST'])
def incoming():
    user_id = viber.get_account_info()['members'][0]['id']
    print(user_id)
    viber.send_messages(user_id, [
        TextMessage(text="thanks for subscribing!!!!!")
    ])
    return Response(status=200)


if __name__ == "__main__":
    context = ('E:\\Docs\\learn_py\\viberbot\\cert.pem',
               'E:\\Docs\\learn_py\\viberbot\\key.pem')
    app.run(host='0.0.0.0', port=4443, debug=True, ssl_context=context)

Request message send code:

import json
import requests

webhook_url = 'https://xxx.xxx.xxx.xxx:4443'

requests.post(
    webhook_url, data=json.dumps({"text": "Hello World"}),
    headers={'Content-Type': 'application/json'},
    verify='E:\\Docs\\learn_py\\viberbot\\cert.pem'
)

Error message:

Cfklv9HOJ6bXZcHMaTl9Gw==
192.168.1.1 - - [15/Mar/2019 08:44:02] "POST / HTTP/1.1" 500 - Traceback (most recent call last):   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)   File "E:\Docs\learn_py\viberbot\app.py", line 21, in incoming
    TextMessage(text="thanks for subscribing!!!!!")   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\viberbot\api\api.py", line 72, in send_messages
    to, self._bot_configuration.name, self._bot_configuration.avatar, message, chat_id)   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\viberbot\api\message_sender.py", line 27, in send_message
    return self._post_request(BOT_API_ENDPOINT.SEND_MESSAGE, payload)   File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\viberbot\api\message_sender.py", line 53, in _post_request
    raise Exception(u"failed with status: {0}, message: {1}".format(result['status'], result['status_message'])) Exception: failed with status: 10, message: webhookNotSet  * Detected change in 'E:\\Docs\\learn_py\\viberbot\\app.py', reloading

UPDATE: As suggested by mingaleg I've added viber.set_webhook('https://xxx.xxx.xxx.xxx:yyyy') to the incoming() function and now getting another error:

Exception: failed with status: 1, message: Result[HttpRequest[POST / HTTP/1.1]@2c67393 > HttpResponse[null 0 null]@72391ae] javax.net.ssl.SSLHandshakeException: General SSLEngine problem

The certificate was generated as suggested in this answer:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

like image 454
Dmitrij Kultasev Avatar asked Mar 15 '19 06:03

Dmitrij Kultasev


People also ask

How do I send a message to a Viber user?

The send_message API allows accounts to send messages to Viber users who subscribe to the account. Sending a message to a user will be possible only after the user has subscribed to the bot. (see subscribed callback for additional information). You can share your bot with the users via a deeplink.

How do you advertise a chatbot on Viber?

Stand out from the crowd After release, contact the Viber team to make your bot visible and searchable. Users will find it by typing its name on the Chats screen. Promote your chatbot on your own marketing channels and take advantage of Viber ads and sticker packs to attract new users.

How does sub-subscribing to a Bot work?

Subscribing can take place if the user sends a message to the bot - when a user sends its first message to a bot the user will be automatically subscribed to the bot. Sending the first message will not trigger a subscribe callback, only a message callback (see receive message from user section).

How to get the details of a specific Viber user?

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.


2 Answers

Since you have an webhookNotSet error message you should configure your bot to have one:

...
viber = Api(BotConfiguration(
    name='PythonSampleBot',
    avatar='http://www.clker.com/cliparts/3/m/v/Y/E/V/small-red-apple-hi.png',
    auth_token='xxx-xxx-xxx'
))
viber.set_webhook(webhook_url)
...

webhook_url should be the one your flask server is reachable by.

like image 192
mingaleg Avatar answered Nov 04 '22 16:11

mingaleg


You aren't supposed to use self-signed certificate.
I can recommend Let's Encrypt service as convenient and free way to get an SSL certificate for your domain.

Or you can use ngrok for local development or deploy it to Heroku (it gives HTTPS domain for free).

like image 24
wowkin2 Avatar answered Nov 04 '22 17:11

wowkin2