-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathhello_world.py
More file actions
71 lines (58 loc) · 2.59 KB
/
hello_world.py
File metadata and controls
71 lines (58 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------
import os
from azure.messaging.webpubsubclient import WebPubSubClient, WebPubSubClientCredential
from azure.messaging.webpubsubservice import WebPubSubServiceClient
from azure.identity import DefaultAzureCredential
from azure.messaging.webpubsubclient.models import (
OnConnectedArgs,
OnGroupDataMessageArgs,
OnDisconnectedArgs,
CallbackType,
WebPubSubDataType,
)
from dotenv import load_dotenv
load_dotenv()
def on_connected(msg: OnConnectedArgs):
print("======== connected ===========")
print(f"Connection {msg.connection_id} is connected")
def on_disconnected(msg: OnDisconnectedArgs):
print("========== disconnected =========")
print(f"connection is disconnected: {msg.message}")
def on_group_message(msg: OnGroupDataMessageArgs):
print("========== group message =========")
if isinstance(msg.data, memoryview):
print(f"Received message from {msg.group}: {bytes(msg.data).decode()}")
else:
print(f"Received message from {msg.group}: {msg.data}")
def main():
service_client = WebPubSubServiceClient(
endpoint=os.getenv("WEBPUBSUB_ENDPOINT", ""), hub="hub", credential=DefaultAzureCredential()
)
client = WebPubSubClient(
credential=WebPubSubClientCredential(
client_access_url_provider=lambda: service_client.get_client_access_token(
roles=["webpubsub.joinLeaveGroup", "webpubsub.sendToGroup"]
)["url"]
),
)
with client:
client.subscribe(CallbackType.CONNECTED, on_connected)
client.subscribe(CallbackType.DISCONNECTED, on_disconnected)
client.subscribe(CallbackType.GROUP_MESSAGE, on_group_message)
group_name = "hello_world"
client.join_group(group_name)
client.send_to_group(group_name, "hello text", WebPubSubDataType.TEXT, no_echo=False, ack=False)
client.send_to_group(group_name, {"hello": "json"}, WebPubSubDataType.JSON)
client.send_to_group(group_name, "hello text", WebPubSubDataType.TEXT)
content = memoryview("hello binary".encode())
client.send_to_group(group_name, content, WebPubSubDataType.BINARY)
# If you can't run client in context, please open/close client manually like:
# client.open()
# ...
# client.close()
if __name__ == "__main__":
main()