-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram_bot.py
55 lines (47 loc) · 1.92 KB
/
telegram_bot.py
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
50
51
52
53
54
55
import requests
import time
import json
class TelegramBot:
CONNECTION_LOST_TIMEOUT = 60
def __init__(self, token, proxies=None):
self.token = token
self.url = f"https://api.telegram.org/bot{self.token}/"
self.update_id = 0
self.proxies = proxies
self._check_token()
def _check_token(self):
try:
r = requests.get(self.url + "getMe", proxies=self.proxies)
except:
raise ValueError("Can't connect")
if r.json()['ok'] == True:
return True
else:
raise ValueError("Invalid token!")
def get_messages(self):
out = []
try:
r = requests.get(f"{self.url}getUpdates?offset={self.update_id}", timeout=self.CONNECTION_LOST_TIMEOUT, proxies=self.proxies).json()
except requests.exceptions.RequestException as e:
print(f"{int(time.time())} | Error while getting messages:", e)
return out
except json.decoder.JSONDecodeError as e:
print(f"{int(time.time())} | Error while getting messages:", e)
return out
if r['ok'] and 'result' in r.keys():
for i in r['result']:
if 'message' in i.keys() and 'text' in i['message'].keys():
out.append(i['message'])
if i['update_id'] >= self.update_id:
self.update_id = i['update_id']+1
return out
def send_message(self, chat_id, text, parse_mode=''):
try:
r = requests.post(f"{self.url}sendMessage",
data={'chat_id': chat_id, 'text': text, 'parse_mode': parse_mode},
timeout=self.CONNECTION_LOST_TIMEOUT,
proxies=self.proxies)
except requests.exceptions.RequestException as e:
print(f"{int(time.time())} | Error while sending message:", e)
return None
return r