-
Notifications
You must be signed in to change notification settings - Fork 4
/
telegram.py
73 lines (59 loc) · 1.81 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
# -*-coding:utf8;-*-
import os
import requests
import io
import base64
"""
library to interact with telegram bot api
references:
- https://telegram-bot-sdk.readme.io/reference/sendmessage
- https://djangostars.com/blog/how-to-create-and-deploy-a-telegram-bot/
"""
token = os.environ.get("TG_BOT_TOKEN")
BOT_URL = f"https://api.telegram.org/bot{token}/"
def get_chat_id(data):
chat_id = data["message"]["chat"]["id"]
return chat_id
def get_message(data):
message_text = data["message"]["text"]
return message_text
def get_message_id(data):
message_id = data["message"]["message_id"]
return message_id
def send_message(
text,
chat_id,
parse_mode=False,
disable_web_page_preview=False,
disable_notification=False,
reply_to_message_id=False,
reply_markup=False,
):
message_url = BOT_URL + "sendMessage"
json_data = {
"chat_id": chat_id,
"text": text,
"disable_web_page_preview": disable_web_page_preview,
"disable_notification": disable_notification,
}
if parse_mode:
json_data["parse_mode"] = parse_mode
if reply_to_message_id:
json_data["reply_to_message_id"] = reply_to_message_id
if reply_markup:
json_data["reply_markup"] = reply_markup
return requests.post(message_url, json=json_data).json()
def set_webhook(uri):
api = BOT_URL + "setWebHook?url=" + uri
return requests.get(api).json()
def send_file(file_name, file_str, chat_id, caption=False):
api = BOT_URL + "sendDocument"
file = base64.b64decode(file_str)
file = io.BytesIO(file)
files = {"document": (file_name, file)}
if caption:
data = {"chat_id": chat_id, "caption": caption}
else:
data = {"chat_id": chat_id}
response = requests.post(api, data=data, files=files)
return response.json()