-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecho_bot.py
More file actions
128 lines (102 loc) · 4.51 KB
/
Copy pathecho_bot.py
File metadata and controls
128 lines (102 loc) · 4.51 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
"""Echo bot example — functional verification of imbot-sdk-python.
Connects to JuggleIM, listens for messages, and echoes any received text
message back to its conversation. Optionally sends one greeting message at
startup to a target you specify.
Usage:
export IMBOT_TOKEN="<your-user-token>"
# optional: send a greeting to a user/group on startup
export IMBOT_TARGET="<target-user-id>"
python -m examples.echo_bot
# or
python examples/echo_bot.py --token <token> --target <target-user-id>
Get a user token from your JuggleIM console / app server (the server-side
admin API mints tokens with your AppKey + AppSecret).
"""
import argparse
import os
import sys
import time
# Allow running directly from the repo root without installing.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from imbot_sdk import ( # noqa: E402
ClientErrorCode,
ConnectState,
Conversation,
ImBotClient,
MessageListener,
ConnectionStatusChangeListener,
messages,
)
from imbot_sdk.pb import appmessages_pb2 as pb # noqa: E402
# Test environment provided by JuggleIM.
DEFAULT_ADDRESS = "wss://127.0.0.1"
DEFAULT_APPKEY = "AppKey"
class ConnListener(ConnectionStatusChangeListener):
def on_status_change(self, status: ConnectState, code: int) -> None:
print(f"[conn] status={status.name} code={code}")
class EchoListener(MessageListener):
def __init__(self, client: ImBotClient) -> None:
self.client = client
def on_message_receive(self, msg) -> None:
content = msg.msg_content
target = msg.conversation.conversation if msg.conversation else ""
if isinstance(content, messages.TextMessage):
print(f"[recv] from={msg.sender_id} target={target} "
f"msgId={msg.msg_id} text={content.content!r}")
# Don't echo our own messages or empty text.
if msg.sender_id and msg.sender_id != self.client.user_id and content.content:
self._echo(msg, content.content)
else:
print(f"[recv] from={msg.sender_id} target={target} "
f"msgId={msg.msg_id} type={msg.msg_type}")
def _echo(self, msg, text: str) -> None:
reply = messages.TextMessage(f"echo: {text}")
up = self.client.build_up_msg(reply, client_uid=f"echo-{time.time_ns()}")
code, ack = self.client.send_message(msg.conversation, up)
if code == ClientErrorCode.SUCCESS:
print(f"[send] echoed -> msgId={ack.msgId} seq={ack.msgSeqNo}")
else:
print(f"[send] echo failed code={code}")
def main() -> int:
parser = argparse.ArgumentParser(description="JuggleIM echo bot example")
parser.add_argument("--address", default=os.getenv("IMBOT_ADDRESS", DEFAULT_ADDRESS))
parser.add_argument("--appkey", default=os.getenv("IMBOT_APPKEY", DEFAULT_APPKEY))
parser.add_argument("--token", default=os.getenv("IMBOT_TOKEN", ""))
parser.add_argument("--target", default=os.getenv("IMBOT_TARGET", ""),
help="optional user id to greet on startup")
args = parser.parse_args()
if not args.token:
print("error: a user token is required (set IMBOT_TOKEN or pass --token)",
file=sys.stderr)
return 2
client = ImBotClient(args.address, args.appkey)
client.add_connection_status_change_listener(ConnListener())
client.add_message_listener(EchoListener(client))
def on_disconnect(code, dis_msg):
print(f"[disconnect] code={code} ext={dis_msg.ext!r}")
client.disconnect_callback = on_disconnect
code, ack = client.connect(args.token)
if code != ClientErrorCode.SUCCESS:
print(f"connect failed: code={code}", file=sys.stderr)
return 1
print(f"connected: userId={ack.userId} session={ack.session}")
if args.target:
text = messages.TextMessage("hello from imbot-sdk-python")
up = client.build_up_msg(text, client_uid=f"greet-{time.time_ns()}")
conv = Conversation(conversation_type=pb.Private, conversation=args.target)
scode, sack = client.send_message(conv, up)
if scode == ClientErrorCode.SUCCESS:
print(f"greeting sent: msgId={sack.msgId} seq={sack.msgSeqNo}")
else:
print(f"greeting send failed: code={scode}")
print("listening for messages, press Ctrl+C to exit")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
client.disconnect()
return 0
if __name__ == "__main__":
raise SystemExit(main())