def sendPic(self, chat_id, pic, caption=None, key_markup="SAME", keyboard_short=True):
		"""
		Sends a picture in a Telegram message to a user. Retries if fails.
		:param chat_id: ID of chat
		:param pic: a picture file (an object created with open() ) or a bytestring
		:param caption: a text that goes together with picture ina message.
		:return: None
		"""
		sent_message_id = None
		while True:
			try:
				logging.debug("Picture: " + str(pic))
				self.bot.sendChatAction(chat_id, telegram.ChatAction.UPLOAD_PHOTO)
				# set file read cursor to the beginning.
				# This ensures that if a file needs to be re-read (may happen due to exception), it is read from the beginning.
				if hasattr(pic, "seek"):
					# It is probably a file
					pic.seek(0)
				else:
					if isinstance(pic, bytes):
						# It is a bytestring
						pic = io.BufferedReader(io.BytesIO(pic))
					else:
						#a string, probably a file_id. leave as-is
						pass

				# Send the picture!
				sent_message_id = self.bot.sendPhoto(chat_id=chat_id, photo=pic, caption=caption,
													 reply_markup=self.markup(key_markup, keyboard_short=keyboard_short))
			except telegram.error.NetworkError as e:
				print(str(e), full_traceback())#debug
				raise Exception("Network error!")
			except KeyboardInterrupt:
				raise KeyboardInterrupt
			except AttributeError:
				logging.error("Could not send photo. Bad object!\n" + full_traceback())
			except FileNotFoundError:
				logging.error("Could not send photo. File not found!\n" + full_traceback())
			except Exception as e:
				if ("urlopen error" in str(e)) or ("timed out" in str(e)):
					logging.error("Could not send photo. Retrying! Error: " +
						full_traceback()
						)
					sleep(3)
					continue
				else:
					# raise Exception("Could not send message. rror: " + full_traceback())
					logging.error(
							"Could not send photo. Unknown error: " + full_traceback())
			break
		return sent_message_id
Esempio n. 2
0
		def filter_row(row):

			# 0 - train number, 1 - asterik, if present, te trin is AT the station, 2 - station name
			# 3 - B stoplight, asterisks, delay
			row_parse = [i.text.strip(" \n\r\t").replace(u"\xa0", " ") for i in row.findAll(name="td")]
			
			try:
				# parse = [i.strip(" \n\t\r") for i in parse[0]]

				delay_parse = list(re.findall(r"(\**)(B?)(\+[0-9]+|-[0-9]+)$", row_parse[3].strip(" \n\t\r").replace(" ","")))[0]
				
				parse_dict = dict(number=row_parse[0].strip(" \n\t\r"),
				  departed=not bool(row_parse[1].strip(" \n\t\r")),
				  station=row_parse[2].strip(" \n\t\r"),
				  red_light=bool(delay_parse[1]),
				  delay=delay_parse[2]
				  )

			except IndexError:
				print(full_traceback())
				return

			# print("Verified: ", len(parse)==6 )#debug

			result.append(parse_dict)
