๐Ÿค– Demo Bots#

This page contains some examples of bots you can create using pywa. Every example is a complete working bot that you can run on your own server.

๐Ÿ‘‹ Hello Bot#

This is a simple bot that welcomes the user when they send a message.

 1import flask  # pip3 install flask
 2from pywa import WhatsApp
 3from pywa.types import Message
 4
 5flask_app = flask.Flask(__name__)
 6
 7wa = WhatsApp(
 8    phone_id='your_phone_number',
 9    token='your_token',
10    server=flask_app,
11    verify_token='xyzxyz',
12)
13
14@wa.on_message()
15def hello(_: WhatsApp, msg: Message):
16    msg.react('๐Ÿ‘‹')
17    msg.reply(f'Hello {msg.from_user.name}!')
18
19# Run the server
20flask_app.run()

๐Ÿ“ Echo Bot#

This is a simple bot that echoes back the userโ€™s message.

 1import flask  # pip3 install flask
 2from pywa import WhatsApp
 3from pywa.types import Message
 4
 5flask_app = flask.Flask(__name__)
 6
 7wa = WhatsApp(
 8    phone_id='your_phone_number',
 9    token='your_token',
10    server=flask_app,
11    verify_token='xyzxyz',
12)
13
14@wa.on_message()
15def echo(_: WhatsApp, msg: Message):
16    try:
17        msg.copy(to=msg.from_user.wa_id, reply_to_message_id=msg.message_id_to_reply)
18    except ValueError:
19        msg.reply_text("I can't echo this message")
20
21# Run the server
22flask_app.run()

โฌ†๏ธ Url Uploader Bot#

This is a simple bot that uploads files from URLs.

 1import flask  # pip3 install flask
 2from pywa import WhatsApp, filters, errors
 3from pywa.types import Message, MessageStatus
 4
 5flask_app = flask.Flask(__name__)
 6
 7wa = WhatsApp(
 8    phone_id='your_phone_number',
 9    token='your_token',
10    server=flask_app,
11    verify_token='xyzxyz',
12)
13
14@wa.on_message(filters.startswith('http'))
15def download(_: WhatsApp, msg: Message):
16    msg.reply_document(msg.text, filename=msg.text.split('/')[-1])
17
18# When a file fails to download/upload, the bot will reply with an error message.
19@wa.on_message_status(filters.message_status.failed_with(errors.MediaDownloadError, errors.MediaUploadError))
20def on_media_download_error(_: WhatsApp, status: MessageStatus):
21    status.reply_text(f"I can't download/upload this file: {status.error.details}")
22
23# Run the server
24flask_app.run()

๐Ÿ”ข Calculator WhatsApp Bot#

This is a simple calculator bot for WhatsApp. It can perform basic arithmetic operations on integers.

Usage:

>>> 1 + 2
>>> 1 - 2
>>> 1 * 2
>>> 1 / 2
import re
import flask  # pip3 install flask
from pywa import WhatsApp, filters
from pywa.types import Message

flask_app = flask.Flask(__name__)

wa = WhatsApp(
    phone_id='your_phone_number',
    token='your_token',
    server=flask_app,
    verify_token='xyzxyz',
)

pattern = re.compile(r'^(\d+)\s*([+*/-])\s*(\d+)$')

@wa.on_message(filters.regex(pattern))
def calculator(_: WhatsApp, msg: Message):
    a, op, b = re.match(pattern, msg.text).groups()
    a, b = int(a), int(b)
    match op:
        case '+':
            result = a + b
        case '-':
            result = a - b
        case '*':
            result = a * b
        case '/':
            try:
                result = a / b
            except ZeroDivisionError:
                msg.react('โŒ')
                msg.reply('Division by zero is not allowed')
                return
        case _:
            msg.react('โŒ')
            msg.reply('Unknown operator')
            return
    msg.reply(f'{a} {op} {b} = *{result}*')

# Run the server
flask_app.run()

๐ŸŒ Translator Bot#

A simple WhatsApp bot that translates text messages to other languages.

 1import logging
 2import flask  # pip3 install flask
 3import googletrans  # pip3 install googletrans==4.0.0-rc1
 4from pywa import WhatsApp, filters
 5from pywa.types import Message, SectionList, CallbackSelection, Section, SectionRow
 6
 7flask_app = flask.Flask(__name__)
 8translator = googletrans.Translator()
 9
