forked from hiero-ledger/hiero-sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopic_message_submit.py
More file actions
95 lines (78 loc) · 2.65 KB
/
topic_message_submit.py
File metadata and controls
95 lines (78 loc) · 2.65 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""
uv run examples/topic_message_submit.py
python examples/topic_message_submit.py
"""
import os
import sys
from dotenv import load_dotenv
from hiero_sdk_python import (
Client,
AccountId,
PrivateKey,
Network,
TopicMessageSubmitTransaction,
TopicCreateTransaction,
ResponseCode
)
load_dotenv()
def setup_client():
"""Initialize and set up the client with operator account"""
print("Connecting to Hedera testnet...")
client = Client(Network(os.getenv('NETWORK')))
try:
operator_id = AccountId.from_string(os.getenv('OPERATOR_ID'))
operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY'))
client.set_operator(operator_id, operator_key)
return client, operator_id, operator_key
except (TypeError, ValueError):
print("❌ Error: Creating client, Please check your .env file")
sys.exit(1)
def create_topic(client, operator_key):
"""Create a new topic"""
print("\nSTEP 1: Creating a Topic...")
try:
topic_tx = (
TopicCreateTransaction(
memo="Python SDK created topic",
admin_key=operator_key.public_key()
)
.freeze_with(client)
.sign(operator_key)
)
topic_receipt = topic_tx.execute(client)
topic_id = topic_receipt.topic_id
print(f"✅ Success! Created topic: {topic_id}")
return topic_id
except Exception as e:
print(f"❌ Error: Creating topic: {e}")
sys.exit(1)
def submit_topic_message_transaction(client, topic_id, message, operator_key):
"""Submit a message to the specified topic"""
print("\nSTEP 2: Submitting message...")
transaction = (
TopicMessageSubmitTransaction(topic_id=topic_id, message=message)
.freeze_with(client)
.sign(operator_key)
)
try:
receipt = transaction.execute(client)
print(f"Message Submit Transaction completed: "
f"(status: {ResponseCode(receipt.status).name}, "
f"transaction_id: {receipt.transaction_id})")
print(f"✅ Success! Message submitted to topic {topic_id}: {message}")
except Exception as e:
print(f"❌ Error: Message submission failed: {str(e)}")
sys.exit(1)
def main():
"""
A example to create a topic and then submit a message to it.
"""
message = "Hello, Hiero!"
# Config Client
client, _, operator_key = setup_client()
# Create a new Topic
topic_id = create_topic(client, operator_key)
# Submit message to topic
submit_topic_message_transaction(client, topic_id, message, operator_key)
if __name__ == "__main__":
main()