Esempio n. 3
0
		def readDir(LINK, DIR):

			def unixify_date(d):
				MONTHS = {"Jan": "01",
						  "Feb": "02",
						  "Mar": "03",
						  "Apr": "04",
						  "May": "05",
						  "Jun": "06",
						  "Jul": "07",
						  "Aug": "08",
						  "Sep": "09",
						  "Oct": "10",
						  "Nov": "11",
						  "Dec": "12"
						  }
				d = d.split(",")[1].strip(" ")
				for i in MONTHS.keys():
					d = d.replace(i, MONTHS[i])

				result = timegm(datetime.datetime.strptime(d, "%d %m %Y %H:%M:%S %z").timetuple())
				# print(result)#debug
				return result

			#Set a loop to retry connection if it is refused
			result = []
			while True:
				try:
					req=requests.post('https://api.dropbox.com/1/metadata/link',
									  data=dict( link=LINK, client_id=DROPBOX_APP_KEY,
												 client_secret=DROPBOX_SECRET_KEY, path=DIR) )

					if not req.ok:
						print("Retrying! req.status_code", req.status_code)#debug
						continue

					for i in json.loads(req.content.decode())['contents']:
						if i['is_dir']:
							logging.warning("Reading directory: " + str(i['path']))
							result += readDir(LINK,i['path'])
						else:
							#a file, add to list
							if unixify_mod_time:
								result += [(i['path'], unixify_date(i['modified']),)]
							else:
								result += [(i['path'], i['modified'],)]

					break
				except Exception as e:
					print("Dropbox error:" + full_traceback())
					sleep(60)#wait a bit before retrying
					pass

			return result
	def getUpdates(self):
		"""
		Gets updates. Updates are basically messages sent to bot from users.
		Retries if it fails.
		:return: a list of update objects
		"""
		# if getting updates fails - retry
		updates = []
		while True:
			try:
				updates = self.bot.getUpdates(offset=self.LAST_UPDATE_ID)
				pass
			except KeyboardInterrupt:
				raise KeyboardInterrupt
			except Exception:
				logging.error("Could not read updates. Retrying! Error: " + full_traceback())
				sleep(1)
				continue
			break
		return updates
    def getUpdates(self):
        """
		Gets updates. Updates are basically messages sent to bot from users.
		Retries if it fails.
		:return: a list of update objects
		"""
        # if getting updates fails - retry
        updates = []
        while True:
            try:
                updates = self.bot.getUpdates(offset=self.LAST_UPDATE_ID)
                pass
            except KeyboardInterrupt:
                raise KeyboardInterrupt
            except Exception:
                logging.error("Could not read updates. Retrying! Error: " +
                              full_traceback())
                sleep(1)
                continue
            break
        return updates
	def sendMessage(self, chat_id, message, key_markup="SAME", keyboard_short=True, preview=True, markdown=None, reply_to=None):
		"""
		Sends a text message to Telegram user
		:param keyboard_short: If True, the buttons on custom keyboard will be lower in height.
		Might be useful if there are many rows of buttons and the kyboard fills the screen.
		:param chat_id: ID of chat
		:param message: text to send
		:param key_markup: a list representing a custom keyboard markup to show to user.
		If "SAME", use the same markup as before.
		If None, hide the custom keyboard.
		:param preview: Should a link in a message generate a page preview within a message?
		:type preview: bool
		:param markdown: Should a message support markdown formatting or htmls formatting?
		Pass "html" for HTML formatting, or True for markdown formatting.
		:param reply_to: An id of an existing message. A sent message will be a reply to that message.
		:return: None
		"""

		markdown_mode = None
		if markdown == "html":
			markdown_mode = telegram.ParseMode.HTML
		elif markdown:
			markdown_mode = telegram.ParseMode.MARKDOWN

		logging.warning("Replying to " + str(chat_id) + ": " + message)
		fulltext = self.breakLongMessage(message)

		def send(text):
			self.bot.sendMessage(chat_id=chat_id,
					text=text,
					parse_mode=markdown_mode,
					disable_web_page_preview=(not preview),
					reply_markup=self.markup(key_markup, keyboard_short=keyboard_short),
					reply_to_message_id=reply_to
					)

		for text in fulltext:
			# iterating over parts of a long split message
			while True:
				try:
					if text:
						self.bot.sendChatAction(chat_id, telegram.ChatAction.TYPING)
						send(text=text)
				except telegram.error.NetworkError as e:
					if "Bad request: can't parse message text: can't find end of the entity" in str(e):
						self.sendMessage(chat_id=chat_id, message=self.escape_markdown(text),
										 key_markup=key_markup, keyboard_short=keyboard_short,
										 preview=preview, markdown=markdown, reply_to=reply_to)
				except KeyboardInterrupt:
					raise KeyboardInterrupt
				except Exception as e:
					if "Message is too long" in str(e):
						self.sendMessage(chat_id=chat_id, message="Error: Message is too long!")
					elif ("urlopen error" in str(e)) or ("timed out" in str(e)):
						logging.error("Could not send message. Retrying! Error: " +
							full_traceback()
							)
						sleep(3)
						continue
					else:
						logging.error(
								"Could not send message. Error: " + full_traceback())
				break
    def sendPic(self,
                chat_id,
                pic,
                caption=None,
                key_markup="SAME",
                keyboard_short=True):
        """
		Sends a picture in a Telegram message to a user. Retries if fails.
		:param chat_id: ID of chat
		:param pic: a picture file (an object created with open() ) or a bytestring
		:param caption: a text that goes together with picture ina message.
		:return: None
		"""
        sent_message_id = None
        while True:
            try:
                logging.debug("Picture: " + str(pic))
                self.bot.sendChatAction(chat_id,
                                        telegram.ChatAction.UPLOAD_PHOTO)
                # set file read cursor to the beginning.
                # This ensures that if a file needs to be re-read (may happen due to exception), it is read from the beginning.
                if hasattr(pic, "seek"):
                    # It is probably a file
                    pic.seek(0)
                else:
                    if isinstance(pic, bytes):
                        # It is a bytestring
                        pic = io.BufferedReader(io.BytesIO(pic))
                    else:
                        #a string, probably a file_id. leave as-is
                        pass

                # Send the picture!
                sent_message_id = self.bot.sendPhoto(
                    chat_id=chat_id,
                    photo=pic,
                    caption=caption,
                    reply_markup=self.markup(key_markup,
                                             keyboard_short=keyboard_short))
            except telegram.error.NetworkError as e:
                print(str(e), full_traceback())  #debug
                raise Exception("Network error!")
            except KeyboardInterrupt:
                raise KeyboardInterrupt
            except AttributeError:
                logging.error("Could not send photo. Bad object!\n" +
                              full_traceback())
            except FileNotFoundError:
                logging.error("Could not send photo. File not found!\n" +
                              full_traceback())
            except Exception as e:
                if ("urlopen error" in str(e)) or ("timed out" in str(e)):
                    logging.error("Could not send photo. Retrying! Error: " +
                                  full_traceback())
                    sleep(3)
                    continue
                else:
                    # raise Exception("Could not send message. rror: " + full_traceback())
                    logging.error("Could not send photo. Unknown error: " +
                                  full_traceback())
            break
        return sent_message_id
    def sendMessage(self,
                    chat_id,
                    message,
                    key_markup="SAME",
                    keyboard_short=True,
                    preview=True,
                    markdown=None,
                    reply_to=None):
        """
		Sends a text message to Telegram user
		:param keyboard_short: If True, the buttons on custom keyboard will be lower in height.
		Might be useful if there are many rows of buttons and the kyboard fills the screen.
		:param chat_id: ID of chat
		:param message: text to send
		:param key_markup: a list representing a custom keyboard markup to show to user.
		If "SAME", use the same markup as before.
		If None, hide the custom keyboard.
		:param preview: Should a link in a message generate a page preview within a message?
		:type preview: bool
		:param markdown: Should a message support markdown formatting or htmls formatting?
		Pass "html" for HTML formatting, or True for markdown formatting.
		:param reply_to: An id of an existing message. A sent message will be a reply to that message.
		:return: None
		"""

        markdown_mode = None
        if markdown == "html":
            markdown_mode = telegram.ParseMode.HTML
        elif markdown:
            markdown_mode = telegram.ParseMode.MARKDOWN

        logging.warning("Replying to " + str(chat_id) + ": " + message)
        fulltext = self.breakLongMessage(message)

        def send(text):
            self.bot.sendMessage(
                chat_id=chat_id,
                text=text,
                parse_mode=markdown_mode,
                disable_web_page_preview=(not preview),
                reply_markup=self.markup(key_markup,
                                         keyboard_short=keyboard_short),
                reply_to_message_id=reply_to)

        for text in fulltext:
            # iterating over parts of a long split message
            while True:
                try:
                    if text:
                        self.bot.sendChatAction(chat_id,
                                                telegram.ChatAction.TYPING)
                        send(text=text)
                except telegram.error.NetworkError as e:
                    if "Bad request: can't parse message text: can't find end of the entity" in str(
                            e):
                        self.sendMessage(chat_id=chat_id,
                                         message=self.escape_markdown(text),
                                         key_markup=key_markup,
                                         keyboard_short=keyboard_short,
                                         preview=preview,
                                         markdown=markdown,
                                         reply_to=reply_to)
                except KeyboardInterrupt:
                    raise KeyboardInterrupt
                except Exception as e:
                    if "Message is too long" in str(e):
                        self.sendMessage(chat_id=chat_id,
                                         message="Error: Message is too long!")
                    elif ("urlopen error" in str(e)) or ("timed out"
                                                         in str(e)):
                        logging.error(
                            "Could not send message. Retrying! Error: " +
                            full_traceback())
                        sleep(3)
                        continue
                    else:
                        logging.error("Could not send message. Error: " +
                                      full_traceback())
                break