/
demo-bots.rst
354 lines (275 loc) · 9.64 KB
/
demo-bots.rst
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
🤖 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.
.. code-block:: python
:linenos:
import flask # pip3 install flask
from pywa import WhatsApp
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',
)
@wa.on_message()
def hello(_: WhatsApp, msg: Message):
msg.react('👋')
msg.reply(f'Hello {msg.from_user.name}!')
# Run the server
flask_app.run()
📝 Echo Bot
-----------
This is a simple bot that echoes back the user's message.
.. code-block:: python
:linenos:
import flask # pip3 install flask
from pywa import WhatsApp
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',
)
@wa.on_message()
def echo(_: WhatsApp, msg: Message):
try:
msg.copy(to=msg.from_user.wa_id, reply_to_message_id=msg.message_id_to_reply)
except ValueError:
msg.reply_text("I can't echo this message")
# Run the server
flask_app.run()
⬆️ Url Uploader Bot
--------------------
This is a simple bot that uploads files from URLs.
.. code-block:: python
:linenos:
import flask # pip3 install flask
from pywa import WhatsApp, filters, errors
from pywa.types import Message, MessageStatus
flask_app = flask.Flask(__name__)
wa = WhatsApp(
phone_id='your_phone_number',
token='your_token',
server=flask_app,
verify_token='xyzxyz',
)
@wa.on_message(filters.startswith('http'))
def download(_: WhatsApp, msg: Message):
msg.reply_document(msg.text, filename=msg.text.split('/')[-1])
# When a file fails to download/upload, the bot will reply with an error message.
@wa.on_message_status(filters.message_status.failed_with(errors.MediaDownloadError, errors.MediaUploadError))
def on_media_download_error(_: WhatsApp, status: MessageStatus):
status.reply_text(f"I can't download/upload this file: {status.error.details}")
# Run the server
flask_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
.. code-block:: python
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.
.. code-block:: python
:linenos:
import logging
import flask # pip3 install flask
import googletrans # pip3 install googletrans==4.0.0-rc1
from pywa import WhatsApp, filters
from pywa.types import Message, SectionList, CallbackSelection, Section, SectionRow
flask_app = flask.Flask(__name__)
translator = googletrans.Translator()
wa = WhatsApp(
phone_id='your_phone_number',
token='your_token',
server=flask_app,
verify_token='xyzxyz',
)
MESSAGE_ID_TO_TEXT: dict[str, str] = {} # msg_id -> text
POPULAR_LANGUAGES = {
"en": ("English", "🇺🇸"),
"es": ("Español", "🇪🇸"),
"fr": ("Français", "🇫🇷")
}
OTHER_LANGUAGES = {
"iw": ("עברית", "🇮🇱"),
"ar": ("العربية", "🇸🇦"),
"ru": ("Русский", "🇷🇺"),
"de": ("Deutsch", "🇩🇪"),
"it": ("Italiano", "🇮🇹"),
"pt": ("Português", "🇵🇹"),
"ja": ("日本語", "🇯🇵"),
}
@wa.on_message(filters.text)
def offer_translation(_: WhatsApp, msg: Message):
msg_id = msg.reply_text(
text='Choose language to translate to:',
buttons=SectionList(
button_title='🌐 Choose Language',
sections=[
Section(
title="🌟 Popular languages",
rows=[
SectionRow(
title=f"{flag} {name}",
callback_data=f"translate:{code}",
)
for code, (name, flag) in POPULAR_LANGUAGES.items()
],
),
Section(
title="🌐 Other languages",
rows=[
SectionRow(
title=f"{flag} {name}",
callback_data=f"translate:{code}",
)
for code, (name, flag) in OTHER_LANGUAGES.items()
],
),
]
)
)
# Save the message ID so we can use it later to get the original text.
MESSAGE_ID_TO_TEXT[msg_id] = msg.text
@wa.on_callback_selection(filters.startswith('translate:'))
def translate(_: WhatsApp, sel: CallbackSelection):
lang_code = sel.data.split(':')[-1]
try:
# every CallbackSelection has a reference to the original message (the selection's message)
original_text = MESSAGE_ID_TO_TEXT[sel.reply_to_message.message_id]
except KeyError: # If the bot was restarted, the message ID is no longer valid.
sel.react('❌')
sel.reply_text(
text='Original message not found. Please send a new message.'
)
return
try:
translated = translator.translate(original_text, dest=lang_code)
except Exception as e:
sel.react('❌')
sel.reply_text(
text='An error occurred. Please try again.'
)
logging.exception(e)
return
sel.reply_text(
text=f"Translated to {translated.dest}:\n{translated.text}"
)
# Run the server
flask_app.run()
🖼 Random image bot
-------------------
This example shows how to create a simple bot that replies with a random image from Unsplash.
.. code-block:: python
:linenos:
import requests
import flask
from pywa import WhatsApp
from pywa.types import Message, ButtonUrl
flask_app = flask.Flask(__name__)
wa = WhatsApp(
phone_id='your_phone_number',
token='your_token',
server=flask_app,
verify_token='xyzxyz',
)
@wa.on_message()
def send_random_image(_: WhatsApp, msg: Message):
msg.reply_image(
image='https://source.unsplash.com/random',
caption='🔄 Random image',
buttons=ButtonUrl(title='Unsplash', url='https://unsplash.com')
)
# Run the server
flask_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.
.. code-block:: python
:linenos:
import requests
import flask
from pywa import WhatsApp
from pywa.types import Message, ButtonUrl
flask_app = flask.Flask(__name__)
wa = WhatsApp(
phone_id='your_phone_number',
token='your_token',
server=flask_app,
verify_token='xyzxyz',
)
REMOVEBG_API_KEY = "your_api_key" # https://www.remove.bg/api
def get_removed_bg_image(original_img: bytes) -> bytes:
url = "https://api.remove.bg/v1.0/removebg"
files = {'image_file': original_img}
data = {'size': 'auto'}
headers = {'X-Api-Key': REMOVEBG_API_KEY}
response = requests.post(url, files=files, data=data, headers=headers)
response.raise_for_status()
return response.content
@wa.on_message(filters.image)
def on_image(_: WhatsApp, msg: Message):
try:
original_img = msg.image.download(in_memory=True)
image = get_removed_bg_image(original_img)
except requests.HTTPError as e:
msg.reply_text(f"A error occurred")
logging.exception(e)
return
msg.reply_image(
image=image,
caption="Here you go",
mime_type='image/png', # when sending bytes, you must specify the mime type
)
# Run the server
flask_app.run()