Last active
December 30, 2017 07:42
-
-
Save paulwinex/269e15745497b9f97c3429a6b192647d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from bot_config import * | |
import requests | |
import logging | |
logger = logging.getLogger(__name__) | |
url = 'https://api.telegram.org/bot{}/{}' | |
def _send_text(text, c_id=None, parse_mode='Markdown'): | |
method = 'sendMessage' | |
send_url = url.format(botToken, method) | |
data = {'chat_id': c_id or chat_id, 'text': text} | |
if parse_mode: | |
data['parse_mode'] = 'Markdown' | |
if fake_send: | |
logger.info('Fake Send text %s' % data) | |
return type('fakerequests', (object,), {'status_code': 200, 'content': '', 'json': lambda: {}}) | |
res = requests.post(send_url, json=data) | |
if not res.status_code == 200: | |
try: | |
if res.json().get('description') == "Bad Request: chat not found": | |
logger.error("Bad Request: chat not found: %s" % c_id) | |
else: | |
_send_log_error('Error sending text (code %s):\n`%s` \n\n`%s`' % (res.status_code, pformat(str(res.content)), pformat(data))) | |
except: | |
_send_log_error('Error sending text (code %s):\n`%s` \n\n`%s`' % ( | |
res.status_code, pformat(str(res.content)), pformat(data))) | |
return res | |
def _send_simple_text(text, c_id=None): | |
return _send_text(text, c_id, False) | |
def _send_photo(img, text): | |
method = 'sendPhoto' | |
send_url = url.format(botToken, method) | |
data = {'chat_id': chat_id, 'caption': text, 'photo': img} | |
if fake_send: | |
logger.info('Fake Send image %s' % data) | |
return type('fakerequests', (object,), {'status_code': 200, 'content': '', 'json': lambda: {}}) | |
res = requests.post(send_url, json=data) | |
if not res.status_code == 200: | |
_send_log_error('Error sending image (code %s):\n`%s` \n\n`%s`' % (res.status_code, pformat(str(res.content)), pformat(data))) | |
return res | |
def _send_log_error(text): | |
logger.error(text) | |
_send_text(text, debug_chat_id) | |
def _send_log(text): | |
logger.debug(text) | |
_send_text(text, debug_chat_id) | |
def _escape_markdown(text): | |
chars = ['_', '*'] | |
for c in chars: | |
text = text.replace(c, '\\'+c) | |
return text | |
### EXAMPLE ### | |
def send_example(obj): | |
text = '{ico} / *{version}* / _{date}_ \n{text}'.format( | |
ico='⭐️', | |
version=obj.version, | |
date=datetime.fromtimestamp(float(obj.date)).strftime('%a. %B %d, %Y'), | |
text=_escape_markdown(obj.text) | |
).strip() | |
r = _send_text(text) | |
if r.status_code == 200: | |
return True | |
return False | |
invis_char = '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment