Passed
Push — master ( cc3949...eaebec )
by Ian
05:52
created

build.rsudp.c_telegram.Telegrammer._when_img()   B

Complexity

Conditions 8

Size

Total Lines 37
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 25.0063

Importance

Changes 0
Metric Value
eloc 28
dl 0
loc 37
ccs 10
cts 28
cp 0.357
rs 7.3333
c 0
b 0
f 0
cc 8
nop 2
crap 25.0063
1 1
import os, sys
2 1
import time
3 1
import rsudp.raspberryshake as rs
4 1
from rsudp import printM, printW, printE, helpers
5 1
from rsudp.test import TEST
6 1
import telegram as tg
7
8 1
class Telegrammer(rs.ConsumerThread):
9
	'''
10
	 .. versionadded:: 0.4.2
11
12
	.. |telegram| raw:: html
13
14
		<a href="https://t.me/" target="_blank">Telegram</a>
15
16
	.. |sasmex_use| raw:: html
17
18
		<a href="https://t.me/sasmex" target="_blank">Mexican Early Warning System (SASMEX)</a>
19
20
	|telegram| is a free messaging service which,
21
	among other things, is suited to quickly broadcasting automatic
22
	notifications via an API.
23
	It is used by the |sasmex_use| and PanamaIGC.
24
25
	:param str token: bot token from Telegram bot creation
26
	:param str chat_id: Telegram chat ID number that this module will post to
27
	:param bool send_images: whether or not to send images. if False, only alerts will be sent.
28
	:param queue.Queue q: queue of data and messages sent by :class:`rsudp.c_consumer.Consumer`
29
30
	'''
31 1
	def __init__(self, token, chat_id, testing=False,
32
				 q=False, send_images=False, extra_text=False,
33
				 sender='Telegram'):
34
		"""
35
		Initializing the Telegram message posting thread.
36
37
		"""
38 1
		super().__init__()
39 1
		self.queue = q
40 1
		self.sender = sender
41 1
		self.alive = True
42 1
		self.send_images = send_images
43 1
		self.token = token
44 1
		self.chat_id = chat_id
45 1
		self.testing = testing
46 1
		self.fmt = '%Y-%m-%d %H:%M:%S.%f'
47 1
		self.region = ' - region: %s' % rs.region.title() if rs.region else ''
48
49 1
		self._resolve_extra_text(extra_text)
50
51 1
		self.auth()
52
53 1
		self.livelink = u'live feed ➡️ https://stationview.raspberryshake.org/#?net=%s&sta=%s' % (rs.net, rs.stn)
54 1
		self.message0 = '(Raspberry Shake station %s.%s%s) Event detected at' % (rs.net, rs.stn, self.region)
55 1
		self.last_message = False
56
57 1
		printM('Starting.', self.sender)
58
59
60 1 View Code Duplication
	def _resolve_extra_text(self, extra_text):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
61 1
		allowable_len = 4096 - (280-103)	# length of string allowable given maximum message text & region
62 1
		if ((extra_text == '') or (extra_text == None) or (extra_text == False)):
63 1
			self.extra_text = ''
64
		else:
65
			extra_text = str(extra_text)
66
			len_ex_txt = len(extra_text)
67
68
			if len_ex_txt > allowable_len:
69
				printW('extra_text parameter is longer than allowable (%s chars) and will be truncated. Please keep extra_text at or below %s characters.' % (len_ex_txt, allowable_len), sender=self.sender)
70
				extra_text = extra_text[:allowable_len]
71
72
			self.extra_text =  ' %s' % (extra_text)
73
74
75 1
	def auth(self):
76 1
		if not self.testing:
77
			self.telegram = tg.Bot(token=self.token)
78
		else:
79 1
			printW('The Telegram module will not post to Telegram in Testing mode.',
80
					self.sender, announce=False)
81
82
83 1
	def getq(self):
84 1
		d = self.queue.get()
85 1
		self.queue.task_done()
86
87 1
		if 'TERM' in str(d):
88 1
			self.alive = False
89 1
			printM('Exiting.', self.sender)
90 1
			sys.exit()
91
		else:
92 1
			return d
93
94
95 1
	def _when_alarm(self, d):
96
		'''
97
		Send a telegram in an alert scenario.
98
99
		:param bytes d: queue message
100
		'''
101 1
		event_time = helpers.fsec(helpers.get_msg_time(d))
102 1
		self.last_event_str = '%s' % (event_time.strftime(self.fmt)[:22])
103 1
		message = '%s %s UTC%s - %s' % (self.message0, self.last_event_str, self.extra_text, self.livelink)
104 1
		response = None
105 1
		try:
106 1
			printM('Sending alert...', sender=self.sender)
107 1
			printM('Telegram message: %s' % (message), sender=self.sender)
108 1
			if not self.testing:
109
				response = self.telegram.sendMessage(chat_id=self.chat_id, text=message)
110
			else:
111 1
				TEST['c_telegram'][1] = True
112
113
		except Exception as e:
114
			printE('Could not send alert - %s' % (e))
115
			try:
116
				printE('Waiting 5 seconds and trying to send again...', sender=self.sender, spaces=True)
117
				time.sleep(5)
118
				self.auth()
119
				printM('Telegram message: %s' % (message), sender=self.sender)
120
				if not self.testing:
121
					response = self.telegram.sendMessage(chat_id=self.chat_id, text=message)
122
				else:
123
					# if you are here in testing mode, there is a problem
124
					TEST['c_telegram'][1] = False
125
			except Exception as e:
126
				printE('Could not send alert - %s' % (e))
127
				response = None
128 1
		self.last_message = message
129
130
131 1
	def _when_img(self, d):
132
		'''
133
		Send a telegram image in when you get an ``IMGPATH`` message.
134
135
		:param bytes d: queue message
136
		'''
137 1
		if self.send_images:
138 1
			imgpath = helpers.get_msg_path(d)
139 1
			response = None
140 1
			if os.path.exists(imgpath):
141 1
				with open(imgpath, 'rb') as image:
142 1
					try:
143 1
						if not self.testing:
144
							printM('Uploading image to Telegram %s' % (imgpath), self.sender)
145
							response = self.telegram.sendPhoto(chat_id=self.chat_id, photo=image)
146
							printM('Sent image', sender=self.sender)
147
						else:
148 1
							printM('Image ready to send - %s' % (imgpath), self.sender)
149 1
							TEST['c_telegramimg'][1] = True
150
					except Exception as e:
151
						printE('Could not send image - %s' % (e))
152
						try:
153
							if not self.testing:
154
								printM('Waiting 5 seconds and trying to send again...', sender=self.sender)
155
								time.sleep(5.1)
156
								self.auth()
157
								printM('Uploading image to Telegram (2nd try) %s' % (imgpath), self.sender)
158
								response = self.telegram.sendPhoto(chat_id=self.chat_id, photo=image)
159
								printM('Sent image', sender=self.sender)
160
							else:
161
								# if you are here in testing mode, there is a problem
162
								TEST['c_telegramimg'][1] = False
163
						except Exception as e:
164
							printE('Could not send image - %s' % (e))
165
							response = None
166
			else:
167
				printM('Could not find image: %s' % (imgpath), sender=self.sender)
168
169
170 1 View Code Duplication
	def run(self):
171
		"""
172
		Reads data from the queue and sends a message if it sees an ALARM or IMGPATH message
173
		"""
174 1
		while True:
175 1
			d = self.getq()
176
177 1
			if 'ALARM' in str(d):
178 1
				self._when_alarm(d)
179
180 1
			elif 'IMGPATH' in str(d):
181
				self._when_img(d)
182