-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_bot.py
More file actions
105 lines (79 loc) · 3.88 KB
/
Copy pathbasic_bot.py
File metadata and controls
105 lines (79 loc) · 3.88 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
"""Basic Echo Bot — replies to every text message.
Commands:
ping -> reply pong
help -> show available commands
time -> show current server time
info -> show sender info
"""
import asyncio
import os
from datetime import datetime, timezone
from tryx.backend import SqliteStore
from tryx.client import Tryx, TryxClient
from tryx.events import EvMessage, EvPairingQrCode
DB_PATH = os.getenv("TRYX_DB_PATH", "whatsapp.db")
def jid_to_text(jid: object) -> str:
"""Format a JID object as user@server string."""
user = getattr(jid, "user", "")
server = getattr(jid, "server", "")
return f"{user}@{server}"
# ── Setup ────────────────────────────────────────────────────────────────────
backend = SqliteStore(DB_PATH)
app = Tryx(backend)
@app.on(EvPairingQrCode)
async def on_pairing_qr(_client: TryxClient, event: EvPairingQrCode) -> None:
"""Display the QR code for initial device pairing."""
print("=" * 40)
print("Scan this QR code with WhatsApp:")
print(event.code)
print("=" * 40)
@app.on(EvMessage)
async def on_message(client: TryxClient, event: EvMessage) -> None:
"""Handle incoming messages and dispatch commands."""
data = event.data
info = data.message_info
source = info.source
chat_jid = source.chat
sender_jid = source.sender
text = (data.get_text() or "").strip()
sender = jid_to_text(sender_jid)
chat = jid_to_text(chat_jid)
print(f"[message] from={sender} chat={chat} text={text!r}")
if not text:
return
cmd = text.lower()
# ── /ping ────────────────────────────────────────────────────────────
if cmd == "ping":
await client.chatstate.send_composing(chat_jid)
await asyncio.sleep(1) # Simulate processing
await client.send_text(chat_jid, "pong", quoted=event)
await client.chatstate.send_paused(chat_jid)
# ── /help ────────────────────────────────────────────────────────────
elif cmd == "help":
help_text = (
"*Available Commands*\n\n"
"• ping — check if bot is alive\n"
"• help — show this message\n"
"• time — show current time\n"
"• info — show your info"
)
await client.send_text(chat_jid, help_text, quoted=event)
# ── /time ────────────────────────────────────────────────────────────
elif cmd == "time":
now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
await client.send_text(chat_jid, f"Current time: {now}", quoted=event)
# ── /info ────────────────────────────────────────────────────────────
elif cmd == "info":
info_lines = [
"*Your Info*",
f"• JID: {jid_to_text(sender_jid)}",
f"• Chat: {jid_to_text(chat_jid)}",
f"• Push name: {info.push_name or '(none)'}",
]
await client.send_text(chat_jid, "\n".join(info_lines), quoted=event)
# ── Entry point ──────────────────────────────────────────────────────────────
async def main() -> None:
print(f"Starting basic bot with DB: {DB_PATH}")
await app.run()
if __name__ == "__main__":
asyncio.run(main())