Passed
Push — master ( e96c3d...44474a )
by Ian
06:20
created

build.rsudp.c_telegram   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 154
Duplicated Lines 7.79 %

Importance

Changes 0
Metric Value
wmc 19
eloc 91
dl 12
loc 154
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A Telegrammer.getq() 0 10 2
A Telegrammer.run() 12 12 4
A Telegrammer._when_alarm() 0 26 3
B Telegrammer._when_img() 0 30 6
A Telegrammer.auth() 0 2 1
A Telegrammer.__init__() 0 30 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
import os, sys
2
import time
3
from datetime import datetime, timedelta
4
from rsudp.raspberryshake import ConsumerThread
5
import rsudp.raspberryshake as rs
6
from rsudp import printM, printW, printE, helpers
7
import rsudp
8
import telegram as tg
9
10
class Telegrammer(rs.ConsumerThread):
11
	'''
12
	 .. versionadded:: 0.4.2
13
14
	.. |telegram| raw:: html
15
16
		<a href="https://t.me/" target="_blank">Telegram</a>
17
18
	.. |sasmex_use| raw:: html
19
20
		<a href="https://t.me/sasmex" target="_blank">used by</a>
21
22
	|telegram| is a free messaging service which,
23
	among other things, is suited to quickly broadcasting automatic
24
	notifications via an API.
25
	It is |sasmex_use| the Mexican Early Warning
26
	System (SASMEX) and PanamaIGC.
27
28
	:param str token: bot token from Telegram bot creation
29
	:param str chat_id: Telegram chat ID number that this module will post to
30
	:param bool send_images: whether or not to send images. if False, only alerts will be sent.
31
	:param queue.Queue q: queue of data and messages sent by :class:`rsudp.c_consumer.Consumer`
32
33
	'''
34
	def __init__(self, token, chat_id,
35
				 q=False, send_images=False,
36
				 sender='Telegram'):
37
		"""
38
		Initializing the Telegram message posting thread.
39
40
		"""
41
		super().__init__()
42
		self.sender = sender
43
		self.alive = True
44
		self.send_images = send_images
45
		self.token = token
46
		self.chat_id = chat_id
47
		self.fmt = '%Y-%m-%d %H:%M:%S.%f'
48
		self.region = ' - region: %s' % rs.region.title() if rs.region else ''
49
50
		if q:
51
			self.queue = q
52
		else:
53
			printE('no queue passed to consumer! Thread will exit now!', self.sender)
54
			sys.stdout.flush()
55
			self.alive = False
56
			sys.exit()
57
58
		self.telegram = tg.Bot(token=self.token)
59
60
		self.livelink = 'live feed ➡️ https://raspberryshake.net/stationview/#?net=%s&sta=%s' % (rs.net, rs.stn)
61
		self.message0 = '(Raspberry Shake station %s.%s%s) Event detected at' % (rs.net, rs.stn, self.region)
62
63
		printM('Starting.', self.sender)
64
65
66
	def auth(self):
67
		self.telegram = tg.Bot(token=self.token)
68
69
70
	def getq(self):
71
		d = self.queue.get()
72
		self.queue.task_done()
73
74
		if 'TERM' in str(d):
75
			self.alive = False
76
			printM('Exiting.', self.sender)
77
			sys.exit()
78
		else:
79
			return d
80
81
82
	def _when_alarm(self, d):
83
		'''
84
		Send a telegram in an alert scenario.
85
86
		:param bytes d: queue message
87
		'''
88
		event_time = helpers.fsec(helpers.get_msg_time(d))
89
		self.last_event_str = '%s' % (event_time.strftime(self.fmt)[:22])
90
		message = '%s %s UTC - %s' % (self.message0, self.last_event_str, self.livelink)
91
		response = None
92
		try:
93
			printM('Sending alert...', sender=self.sender)
94
			response = self.telegram.sendMessage(chat_id=self.chat_id, text=message)
95
			printM('Sent Telegram: %s' % (message), sender=self.sender)
96
97
		except Exception as e:
98
			printE('Could not send alert - %s' % (e))
99
			try:
100
				printE('Waiting 5 seconds and trying to send again...', sender=self.sender, spaces=True)
101
				time.sleep(5)
102
				self.auth()
103
				response = self.telegram.sendMessage(chat_id=self.chat_id, text=message)
104
				printM('Sent Telegram: %s' % (message), sender=self.sender)
105
			except Exception as e:
106
				printE('Could not send alert - %s' % (e))
107
				response = None
108
109
110
	def _when_img(self, d):
111
		'''
112
		Send a telegram image in when you get an ``IMGPATH`` message.
113
114
		:param bytes d: queue message
115
		'''
116
		if self.send_images:
117
			imgpath = helpers.get_msg_path(d)
118
			response = None
119
			if os.path.exists(imgpath):
120
				with open(imgpath, 'rb') as image:
121
					try:
122
						printM('Uploading image to Telegram %s' % (imgpath), self.sender)
123
						response = self.telegram.sendPhoto(chat_id=self.chat_id, photo=image)
124
						printM('Sent image', sender=self.sender)
125
					except Exception as e:
126
						printE('Could not send image - %s' % (e))
127
						try:
128
							printM('Waiting 5 seconds and trying to send again...', sender=self.sender)
129
							time.sleep(5.1)
130
							self.auth()
131
							printM('Uploading image to Telegram (2nd try) %s' % (imgpath), self.sender)
132
							response = self.telegram.sendPhoto(chat_id=self.chat_id, photo=image)
133
							printM('Sent image', sender=self.sender)
134
135
						except Exception as e:
136
							printE('Could not send image - %s' % (e))
137
							response = None
138
			else:
139
				printM('Could not find image: %s' % (imgpath), sender=self.sender)
140
141
142 View Code Duplication
	def run(self):
143
		"""
144
		Reads data from the queue and sends a message if it sees an ALARM or IMGPATH message
145
		"""
146
		while True:
147
			d = self.getq()
148
149
			if 'ALARM' in str(d):
150
				self._when_alarm(d)
151
152
			elif 'IMGPATH' in str(d):
153
				self._when_img(d)
154