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

54 lines
1.7 KiB
Python
Raw Normal View History

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):
token = ''
2016-01-23 13:14:17 +01:00
url_template = 'https://api.botan.io/track?' \
'token={token}&uid={uid}&name={name}'
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'})
response = urlopen(request, json.dumps(data))
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 ' +
str(error.code) + ':' + error.reason)
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