Skip to content

Commit 8d90a97

Browse files
committed
Add proxy to WebhookClient (ref: #715)
1 parent b78516a commit 8d90a97

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

slack/webhook/client.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import json
22
import logging
3+
import re
34
from http.client import HTTPResponse
45
from typing import Dict, Union, List, Optional
56
from urllib.error import HTTPError
@@ -16,15 +17,21 @@ class WebhookClient:
1617
logger = logging.getLogger(__name__)
1718

1819
def __init__(
19-
self, url: str, timeout: int = 30, default_headers: Dict[str, str] = {}
20+
self,
21+
url: str,
22+
timeout: int = 30,
23+
proxy: Optional[str] = None,
24+
default_headers: Dict[str, str] = {},
2025
):
2126
"""API client for Incoming Webhooks and response_url
2227
:param url: a complete URL to send data (e.g., https://hooks.slack.com/XXX)
2328
:param timeout: request timeout (in seconds)
29+
:param proxy: proxy URL (e.g., localhost:9000, http://localhost:9000)
2430
:param default_headers: request headers to add to all requests
2531
"""
2632
self.url = url
2733
self.timeout = timeout
34+
self.proxy = proxy
2835
self.default_headers = default_headers
2936

3037
def send(
@@ -93,6 +100,10 @@ def _perform_http_request(
93100
req = Request(
94101
method="POST", url=url, data=body.encode("utf-8"), headers=headers
95102
)
103+
if self.proxy is not None:
104+
host = re.sub("^https?://", "", self.proxy)
105+
req.set_proxy(host, "http")
106+
req.set_proxy(host, "https")
96107
else:
97108
raise SlackRequestError(f"Invalid URL detected: {url}")
98109

tests/webhook/test_webhook.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import unittest
22
import socket
3+
import urllib
34

45
from slack.web.classes.attachments import Attachment, AttachmentField
56
from slack.web.classes.blocks import SectionBlock, ImageBlock
@@ -160,3 +161,8 @@ def test_timeout_issue_712(self):
160161
client = WebhookClient(url="http://localhost:8888/timeout", timeout=1)
161162
with self.assertRaises(socket.timeout):
162163
client.send_dict({"text": "hello!"})
164+
165+
def test_proxy_issue_714(self):
166+
client = WebhookClient(url="http://localhost:8888", proxy="http://invalid-host:9999")
167+
with self.assertRaises(urllib.error.URLError):
168+
client.send_dict({"text": "hello!"})

0 commit comments

Comments
 (0)