echo_bot.pyΒΆ

 1import asyncio
 2import logging
 3
 4from whatsapp.bot import WhatsappBot, bot_options_parser
 5from whatsapp.messages import Incoming, MessageTypes, TextMessage
 6from whatsapp.utils import read_message
 7
 8# Enable logging
 9logging.basicConfig(
10    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
11)
12
13logger = logging.getLogger(__name__)
14
15START = range(1)
16
17@read_message
18async def echo (bot: WhatsappBot, incoming: Incoming) -> int:
19    """
20    Echo function to send the same message back to the user.
21
22    :param bot: WhatsappBot instance.
23    :param incoming: Incoming message object.
24    :return: Next bot state
25    """
26    echo_msg = None
27
28    match incoming.message.type:
29        case MessageTypes.TEXT:
30            echo_msg = TextMessage.to_send(incoming.message.from_, incoming.message.message_value)
31
32    try:
33        await bot.send_message(echo_msg, incoming.metadata.phone_number_id)
34
35    except Exception as exc:
36        logger.error(f"Error sending message: {exc}")
37
38    # Returns to initial state
39    return START
40
41async def main (args: list[str] = None):
42    # Parse args from terminal, like "python echo_bot.py --phone_number_id=1234567890"
43    user_args = bot_options_parser.parse_args(args)
44    user_args_as_kwargs = dict(user_args._get_kwargs())
45
46    bot: WhatsappBot = WhatsappBot.from_dict(user_args_as_kwargs)
47
48    # Add a new state to the bot, that captures all text messages
49    bot.add_new_state(START, echo, MessageTypes.TEXT)
50
51    # Start webhook server in a separeted Thread
52    bot.start_webhook()
53
54    # Verify updates in shared queue
55    await bot.run_forever()
56
57if __name__ == "__main__":
58    asyncio.run(main())