๐Ÿค– 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, types
 3
 4flask_app = flask.Flask(__name__)
 5
 6wa = WhatsApp(
 7    phone_id='your_phone_number',
 8    token='your_token',
 9    server=flask_app,
10    verify_token='xyzxyz',
11)
12
13@wa.on_message
14def hello(_: WhatsApp, msg: types.Message):
15    msg.react('๐Ÿ‘‹')
16    msg.reply(f'Hello {msg.from_user.name}!')
17
18# Run the server
19flask_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, types
 3
 4flask_app = flask.Flask(__name__)
 5
 6wa = WhatsApp(
 7    phone_id='your_phone_number',
 8    token='your_token',
 9    server=flask_app,
10    verify_token='xyzxyz',
11)
12
13@wa.on_message
14def echo(_: WhatsApp, msg: types.Message):
15    try:
16        msg.copy(to=msg.sender, reply_to_message_id=msg.message_id_to_reply)
17    except ValueError:
18        msg.reply_text("I can't echo this message")
19
20# Run the server
21flask_app.run()

โฌ†๏ธ Url Uploader Bot#

This is a simple bot that uploads files from URLs.

 1import flask  # pip3 install flask
 2from pywa import WhatsApp, types, 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: types.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.failed_with(errors.MediaDownloadError, errors.MediaUploadError))
20def on_media_download_error(_: WhatsApp, status: types.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, types, filters

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: types.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, types, filters
 5
 6flask_app = flask.Flask(__name__)
 7translator = googletrans.Translator()
 8
 9wa = WhatsApp(
10    phone_id='your_phone_number',
11    token='your_token',
12    server=flask_app,
13    verify_token='xyzxyz',
14)
15
16MESSAGE_ID_TO_TEXT: dict[str, str] = {}  # msg_id -> text
17POPULAR_LANGUAGES = {
18    "en": ("English", "๐Ÿ‡บ๐Ÿ‡ธ"),
19    "es": ("Espaรฑol", "๐Ÿ‡ช๐Ÿ‡ธ"),
20    "fr": ("Franรงais", "๐Ÿ‡ซ๐Ÿ‡ท")
21}
22OTHER_LANGUAGES = {
23    "iw": ("ืขื‘ืจื™ืช", "๐Ÿ‡ฎ๐Ÿ‡ฑ"),
24    "ar": ("ุงู„ุนุฑุจูŠุฉ", "๐Ÿ‡ธ๐Ÿ‡ฆ"),
25    "ru": ("ะ ัƒััะบะธะน", "๐Ÿ‡ท๐Ÿ‡บ"),
26    "de": ("Deutsch", "๐Ÿ‡ฉ๐Ÿ‡ช"),
27    "it": ("Italiano", "๐Ÿ‡ฎ๐Ÿ‡น"),
28    "pt": ("Portuguรชs", "๐Ÿ‡ต๐Ÿ‡น"),
29    "ja": ("ๆ—ฅๆœฌ่ชž", "๐Ÿ‡ฏ๐Ÿ‡ต"),
30}
31
32
33@wa.on_message(filters.text)
34def offer_translation(_: WhatsApp, msg: types.Message):
35    msg_id = msg.reply_text(
36        text='Choose language to translate to:',
37        buttons=types.SectionList(
38            button_title='๐ŸŒ Choose Language',
39            sections=[
40                types.Section(
41                    title="๐ŸŒŸ Popular languages",
42                    rows=[
43                        types.SectionRow(
44                            title=f"{flag} {name}",
45                            callback_data=f"translate:{code}",
46                        )
47                        for code, (name, flag) in POPULAR_LANGUAGES.items()
48                    ],
49                ),
50                types.Section(
51                    title="๐ŸŒ Other languages",
52                    rows=[
53                        types.SectionRow(
54                            title=f"{flag} {name}",
55                            callback_data=f"translate:{code}",
56                        )
57                        for code, (name, flag) in OTHER_LANGUAGES.items()
58                    ],
59                ),
60            ]
61        )
62    )
63    # Save the message ID so we can use it later to get the original text.
64    MESSAGE_ID_TO_TEXT[msg_id] = msg.text
65
66@wa.on_callback_selection(filters.startswith('translate:'))
67def translate(_: WhatsApp, sel: types.CallbackSelection):
68    lang_code = sel.data.split(':')[-1]
69    try:
70        # every CallbackSelection has a reference to the original message (the selection's message)
71        original_text = MESSAGE_ID_TO_TEXT[sel.reply_to_message.message_id]
72    except KeyError:  # If the bot was restarted, the message ID is no longer valid.
73        sel.react('โŒ')
74        sel.reply_text(
75            text='Original message not found. Please send a new message.'
76        )
77        return
78    try:
79        translated = translator.translate(original_text, dest=lang_code)
80    except Exception as e:
81        sel.react('โŒ')
82        sel.reply_text(
83            text='An error occurred. Please try again.'
84        )
85        logging.exception(e)
86        return
87
88    sel.reply_text(
89        text=f"Translated to {translated.dest}:\n{translated.text}"
90    )
91
92
93# Run the server
94flask_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, types
 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 send_random_image(_: WhatsApp, msg: types.Message):
16    msg.reply_image(
17        image='https://source.unsplash.com/random',
18        caption='๐Ÿ”„ Random image',
19        buttons=types.ButtonUrl(title='Unsplash', url='https://unsplash.com')
20    )
21
22# Run the server
23flask_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, types
 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
14REMOVEBG_API_KEY = "your_api_key"  # https://www.remove.bg/api
15
16
17def get_removed_bg_image(original_img: bytes) -> bytes:
18    url = "https://api.remove.bg/v1.0/removebg"
19    files = {'image_file': original_img}
20    data = {'size': 'auto'}
21    headers = {'X-Api-Key': REMOVEBG_API_KEY}
22    response = requests.post(url, files=files, data=data, headers=headers)
23    response.raise_for_status()
24    return response.content
25
26
27@wa.on_message(filters.image)
28def on_image(_: WhatsApp, msg: types.Message):
29    try:
30        original_img = msg.image.download(in_memory=True)
31        image = get_removed_bg_image(original_img)
32    except requests.HTTPError as e:
33        msg.reply_text(f"A error occurred")
34        logging.exception(e)
35        return
36    msg.reply_image(
37        image=image,
38        caption="Here you go",
39        mime_type='image/png',  # when sending bytes, you must specify the mime type
40    )
41
42# Run the server
43flask_app.run()