Repository navigation
Expand file tree
/
Copy pathbot_python.py
More file actions
49 lines (47 loc) · 2.64 KB
/
Copy pathbot_python.py
File metadata and controls
49 lines (47 loc) · 2.64 KB
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
"""Independent standard-library example based on public Adsun docs."""
import json, os, urllib.parse, urllib.request, urllib.error
def message_payload(ad, chat_id):
body = {'chat_id': chat_id, 'parse_mode': 'HTML', 'protect_content': True,
'reply_markup': {'inline_keyboard': [
[{'text': ad['button_name'], 'url': ad['click_url']}],
[{'text': ad['button_reward_name'], 'url': ad['reward_url']}]]}}
if ad.get('image_url'):
body.update(photo=ad['image_url'], caption=ad['text_html'])
return 'sendPhoto', body
body['text'] = ad['text_html']
return 'sendMessage', body
def send_ad(chat_id, user_id, language='en'):
token = os.environ['ADSUN_TOKEN']
bot_token = os.environ['TELEGRAM_BOT_TOKEN']
block_id = os.environ['ADSUN_BLOCK_ID']
if not str(user_id).isdigit() or not block_id.isdigit():
raise ValueError('Numeric user and block IDs required')
params = urllib.parse.urlencode(dict(tgid=user_id, blockid=block_id, language=language, token=token))
try:
with urllib.request.urlopen('https://api.adsun.io/advbot?' + params, timeout=15) as response:
if response.status == 204:
return {'sent': False, 'reason': 'no-ad'}
ad = json.load(response)
except urllib.error.HTTPError as error:
raise RuntimeError('Adsun request failed: HTTP ' + str(error.code)) from None
except urllib.error.URLError:
raise RuntimeError('Adsun network request failed') from None
for key in ('text_html', 'button_name', 'click_url', 'button_reward_name', 'reward_url'):
if not isinstance(ad.get(key), str) or not ad[key]:
raise ValueError('Missing ad field: ' + key)
for key in ('click_url', 'reward_url', 'image_url'):
if ad.get(key) and urllib.parse.urlparse(ad[key]).scheme != 'https':
raise ValueError('Ad URLs must use HTTPS')
method, body = message_payload(ad, chat_id)
request = urllib.request.Request('https://api.telegram.org/bot' + bot_token + '/' + method,
data=json.dumps(body).encode(), headers={'Content-Type': 'application/json'})
try:
with urllib.request.urlopen(request, timeout=15) as response:
result = json.load(response)
except urllib.error.HTTPError as error:
raise RuntimeError('Telegram request failed: HTTP ' + str(error.code)) from None
except urllib.error.URLError:
raise RuntimeError('Telegram network request failed') from None
if not result.get('ok'):
raise RuntimeError('Telegram rejected the message')
return {'sent': True, 'message_id': result['result']['message_id']}