make Python 3.x Slack (slackclient) use a corporate proxy

北城以北 提交于 2019-12-24 04:26:27

问题


I have some Python 3 code and can make it use the module slackclient to post to channels, no problem. However if I run this code from our corporate servers where all traffic needs to go through a proxy it fails. I know the proxy server and port and have to use them to run pip from our servers, like this:

pip install --proxy proxy.evilcorp.com:8080 slackclient

That works great. If I don't proxy the pip, it fails to connect as expected. So that tells me I just need to figure out how to get my slackclient code to use the proxy, but how? Here is my code:

from slackclient import SlackClient

def get_slackclient():
    token = "blah-blah-token"
    sc = SlackClient(token)
    return sc

def post_slackmessage(username,channel,text):
    sc = get_slackclient()
    try:
        sc.api_call("chat.postMessage",channel=channel,text=text,username=username,unfurl_links="true")
    except:
        print ("failed to post messaage to slack")

post_slackmessage("test_slack", "test", "hurrah it posted")

I just can't seem to figure out where to put proxy settings, I must be missing something simple. I'm open to other outside the box ideas to make this all work but I can't really install anything on the server to make all traffic go through the proxy or change the proxy settings.


回答1:


Figured it out. I'll leave this here in case somebody else has the same problem. Looks like it's built in, just pass a proxies dict in.

def get_slackclient():
    #https://api.slack.com/custom-integrations/legacy-tokens
    token = "blah-blah-blah"
    proxies = dict(https="proxy.evilcorp.com:8080", http="proxy.evilcorp.com:8080")
    sc = SlackClient(token, proxies=proxies)
    return sc

Well, that was easy :)

UPDATE

If you happen to upgrade to the latest slack module, it is a little different and only http:// proxies are supported (no secure for you!). And you pass in a str instead of a dict so just one proxy.

Just change to this:

proxy = "proxy.evilcorp.com:8080"
sc = slack.WebClient(token, timeout=60, proxy=proxy)

You'll note that actually making the call to the api has changed as well, like this:

sc.chat_postMessage(channel=thechannel, text=thetext, username=theusername, unfurl_links="true")


来源:https://stackoverflow.com/questions/46365527/make-python-3-x-slack-slackclient-use-a-corporate-proxy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!