예제 #1
0
def add_subscriptions(client: Client) -> None:

    # {code_example|start}
    # Subscribe to the stream "new stream"
    result = client.add_subscriptions(streams=[
        {
            "name": "new stream",
            "description": "New stream for testing",
        },
    ], )
    # {code_example|end}

    validate_against_openapi_schema(result, "/users/me/subscriptions", "post",
                                    "200_0")

    # {code_example|start}
    # To subscribe other users to a stream, you may pass
    # the `principals` argument, like so:
    user_id = 26
    result = client.add_subscriptions(
        streams=[
            {
                "name": "new stream",
                "description": "New stream for testing"
            },
        ],
        principals=[user_id],
    )
    # {code_example|end}
    assert result["result"] == "success"
    assert "*****@*****.**" in result["subscribed"]
예제 #2
0
def test_authorization_errors_fatal(client: Client, nonadmin_client: Client) -> None:
    client.add_subscriptions(
        streams=[
            {'name': 'private_stream'},
        ],
    )

    stream_id = client.get_stream_id('private_stream')['stream_id']
    client.call_endpoint(
        f'streams/{stream_id}',
        method='PATCH',
        request={'is_private': True},
    )

    result = nonadmin_client.add_subscriptions(
        streams=[
            {'name': 'private_stream'},
        ],
        authorization_errors_fatal=False,
    )

    validate_against_openapi_schema(result, '/users/me/subscriptions', 'post',
                                    '400_0')

    result = nonadmin_client.add_subscriptions(
        streams=[
            {'name': 'private_stream'},
        ],
        authorization_errors_fatal=True,
    )

    validate_against_openapi_schema(result, '/users/me/subscriptions', 'post',
                                    '400_1')
예제 #3
0
def add_subscriptions(client: Client) -> None:

    # {code_example|start}
    # Subscribe to the stream "new stream"
    result = client.add_subscriptions(
        streams=[
            {
                'name': 'new stream',
                'description': 'New stream for testing',
            },
        ],
    )
    # {code_example|end}

    validate_against_openapi_schema(result, '/users/me/subscriptions', 'post',
                                    '200_0')

    # {code_example|start}
    # To subscribe other users to a stream, you may pass
    # the `principals` argument, like so:
    user_id = 25
    result = client.add_subscriptions(
        streams=[
            {'name': 'new stream', 'description': 'New stream for testing'},
        ],
        principals=[user_id],
    )
    # {code_example|end}
    assert result['result'] == 'success'
    assert '*****@*****.**' in result['subscribed']
예제 #4
0
def test_authorization_errors_fatal(client: Client, nonadmin_client: Client) -> None:
    client.add_subscriptions(
        streams=[
            {"name": "private_stream"},
        ],
    )

    stream_id = client.get_stream_id("private_stream")["stream_id"]
    client.call_endpoint(
        f"streams/{stream_id}",
        method="PATCH",
        request={"is_private": True},
    )

    result = nonadmin_client.add_subscriptions(
        streams=[
            {"name": "private_stream"},
        ],
        authorization_errors_fatal=False,
    )

    validate_against_openapi_schema(result, "/users/me/subscriptions", "post", "400_0")

    result = nonadmin_client.add_subscriptions(
        streams=[
            {"name": "private_stream"},
        ],
        authorization_errors_fatal=True,
    )

    validate_against_openapi_schema(result, "/users/me/subscriptions", "post", "400_1")
예제 #5
0
def test_add_subscriptions_already_subscribed(client: Client) -> None:
    result = client.add_subscriptions(
        streams=[
            {"name": "new stream", "description": "New stream for testing"},
        ],
        principals=["*****@*****.**"],
    )

    validate_against_openapi_schema(result, "/users/me/subscriptions", "post", "200_1")
예제 #6
0
def test_add_subscriptions_already_subscribed(client: Client) -> None:
    result = client.add_subscriptions(
        streams=[
            {'name': 'new stream', 'description': 'New stream for testing'},
        ],
        principals=['*****@*****.**'],
    )

    validate_against_openapi_schema(result, '/users/me/subscriptions', 'post',
                                    '200_1')
예제 #7
0
def delete_stream(client: Client, stream_id: int) -> None:
    result = client.add_subscriptions(
        streams=[{
            'name': 'stream to be deleted',
            'description': 'New stream for testing'
        }])

    # {code_example|start}
    # Delete the stream named 'new stream'
    stream_id = client.get_stream_id('stream to be deleted')['stream_id']
    result = client.delete_stream(stream_id)
    # {code_example|end}
    validate_against_openapi_schema(result, '/streams/{stream_id}', 'delete',
                                    '200')

    assert result['result'] == 'success'
예제 #8
0
def archive_stream(client: Client, stream_id: int) -> None:
    result = client.add_subscriptions(streams=[
        {
            "name": "stream to be archived",
            "description": "New stream for testing",
        },
    ], )

    # {code_example|start}
    # Archive the stream named 'stream to be archived'
    stream_id = client.get_stream_id("stream to be archived")["stream_id"]
    result = client.delete_stream(stream_id)
    # {code_example|end}
    validate_against_openapi_schema(result, "/streams/{stream_id}", "delete",
                                    "200")

    assert result["result"] == "success"
예제 #9
0
class ZulipBot:

	def __init__(self):
		self.client = Client(email = os.environ['ZULIP_USERNAME'], api_key = os.environ['ZULIP_API_KEY'])
		self.subscribe_streams()


	def subscribe_streams(self):
		response = get('https://api.zulip.com/v1/streams', auth=(os.environ['ZULIP_USERNAME'], os.environ['ZULIP_API_KEY']))
		
		if response.status_code == 200:
			streams = [{'name': stream['name']} for stream in response.json()['streams']]
			self.client.add_subscriptions(streams)

		else:
			raise RuntimeError(response)


	##Function to check for any messages

	def read_message(self, msg):
		content = msg['content'].split(',')
		sender_email = msg['sender_email']

		if sender_email == os.environ['ZULIP_USERNAME']:
			return
		if content[0].upper() in ['RUNNING', 'RUNNINGBOT', '@**RUNNING**']:
			return_info = self.find_runs(content)
			if return_info is None:
				self.send_message("No results", msg)
			else:
				[self.send_message(run, msg) for run in return_info]
		else:
			return 


	def find_runs(self, content):
		run_info = sorted(content[1:])
		
		if len(run_info) == 2:
			run_info.append('min=1')
		elif len(run_info) == 1:
			run_info.extend(['max=5.5', 'min=1'])

		run_params = [r.split("=")[-1] for r in run_info]

		get_coords = GoogleRequests()
		lat, lon = get_coords.get_geocode(run_params[0])

		new_req = MMFRouteAPI()
		json_data = new_req.get_routes(lat, lon, run_params[1], run_params[2])
		list_runs = new_req.list_runs(json_data)
		
		if len(list_runs) < 1:
			return None

		return list_runs



	def send_message(self, return_content, msg):
		links = ["Run Name: ", return_content[0], "Distance (miles): ", return_content[1], "Link:", return_content[-1]]
		return_str = " ".join(links)
		if msg['type'] == 'stream':
			self.client.send_message({
                'type': 'stream',
                'subject': 'RUNNINGBOT',
                'to': msg['display_recipient'],
                'content': return_str})
            
		elif msg['type'] == 'private':
			self.client.send_message({
                    'type': 'private',
                    'to': msg['sender_email'],
                    'content': return_str })