10wa = WhatsApp(
11    phone_id='your_phone_number',
12    token='your_token',
13    server=flask_app,
14    verify_token='xyzxyz',
15)
16
17MESSAGE_ID_TO_TEXT: dict[str, str] = {}  # msg_id -> text
18POPULAR_LANGUAGES = {
19    "en": ("English", "๐Ÿ‡บ๐Ÿ‡ธ"),
20    "es": ("Espaรฑol", "๐Ÿ‡ช๐Ÿ‡ธ"),
21    "fr": ("Franรงais", "๐Ÿ‡ซ๐Ÿ‡ท")
22}
23OTHER_LANGUAGES = {
24    "iw": ("ืขื‘ืจื™ืช", "๐Ÿ‡ฎ๐Ÿ‡ฑ"),
25    "ar": ("ุงู„ุนุฑุจูŠุฉ", "๐Ÿ‡ธ๐Ÿ‡ฆ"),
26    "ru": ("ะ ัƒััะบะธะน", "๐Ÿ‡ท๐Ÿ‡บ"),
27    "de": ("Deutsch", "๐Ÿ‡ฉ๐Ÿ‡ช"),
28    "it": ("Italiano", "๐Ÿ‡ฎ๐Ÿ‡น"),
29    "pt": ("Portuguรชs", "๐Ÿ‡ต๐Ÿ‡น"),
30    "ja": ("ๆ—ฅๆœฌ่ชž", "๐Ÿ‡ฏ๐Ÿ‡ต"),
31}
32
33
34@wa.on_message(filters.text)
35def offer_translation(_: WhatsApp, msg: Message):
36    msg_id = msg.reply_text(
37        text='Choose language to translate to:',
38        buttons=SectionList(
39            button_title='๐ŸŒ Choose Language',
40            sections=[
41                Section(
42                    title="๐ŸŒŸ Popular languages",
43                    rows=[
44                        SectionRow(
45                            title=f"{flag} {name}",
46                            callback_data=f"translate:{code}",
47                        )
48                        for code, (name, flag) in POPULAR_LANGUAGES.items()
49                    ],
50                ),
51                Section(
52                    title="๐ŸŒ Other languages",
53                    rows=[
54                        SectionRow(
55                            title=f"{flag} {name}",
56                            callback_data=f"translate:{code}",
57                        )
58                        for code, (name, flag) in OTHER_LANGUAGES.items()
59                    ],
60                ),
61            ]
62        )
63    )
64    # Save the message ID so we can use it later to get the original text.
65    MESSAGE_ID_TO_TEXT[msg_id] = msg.text
66
67@wa.on_callback_selection(filters.startswith('translate:'))
68def translate(_: WhatsApp, sel: CallbackSelection):
69    lang_code = sel.data.split(':')[-1]
70    try:
71        # every CallbackSelection has a reference to the original message (the selection's message)
72        original_text = MESSAGE_ID_TO_TEXT[sel.reply_to_message.message_id]
73    except KeyError:  # If the bot was restarted, the message ID is no longer valid.
74        sel.react('โŒ')
75        sel.reply_text(
76            text='Original message not found. Please send a new message.'
77        )
78        return
79    try:
80        translated = translator.translate(original_text, dest=lang_code)
81    except Exception as e:
82        sel.react('โŒ')
83        sel.reply_text(
84            text='An error occurred. Please try again.'
85        )
86        logging.exception(e)
87        return
88
89    sel.reply_text(
90        text=f"Translated to {translated.dest}:\n{translated.text}"
91    )
92
93
94# Run the server
95flask_app.run()

๐Ÿ–ผ Random image bot#

This example shows how to create a simple bot that replies with a random image from Unsplash.

 1import requests
 2import flask
 3from pywa import WhatsApp
 4from pywa.types import Message, ButtonUrl
 5
 6flask_app = flask.Flask(__name__)
 7
 8wa = WhatsApp(
 9    phone_id='your_phone_number',
10    token='your_token',
11    server=flask_app,
12    verify_token='xyzxyz',
13)
14
15@wa.on_message()
16def send_random_image(_: WhatsApp, msg: Message):
17    msg.reply_image(
18        image='https://source.unsplash.com/random',
19        caption='๐Ÿ”„ Random image',
20        buttons=ButtonUrl(title='Unsplash', url='https://unsplash.com')
21    )
22
23# Run the server
24flask_app.run()

๐Ÿ“ธ Remove background from image#

This example shows how to create a bot that removes the background from an image using the remove.bg API.

 1import requests
 2import flask
 3from pywa import WhatsApp
 4from pywa.types import Message, ButtonUrl
 5
 6flask_app = flask.Flask(__name__)
 7
 8wa = WhatsApp(
 9    phone_id='your_phone_number',
10    token='your_token',
11    server=flask_app,
12    verify_token='xyzxyz',
13)
14
15REMOVEBG_API_KEY = "your_api_key"  # https://www.remove.bg/api
16
17
18def get_removed_bg_image(original_img: bytes) -> bytes:
19    url = "https://api.remove.bg/v1.0/removebg"
20    files = {'image_file': original_img}
21    data = {'size': 'auto'}
22    headers = {'X-Api-Key': REMOVEBG_API_KEY}
23    response = requests.post(url, files=files, data=data, headers=headers)
24    response.raise_for_status()
25    return response.content
26
27
28@wa.on_message(filters.image)
29def on_image(_: WhatsApp, msg: Message):
30    try:
31        original_img = msg.image.download(in_memory=True)
32        image = get_removed_bg_image(original_img)
33    except requests.HTTPError as e:
34        msg.reply_text(f"A error occurred")
35        logging.exception(e)
36        return
37    msg.reply_image(
38        image=image,
39        caption="Here you go",
40        mime_type='image/png',  # when sending bytes, you must specify the mime type
41    )
42
43# Run the server
44flask_app.run()