首页 > 解决方案 > Python3 Slack RTMClient 在代理后面不工作

问题描述

我正在尝试为我的项目创建一个简单的 Python 机器人。在我的本地主机上一切正常,但相同的代码在需要设置环境代理的网络防火墙后面停止工作。

from slack import RTMClient

proxy='http://XXXX:NNNN'
token='XXXX'

class Botso():
    def __init__(self):
            self.proxy=self.get_proxy()
            self.rt= RTMClient(
                          token=token,
                          connect_method='rtm.start',
                          proxy=self.proxy
                        )

    def get_proxy(self):
        host=socket.gethostname()
        if "internal" in host:
            return None
        elif "XXX" in host:
            return proxy

@RTMClient.run_on(event="message")
def say_hello(**payload):
  data = payload['data']
  web_client = payload['web_client']
  if 'text' in data and 'hii' in data['text']:
    channel_id = data['channel']
    thread_ts = data['ts']
    user = data['user'] # This is not username but user ID (the format is either U*** or W***)

    web_client.chat_postMessage(
      channel=channel_id,
      text=f"Hi <@{user}>!"
      #thread_ts=thread_ts
    )
if __name__ == '__main__':
    botso=Botso()
    botso.rt.start()

我在初始化 RTMClient 时遇到的错误是

Traceback (most recent call last):
  File "botso.py" , in <module>
    botso.rt.start()

  File "/usr/lib64/python3.6/http/client.py", line 974, in send
    self.connect()
  File "/usr/lib64/python3.6/http/client.py", line 1407, in connect
    super().connect()
  File "/usr/lib64/python3.6/http/client.py", line 950, in connect
    self._tunnel()
  File "/usr/lib64/python3.6/http/client.py", line 929, in _tunnel
    message.strip()))
OSError: Tunnel connection failed: 403 Forbidden

我在同一环境中有其他代码,它们使用相同的代理发送松弛消息,并且使用请求 api 可以正常工作。

params={
'token': self.slack_token,
'types': ['public_channel','private_channel']
}
slack_url='https://slack.com/api/conversations.list'
response = requests.get(url=slack_url,params=params,proxies=self.proxy).json()

我们如何使 RTMClient 与代理和 Python3 一起工作。在松弛的 API 文档中找不到太多帮助。

标签: python-3.xproxyslack-api

解决方案


推荐阅读