2016-01-23 12:24:34 +01:00
|
|
|
#!/usr/bin/env python
|
|
|
|
|
|
|
|
import json
|
2016-01-23 14:58:01 +01:00
|
|
|
import logging
|
|
|
|
from telegram import NullHandler
|
2016-01-23 12:24:34 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
from urllib.request import urlopen, Request
|
|
|
|
from urllib.parse import quote
|
2016-01-23 13:21:13 +01:00
|
|
|
from urllib.error import URLError, HTTPError
|
2016-01-23 12:24:34 +01:00
|
|
|
except ImportError:
|
|
|
|
from urllib2 import urlopen, Request
|
|
|
|
from urllib import quote
|
2016-01-23 13:21:13 +01:00
|
|
|
from urllib2 import URLError, HTTPError
|
2016-01-23 12:24:34 +01:00
|
|
|
|
2016-01-23 14:58:01 +01:00
|
|
|
H = NullHandler()
|
|
|
|
logging.getLogger(__name__).addHandler(H)
|
|
|
|
|
2016-01-23 12:24:34 +01:00
|
|
|
|
|
|
|
class Botan(object):
|
2016-01-23 14:59:53 +01:00
|
|
|
"""This class helps to send incoming events in your botan analytics account.
|
|
|
|
See more: https://github.com/botanio/sdk#botan-sdk"""
|
|
|
|
|
2016-01-23 12:24:34 +01:00
|
|
|
token = ''
|
2016-01-23 14:59:53 +01:00
|
|
|
url_template = 'https://api.botan.io/track?token={token}' \
|
|
|
|
'&uid={uid}&name={name}&src=python-telegram-bot'
|
2016-01-23 12:24:34 +01:00
|
|
|
|
|
|
|
def __init__(self, token):
|
|
|
|
self.token = token
|
2016-01-23 14:58:01 +01:00
|
|
|
self.logger = logging.getLogger(__name__)
|
2016-01-23 12:24:34 +01:00
|
|
|
|
|
|
|
def track(self, message, event_name='event'):
|
|
|
|
try:
|
|
|
|
uid = message.chat_id
|
|
|
|
except AttributeError:
|
2016-01-23 14:58:01 +01:00
|
|
|
self.logger.warn('No chat_id in message')
|
2016-01-23 12:24:34 +01:00
|
|
|
return False
|
|
|
|
data = json.dumps(message.__dict__)
|
|
|
|
try:
|
2016-01-23 13:14:17 +01:00
|
|
|
url = self.url_template.format(token=str(self.token),
|
|
|
|
uid=str(uid),
|
|
|
|
name=quote(event_name))
|
2016-01-23 12:24:34 +01:00
|
|
|
request = Request(url,
|
|
|
|
data=data,
|
|
|
|
headers={'Content-Type': 'application/json'})
|
2016-01-23 17:44:40 +01:00
|
|
|
response = urlopen(request)
|
2016-01-23 12:24:34 +01:00
|
|
|
if response.getcode() != 200:
|
|
|
|
return False
|
|
|
|
return True
|
2016-01-23 13:21:13 +01:00
|
|
|
except HTTPError as error:
|
2016-01-23 14:58:01 +01:00
|
|
|
self.logger.warn('Botan track error ' +
|
2016-01-23 17:29:01 +01:00
|
|
|
str(error.code) + ':' + error.read())
|
2016-01-23 13:21:13 +01:00
|
|
|
return False
|
|
|
|
except URLError as error:
|
2016-01-23 14:58:01 +01:00
|
|
|
self.logger.warn('Botan track error ' + error.reason)
|
2016-01-23 12:24:34 +01:00
|
|
|
return False
|