Passed
Push — master ( eaebec...66e57b )
by Ian
06:21
created

Telegrammer._resolve_extra_text()   A

Complexity

Conditions 5

Size

Total Lines 13
Code Lines 10

Duplication

Lines 13
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 10.3999

Importance

Changes 0
Metric Value
eloc 10
dl 13
loc 13
ccs 4
cts 10
cp 0.4
rs 9.3333
c 0
b 0
f 0
cc 5
nop 2
crap 10.3999
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.extra_text = helpers._resolve_extra_text(extra_text, max_len=4096, sender=self.sender)
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
	def auth(self):
61 1
		if not self.testing:
62
			self.telegram = tg.Bot(token=self.token)
63
		else:
64 1
			printW('The Telegram module will not post to Telegram in Testing mode.',
65
					self.sender, announce=False)
66
67
68 1
	def getq(self):
69 1
		d = self.queue.get()
70 1
		self.queue.task_done()
71
72 1
		if 'TERM' in str(d):
73 1
			self.alive = False
74 1
			printM('Exiting.', self.sender)
75 1
			sys.exit()
76
		else:
77 1
			return d
78
79
80 1
	def _when_alarm(self, d):
81
		'''
82
		Send a telegram in an alert scenario.
83
84
		:param bytes d: queue message
85
		'''
86 1
		event_time = helpers.fsec(helpers.get_msg_time(d))
87 1
		self.last_event_str = '%s' % (event_time.strftime(self.fmt)[:22])
88 1
		message = '%s %s UTC%s - %s' % (self.message0, self.last_event_str, self.extra_text, self.livelink)
89 1
		response = None
90 1
		try:
91 1
			printM('Sending alert...', sender=self.sender)
92 1
			printM('Telegram message: %s' % (message), sender=self.sender)
93 1
			if not self.testing:
94
				response = self.telegram.sendMessage(chat_id=self.chat_id, text=message)
95
			else:
96 1
				TEST['c_telegram'][1] = True
97
98
		except Exception as e:
99
			printE('Could not send alert - %s' % (e))
100
			try:
101
				printE('Waiting 5 seconds and trying to send again...', sender=self.sender, spaces=True)
102
				time.sleep(5)
103
				self.auth()
104
				printM('Telegram message: %s' % (message), sender=self.sender)
105
				if not self.testing:
106
					response = self.telegram.sendMessage(chat_id=self.chat_id, text=message)
107
				else:
108
					# if you are here in testing mode, there is a problem
109
					TEST['c_telegram'][1] = False
110
			except Exception as e:
111
				printE('Could not send alert - %s' % (e))
112
				response = None
113 1
		self.last_message = message
114
115
116 1
	def _when_img(self, d):
117
		'''
118
		Send a telegram image in when you get an ``IMGPATH`` message.
119
120
		:param bytes d: queue message
121
		'''
122 1
		if self.send_images:
123 1
			imgpath = helpers.get_msg_path(d)
124 1
			response = None
125 1
			if os.path.exists(imgpath):
126 1
				with open(imgpath, 'rb') as image:
127 1
					try:
128 1
						if not self.testing:
129
							printM('Uploading image to Telegram %s' % (imgpath), self.sender)
130
							response = self.telegram.sendPhoto(chat_id=self.chat_id, photo=image)
131
							printM('Sent image', sender=self.sender)
132
						else:
133 1
							printM('Image ready to send - %s' % (imgpath), self.sender)
134 1
							TEST['c_telegramimg'][1] = True
135
					except Exception as e:
136
						printE('Could not send image - %s' % (e))
137
						try:
138
							if not self.testing:
139
								printM('Waiting 5 seconds and trying to send again...', sender=self.sender)
140
								time.sleep(5.1)
141
								self.auth()
142
								printM('Uploading image to Telegram (2nd try) %s' % (imgpath), self.sender)
143
								response = self.telegram.sendPhoto(chat_id=self.chat_id, photo=image)
144
								printM('Sent image', sender=self.sender)
145
							else:
146
								# if you are here in testing mode, there is a problem
147
								TEST['c_telegramimg'][1] = False
148
						except Exception as e:
149
							printE('Could not send image - %s' % (e))
150
							response = None
151
			else:
152
				printM('Could not find image: %s' % (imgpath), sender=self.sender)
153
154
155 1 View Code Duplication
	def run(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
156
		"""
157
		Reads data from the queue and sends a message if it sees an ALARM or IMGPATH message
158
		"""
159 1
		while True:
160 1
			d = self.getq()
161
162 1
			if 'ALARM' in str(d):
163 1
				self._when_alarm(d)
164
165 1
			elif 'IMGPATH' in str(d):
166
				self._when_img(d)
167