Skip to content

Commit 459b143

Browse files
authored
Set a generic user-agent for bot detection (#30)
Fixes #29
1 parent f02a556 commit 459b143

File tree

3 files changed

+13
-5
lines changed

3 files changed

+13
-5
lines changed

CHANGELOG

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
## June 23, 2020 - 1.3.1
2+
- Set a generic user agent for file/image get to prevent bot detection
3+
14
## Apr 28, 2020 - 1.3.0
25
- Drop six dependency
36
- `verify_webhook` is affected and expects bytes for body parameter

stream_chat/client.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import hashlib
44
import json
55
import urllib
6+
from urllib.request import Request, urlopen
67

78
import jwt
89
import requests
@@ -302,15 +303,12 @@ def send_file(self, uri, url, name, user, content_type=None):
302303
parts = urlparse(url)
303304
if parts[0] == "":
304305
url = "file://" + url
305-
if content_type:
306-
file_tuple = (name, urllib.request.urlopen(url), content_type)
307-
else:
308-
file_tuple = (name, urllib.request.urlopen(url), content_type)
306+
content = urlopen(Request(url, headers={"User-Agent": "Mozilla/5.0"})).read()
309307
response = requests.post(
310308
"{}/{}".format(self.base_url, uri),
311309
params=self.get_default_params(),
312310
data={"user": json.dumps(user)},
313-
files={"file": file_tuple},
311+
files={"file": (name, content, content_type)},
314312
headers=headers,
315313
)
316314
return self._parse_response(response)

stream_chat/tests/test_channel.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,13 @@ def test_send_and_delete_image(self, channel, random_user):
147147
assert "lena.png" in resp["file"]
148148
# resp = channel.delete_image(resp['file'])
149149

150+
def test_send_image_with_bot_blocked(self, channel, random_user):
151+
# following url blocks bots and we set a generic header to skip it
152+
# but it can start failing again, see initial discussion here: https://github.com/GetStream/stream-chat-python/pull/30#discussion_r444209891
153+
url = "https://api.twilio.com/2010-04-01/Accounts/AC3e136e1a00279f4dadcb10a9f1a1e8a3/Messages/MM547edf6f4846a30231c3033fa20f8419/Media/ME498020f8fe0b0ba2ff83ac99e4782e02"
154+
resp = channel.send_image(url, "js.png", random_user, content_type="image/png")
155+
assert "js.png" in resp["file"]
156+
150157
def test_channel_hide_show(self, client, channel, random_users):
151158
# setup
152159
channel.add_members([u["id"] for u in random_users])

0 commit comments

Comments
 (0)