forked from jg-fisher/python-telegram-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram_bot.py
82 lines (55 loc) · 2.21 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import requests
from config import TELEGRAM_SEND_MESSAGE_URL
class TelegramBot:
def __init__(self):
""""
Initializes an instance of the TelegramBot class.
Attributes:
chat_id:str: Chat ID of Telegram chat, used to identify which conversation outgoing messages should be send to.
text:str: Text of Telegram chat
first_name:str: First name of the user who sent the message
last_name:str: Last name of the user who sent the message
"""
self.chat_id = None
self.text = None
self.first_name = None
self.last_name = None
def parse_webhook_data(self, data):
"""
Parses Telegram JSON request from webhook and sets fields for conditional actions
Args:
data:str: JSON string of data
"""
message = data['message']
self.chat_id = message['chat']['id']
self.incoming_message_text = message['text'].lower()
self.first_name = message['from']['first_name']
self.last_name = message['from']['last_name']
def action(self):
"""
Conditional actions based on set webhook data.
Returns:
bool: True if the action was completed successfully else false
"""
success = None
if self.incoming_message_text == '/hello':
self.outgoing_message_text = "Hello {} {}!".format(self.first_name, self.last_name)
success = self.send_message()
if self.incoming_message_text == '/rad':
self.outgoing_message_text = '🤙'
success = self.send_message()
return success
def send_message(self):
"""
Sends message to Telegram servers.
"""
res = requests.get(TELEGRAM_SEND_MESSAGE_URL.format(self.chat_id, self.outgoing_message_text))
return True if res.status_code == 200 else False
@staticmethod
def init_webhook(url):
"""
Initializes the webhook
Args:
url:str: Provides the telegram server with a endpoint for webhook data
"""
requests.get(url)