python-telegram-bot/telegram/contrib/botan.py

44 lines
1.5 KiB
Python
Raw Normal View History

2016-01-23 14:58:01 +01:00
import logging
2016-01-23 12:24:34 +01:00
2016-05-24 23:40:09 +02:00
from future.moves.urllib.parse import quote
from future.moves.urllib.error import HTTPError, URLError
from future.moves.urllib.request import urlopen, Request
2016-01-23 12:24:34 +01:00
logging.getLogger(__name__).addHandler(logging.NullHandler())
2016-01-23 14:58:01 +01:00
2016-01-23 12:24:34 +01:00
class Botan(object):
2016-05-24 23:40:09 +02:00
"""This class helps to send incoming events to your botan analytics account.
See more: https://github.com/botanio/sdk#botan-sdk
"""
2016-01-23 12:24:34 +01:00
token = ''
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
2016-02-07 14:46:36 +01:00
data = message.to_json()
2016-01-23 12:24:34 +01:00
try:
2016-08-26 11:17:05 +02:00
url = self.url_template.format(
token=str(self.token), uid=str(uid), name=quote(event_name))
request = Request(
url, data=data.encode(), headers={'Content-Type': 'application/json'})
urlopen(request)
2016-01-23 12:24:34 +01:00
return True
2016-01-23 13:21:13 +01:00
except HTTPError as error:
2016-05-15 03:46:40 +02:00
self.logger.warn('Botan track error ' + str(error.code) + ':' + error.read().decode(
'utf-8'))
2016-01-23 13:21:13 +01:00
return False
except URLError as error:
self.logger.warn('Botan track error ' + str(error.reason))
2016-01-23 12:24:34 +01:00
return False