๐ค Demo Bots#
This page contains complete, working examples of bots you can create using pywa.
๐ Hello Bot#
This is a simple bot that welcomes the user when they send a message.
1from pywa import WhatsApp, types
2
3wa = WhatsApp(
4 phone_id='your_phone_number',
5 token='your_token',
6 verify_token='xyzxyz',
7)
8
9@wa.on_message
10def hello(_: WhatsApp, msg: types.Message):
11 msg.react('๐')
12 msg.reply(f'Hello {msg.from_user.name}!')
13
14# Run the server with `pywa dev`
๐ Echo Bot#
This is a simple bot that echoes back the userโs message.
1from pywa import WhatsApp, types
2
3wa = WhatsApp(
4 phone_id='your_phone_number',
5 token='your_token',
6 verify_token='xyzxyz',
7)
8
9@wa.on_message
10def echo(_: WhatsApp, msg: types.Message):
11 try:
12 msg.copy(to=msg.sender, reply_to_message_id=msg.message_id_to_reply)
13 except ValueError:
14 msg.reply("I can't echo this message")
15
16# Run the server with `pywa dev`
โฌ๏ธ Url Uploader Bot#
This is a simple bot that uploads files from URLs.
1from pywa import WhatsApp, types, filters, errors
2
3wa = WhatsApp(
4 phone_id='your_phone_number',
5 token='your_token',
6 verify_token='xyzxyz',
7)
8
9@wa.on_message(filters.startswith('http'))
10def download(_: WhatsApp, msg: types.Message):
11 msg.reply_document(msg.text, filename=msg.text.split('/')[-1])
12
13# When a file fails to download/upload, the bot will reply with an error message.
14@wa.on_message_status(filters.failed_with(errors.MediaDownloadError, errors.MediaUploadError))
15def on_media_download_error(_: WhatsApp, status: types.MessageStatus):
16 status.reply(f"I can't download/upload this file: {status.error.details}")
17
18# Run the server with `pywa dev`
๐ข 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
from pywa import WhatsApp, types, filters
wa = WhatsApp(
phone_id='your_phone_number',
token='your_token',
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 with `pywa dev`
๐ Translator Bot#
A simple WhatsApp bot that translates text messages to other languages.
1import logging
2import googletrans # pip3 install googletrans==4.0.0-rc1
3from pywa import WhatsApp, types, filters
4
5translator = googletrans.Translator()
6
7wa = WhatsApp(
8 phone_id='your_phone_number',
9 token='your_token',
10 verify_token='xyzxyz',
11)
12
13MESSAGE_ID_TO_TEXT: dict[str, str] = {} # msg_id -> text
14POPULAR_LANGUAGES = {
15 "en": ("English", "๐บ๐ธ"),
16 "es": ("Espaรฑol", "๐ช๐ธ"),
17 "fr": ("Franรงais", "๐ซ๐ท")
18}
19OTHER_LANGUAGES = {
20 "iw": ("ืขืืจืืช", "๐ฎ๐ฑ"),
21 "ar": ("ุงูุนุฑุจูุฉ", "๐ธ๐ฆ"),
22 "ru": ("ะ ัััะบะธะน", "๐ท๐บ"),
23 "de": ("Deutsch", "๐ฉ๐ช"),
24 "it": ("Italiano", "๐ฎ๐น"),
25 "pt": ("Portuguรชs", "๐ต๐น"),
26 "ja": ("ๆฅๆฌ่ช", "๐ฏ๐ต"),
27}
28
29
30@wa.on_message(filters.text)
31def offer_translation(_: WhatsApp, msg: types.Message):
32 msg_id = msg.reply(
33 text='Choose language to translate to:',
34 buttons=types.SectionList(
35 button_title='๐ Choose Language',
36 sections=[
37 types.Section(
38 title="๐ Popular languages",
39 rows=[
40 types.SectionRow(
41 title=f"{flag} {name}",
42 callback_data=f"translate:{code}",
43 )
44 for code, (name, flag) in POPULAR_LANGUAGES.items()
45 ],
46 ),
47 types.Section(
48 title="๐ Other languages",
49 rows=[
50 types.SectionRow(
51 title=f"{flag} {name}",
52 callback_data=f"translate:{code}",
53 )
54 for code, (name, flag) in OTHER_LANGUAGES.items()
55 ],
56 ),
57 ]
58 )
59 )
60 # Save the message ID so we can use it later to get the original text.
61 MESSAGE_ID_TO_TEXT[msg_id] = msg.text
62
63@wa.on_callback_selection(filters.startswith('translate:'))
64def translate(_: WhatsApp, sel: types.CallbackSelection):
65 lang_code = sel.data.split(':')[-1]
66 try:
67 # every CallbackSelection has a reference to the original message (the selection's message)
68 original_text = MESSAGE_ID_TO_TEXT[sel.reply_to_message.message_id]
69 except KeyError: # If the bot was restarted, the message ID is no longer valid.
70 sel.react('โ')
71 sel.reply(
72 text='Original message not found. Please send a new message.'
73 )
74 return
75 try:
76 translated = translator.translate(original_text, dest=lang_code)
77 except Exception as e:
78 sel.react('โ')
79 sel.reply(
80 text='An error occurred. Please try again.'
81 )
82 logging.exception(e)
83 return
84
85 sel.reply(
86 text=f"Translated to {translated.dest}:\n{translated.text}"
87 )
88
89
90# Run the server with `pywa dev`
๐ผ Random image bot#
This example shows how to create a simple bot that replies with a random image from Unsplash.
1from pywa import WhatsApp, types
2
3wa = WhatsApp(
4 phone_id='your_phone_number',
5 token='your_token',
6 verify_token='xyzxyz',
7)
8
9@wa.on_message
10def send_random_image(_: WhatsApp, msg: types.Message):
11 msg.reply_image(
12 image='https://source.unsplash.com/random',
13 caption='๐ Random image',
14 buttons=types.ButtonUrl(title='Unsplash', url='https://unsplash.com')
15 )
16
17# Run the server with `pywa dev`
๐ธ 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 logging
2import httpx
3from pywa import WhatsApp, types
4
5wa = WhatsApp(
6 phone_id='your_phone_number',
7 token='your_token',
8 verify_token='xyzxyz',
9)
10
11REMOVEBG_API_KEY = "your_api_key" # https://www.remove.bg/api
12
13
14def get_removed_bg_image(original_img: bytes) -> bytes:
15 url = "https://api.remove.bg/v1.0/removebg"
16 files = {'image_file': original_img}
17 data = {'size': 'auto'}
18 headers = {'X-Api-Key': REMOVEBG_API_KEY}
19 response = httpx.post(url, files=files, data=data, headers=headers)
20 response.raise_for_status()
21 return response.content
22
23
24@wa.on_message(filters.image)
25def on_image(_: WhatsApp, msg: types.Message):
26 try:
27 original_img = msg.image.download(in_memory=True)
28 image = get_removed_bg_image(original_img)
29 except httpx.HTTPError as e:
30 msg.reply("An error occurred")
31 logging.exception(e)
32 return
33 msg.reply_image(
34 image=image,
35 caption="Here you go",
36 mime_type='image/png', # when sending bytes, you must specify the mime type
37 )
38
39# Run the server with `pywa dev`