From b76d6b7806500c44b77a15178bbeb87aa72056ad Mon Sep 17 00:00:00 2001 From: Tobi Date: Fri, 27 Apr 2018 18:55:47 +0200 Subject: [PATCH] Implements a Proxy Integration Now, you can use HTTP or SOCKS5 proxies with this bot. In config.yaml under telegram add the two following lines: http_proxy: http://user:pass@proxy.com:3128 https_proxy: http://user:pass@proxy.com:3128 If you are using SOCKS5 proxy, the lines looks like this: http_proxy: socks5://user:pass@proxy.com:3128 https_proxy: socks5://user:pass@proxy.com:3128 Maybe you have to run the following line to install socks-compability: pip install requests[socks] --- octoprint_telegram/__init__.py | 46 +++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/octoprint_telegram/__init__.py b/octoprint_telegram/__init__.py index da513ae..5f6fe1d 100644 --- a/octoprint_telegram/__init__.py +++ b/octoprint_telegram/__init__.py @@ -173,7 +173,7 @@ def handleDocumentMessage(self, message, chat_id, from_id): target_filename = "telegram_"+file_name # for parameter no_markup see _send_edit_msg() self.main.send_msg(self.gEmo('save') + gettext(" Saving file {}...".format(target_filename)), chatID=chat_id) - requests.get(self.main.bot_url + "/sendChatAction", params = {'chat_id': chat_id, 'action': 'upload_document'}) + requests.get(self.main.bot_url + "/sendChatAction", params = {'chat_id': chat_id, 'action': 'upload_document'}, proxies=self.getProxies()) data = self.main.get_file(message['message']['document']['file_id']) stream = octoprint.filemanager.util.StreamWrapper(file_name, io.BytesIO(data)) self.main._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL, target_filename, stream, allow_overwrite=True) @@ -284,7 +284,7 @@ def getUpdates(self): if self.update_offset == 0 and self.first_contact: res = ["0","0"] while len(res) > 0: - req = requests.get(self.main.bot_url + "/getUpdates", params={'offset':self.update_offset, 'timeout':0}, allow_redirects=False, timeout=10) + req = requests.get(self.main.bot_url + "/getUpdates", params={'offset':self.update_offset, 'timeout':0}, allow_redirects=False, timeout=10, proxies=self.getProxies()) json = req.json() if not json['ok']: self.set_status(gettext("Response didn't include 'ok:true'. Waiting 2 minutes before trying again. Response was: %(response)s", json)) @@ -299,7 +299,7 @@ def getUpdates(self): if self.update_offset == 0: self.update_offset = 1 else: - req = requests.get(self.main.bot_url + "/getUpdates", params={'offset':self.update_offset, 'timeout':30}, allow_redirects=False, timeout=40) + req = requests.get(self.main.bot_url + "/getUpdates", params={'offset':self.update_offset, 'timeout':30}, allow_redirects=False, timeout=40, proxies=self.getProxies()) except requests.exceptions.Timeout: # Just start the next loop. raise ExitThisLoopException() @@ -338,6 +338,13 @@ def set_status(self, status, ok=False): self.connection_ok = ok self.main.connection_state_str = status + def getProxies(self): + http_proxy = self.main._settings.get(["http_proxy"]) + https_proxy = self.main._settings.get(["https_proxy"]) + return { + 'http': http_proxy, + 'https': https_proxy + } class TelegramPluginLoggingFilter(logging.Filter): def filter(self, record): @@ -606,7 +613,7 @@ def on_settings_migrate(self, target, current=None): message['text'] = "The OctoPrint Plugin " + self._plugin_name + " has been updated to new Version "+self._plugin_version+ ".\n\nPlease open your " + self._plugin_name + " settings in OctoPrint and set configurations for this chat. Until then you are not able to send or receive anything useful with this Bot.\n\nMore informations on: https://github.com/fabianonline/OctoPrint-Telegram" message['chat_id'] = chat message['disable_web_page_preview'] = True - r = requests.post("https://api.telegram.org/bot" + self._settings.get(['token']) + "/sendMessage", data = message) + r = requests.post("https://api.telegram.org/bot" + self._settings.get(['token']) + "/sendMessage", data = message, proxies=self.getProxies()) r.raise_for_status() if r.headers['content-type'] != 'application/json': raise Exception("invalid content-type") @@ -954,7 +961,7 @@ def _send_edit_msg(self,message="",msg_id="",chatID="", responses= None, inline= keyboard = {'inline_keyboard':myArr} data['reply_markup'] = json.dumps(keyboard) self._logger.debug("SENDING UPDATE: " + str(data)) - req = requests.post(self.bot_url + "/editMessageText", data=data) + req = requests.post(self.bot_url + "/editMessageText", data=data, proxies=self.getProxies()) if req.headers['content-type'] != 'application/json': self._logger.debug(gettext("Unexpected Content-Type. Expected: application/json. Was: %(type)s. Waiting 2 minutes before trying again.", type=req.headers['content-type'])) return @@ -1013,12 +1020,12 @@ def _send_msg(self, message="", with_image=False, responses=None, delay=0, inlin files = {'photo':("image.jpg", image_data)} if message is not "": data['caption'] = message - r = requests.post(self.bot_url + "/sendPhoto", files=files, data=data) - self._logger.debug("Sending finished. " + str(r.status_code)) + r = requests.post(self.bot_url + "/sendPhoto", files=files, data=data, proxies=self.getProxies()) + self._logger.debug("Sending finished. " + str(r)) else: self._logger.debug("Sending without image.. " + str(chatID)) data['text'] = message - r =requests.post(self.bot_url + "/sendMessage", data=data) + r =requests.post(self.bot_url + "/sendMessage", data=data, proxies=self.getProxies()) self._logger.debug("Sending finished. " + str(r.status_code)) if r is not None and inline: @@ -1029,13 +1036,13 @@ def _send_msg(self, message="", with_image=False, responses=None, delay=0, inlin if 'message_id' in myJson['result']: self.updateMessageID[chatID] = myJson['result']['message_id'] except Exception as ex: - self._logger.debug("Caught an exception in _send_msg(): " + str(ex)) + self._logger.info("Caught an exception in _send_msg(): " + str(ex)) def send_file(self,chat_id,path): try: - requests.get(self.bot_url + "/sendChatAction", params = {'chat_id': chat_id, 'action': 'upload_document'}) + requests.get(self.bot_url + "/sendChatAction", params = {'chat_id': chat_id, 'action': 'upload_document'}, proxies=self.getProxies()) files = {'document': open(path, 'rb')} - r = requests.post(self.bot_url + "/sendDocument", files=files, data={'chat_id':chat_id}) + r = requests.post(self.bot_url + "/sendDocument", files=files, data={'chat_id':chat_id}, proxies=self.getProxies()) except Exception as ex: pass @@ -1046,7 +1053,7 @@ def send_video(self, message, video_file): def get_file(self, file_id): self._logger.debug("Requesting file with id %s.", file_id) - r = requests.get(self.bot_url + "/getFile", data={'file_id': file_id}) + r = requests.get(self.bot_url + "/getFile", data={'file_id': file_id}, proxies=self.getProxies()) # {"ok":true,"result":{"file_id":"BQADAgADCgADrWJxCW_eFdzxDPpQAg","file_size":26,"file_path":"document\/file_3.gcode"}} r.raise_for_status() data = r.json() @@ -1054,7 +1061,7 @@ def get_file(self, file_id): raise Exception(_("Telegram didn't respond well to getFile. The response was: %(response)s", response=r.text)) url = self.bot_file_url + "/" + data['result']['file_path'] self._logger.debug("Downloading file: %s", url) - r = requests.get(url) + r = requests.get(url, proxies=self.getProxies()) r.raise_for_status() return r.content @@ -1065,7 +1072,7 @@ def get_usrPic(self,chat_id, file_id=""): if int(chat_id) < 0: self._logger.debug("Not able to load group photos. "+ str(chat_id)+" EXIT") return - r = requests.get(self.bot_url + "/getUserProfilePhotos", params = {'limit': 1, "user_id": chat_id}) + r = requests.get(self.bot_url + "/getUserProfilePhotos", params = {'limit': 1, "user_id": chat_id}, proxies=self.getProxies()) r.raise_for_status() data = r.json() if not "ok" in data: @@ -1088,7 +1095,7 @@ def get_usrPic(self,chat_id, file_id=""): def test_token(self, token=None): if token is None: token = self._settings.get(["token"]) - response = requests.get("https://api.telegram.org/bot" + token + "/getMe") + response = requests.get("https://api.telegram.org/bot" + token + "/getMe", proxies=self.getProxies()) self._logger.debug("getMe returned: " + str(response.json())) self._logger.debug("getMe status code: " + str(response.status_code)) json = response.json() @@ -1110,6 +1117,15 @@ def str2bool(self,v): def set_log_level(self): self._logger.setLevel(logging.DEBUG if self._settings.get_boolean(["debug"]) else logging.NOTSET) + + def getProxies(self): + http_proxy = self._settings.get(["http_proxy"]) + https_proxy = self._settings.get(["https_proxy"]) + return { + 'http': http_proxy, + 'https': https_proxy + } + # checks if the received command is allowed to execute by the user def isCommandAllowed(self, chat_id, from_id, command): if 'bind_none' in self.tcmd.commandDict[command]: