-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtelegram.py
78 lines (65 loc) · 2.13 KB
/
telegram.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from urllib3 import PoolManager
from urllib3.exceptions import ProtocolError
# Initialize PoolManager
manager = PoolManager()
class TG:
"""
Class to handle our telegram sending
Has one attribute
-> api_key: A Telegram bot API key
Has various functions
-> send: sends a message to the given `function` on the telegram API
-> send_message: send(sendMessage)
-> send_chat_action: send(sendChatAction)
-> send_document: send(sendDocument)
"""
def __init__(self, api_key):
self.api_key = api_key
def send(self, function, data):
try:
return manager.request(
"POST",
f"https://api.telegram.org/bot{self.api_key}/{function}",
fields=data,
)
except ProtocolError as e:
print(e, e.__class__)
with open("extra-logs.txt", "a") as f:
f.write(str(data) + "\n\n\n")
def send_message(self, chat_id, message, parse_mode="HTML"):
data = {
"chat_id": chat_id,
"text": message,
"parse_mode": parse_mode,
}
return self.send("sendMessage", data)
def send_chat_action(self, chat_id, action):
data = {
"chat_id": chat_id,
"action": action,
}
return self.send("sendChatAction", data)
def send_document(
self,
chat_id,
caption,
file_name,
disable_notifications=False,
parse_mode="HTML",
):
data = {
"caption": caption,
"chat_id": chat_id,
"document": (file_name, open(file_name, "rb").read()),
"disable_notification": disable_notifications,
"parse_mode": parse_mode,
}
return self.send("sendDocument", data)
def send_image(self, chat_id, image_file, caption, disable_notifications=False):
data = {
"caption": caption,
"chat_id": chat_id,
"photo": (image_file, open(image_file, "rb").read()),
"disable_notification": disable_notifications,
}
return self.send("sendPhoto", data)