-
Notifications
You must be signed in to change notification settings - Fork 242
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add broadcast by protocol example (#165)
- Loading branch information
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
from uagents import Agent, Bureau, Context, Model, Protocol | ||
from uagents.setup import fund_agent_if_low | ||
|
||
# create agents | ||
# alice and bob will support the protocol | ||
# charles will try to reach all agents supporting the protocol | ||
alice = Agent(name="alice", seed="alice recovery phrase") | ||
bob = Agent(name="bob", seed="bob recovery phrase") | ||
charles = Agent(name="charles", seed="charles recovery phrase") | ||
|
||
fund_agent_if_low(alice.wallet.address()) | ||
fund_agent_if_low(bob.wallet.address()) | ||
fund_agent_if_low(charles.wallet.address()) | ||
|
||
|
||
class BroadcastExampleRequest(Model): | ||
pass | ||
|
||
|
||
class BroadcastExampleResponse(Model): | ||
text: str | ||
|
||
|
||
# define protocol | ||
proto = Protocol(name="proto", version="1.0") | ||
|
||
|
||
@proto.on_message(model=BroadcastExampleRequest, replies=BroadcastExampleResponse) | ||
async def handle_request(ctx: Context, sender: str, _msg: BroadcastExampleRequest): | ||
await ctx.send(sender, BroadcastExampleResponse(text=f"Hello from {ctx.name}")) | ||
|
||
|
||
# include protocol | ||
# Note: after the first registration on the almanac smart contract, it will | ||
# take about 5 minutes before the agents can be found through the protocol | ||
alice.include(proto) | ||
bob.include(proto) | ||
|
||
|
||
# let charles send the message to all agents supporting the protocol | ||
@charles.on_interval(period=5) | ||
async def say_hello(ctx: Context): | ||
await ctx.experimental_broadcast(proto.digest, message=BroadcastExampleRequest()) | ||
|
||
|
||
@charles.on_message(model=BroadcastExampleResponse) | ||
async def handle_response(ctx: Context, sender: str, msg: BroadcastExampleResponse): | ||
ctx.logger.info(f"Received response from {sender}: {msg.text}") | ||
|
||
|
||
bureau = Bureau(port=8000, endpoint="http://localhost:8000/submit") | ||
bureau.add(alice) | ||
bureau.add(bob) | ||
bureau.add(charles) | ||
|
||
|
||
if __name__ == "__main__": | ||
bureau.run() |