Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implements a Proxy Integration #128

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 31 additions & 15 deletions octoprint_telegram/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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))
Expand All @@ -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()
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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

Expand All @@ -1046,15 +1053,15 @@ 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()
if not "ok" in data:
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

Expand All @@ -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:
Expand All @@ -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()
Expand All @@ -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]:
Expand Down