forked from Viber/viber-bot-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample_bot.py
62 lines (52 loc) · 2.1 KB
/
sample_bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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 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
import time
import logging
import sched
import threading
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)
app = Flask(__name__)
viber = Api(BotConfiguration(
name='PythonSampleBot',
avatar='http://viber.com/avatar.jpg',
auth_token='YOUR_AUTH_TOKEN_HERE'
))
@app.route('/', methods=['POST'])
def incoming():
logger.debug("received request. post data: {0}".format(request.get_data()))
viber_request = viber.parse_request(request.get_data().decode('utf8'))
if isinstance(viber_request, ViberMessageRequest):
message = viber_request.message
viber.send_messages(viber_request.sender.id, [
message
])
elif isinstance(viber_request, ViberConversationStartedRequest) \
or isinstance(viber_request, ViberSubscribedRequest) \
or isinstance(viber_request, ViberUnsubscribedRequest):
viber.send_messages(viber_request.sender.id, [
TextMessage(None, None, viber_request.get_event_type())
])
elif isinstance(viber_request, ViberFailedRequest):
logger.warn("client failed receiving message. failure: {0}".format(viber_request))
return Response(status=200)
def set_webhook(viber):
viber.set_webhook('https://mybotwebserver.com:8443/')
if __name__ == "__main__":
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(5, 1, set_webhook, (viber,))
t = threading.Thread(target=scheduler.run)
t.start()
context = ('server.crt', 'server.key')
app.run(host='0.0.0.0', port=8443, debug=True, ssl_context=context)