-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyowsup-cli
executable file
·313 lines (225 loc) · 12 KB
/
yowsup-cli
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
#!/usr/bin/python
'''
Copyright (c) <2012> Tarek Galal <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
__author__ = "Tarek Galal"
__version__ = "0.41"
__email__ = "[email protected]"
__license__ = "MIT"
import argparse, sys, os, csv
from Yowsup.Common.utilities import Utilities
from Yowsup.Common.debugger import Debugger
from Yowsup.Common.constants import Constants
from Examples.CmdClient import WhatsappCmdClient
from Examples.EchoClient import WhatsappEchoClient
from Examples.ListenerClient import WhatsappListenerClient
from Yowsup.Registration.v2.existsrequest import WAExistsRequest as WAExistsRequestV2
from Yowsup.Registration.v2.coderequest import WACodeRequest as WACodeRequestV2
from Yowsup.Registration.v2.regrequest import WARegRequest as WARegRequestV2
from Yowsup.Contacts.contacts import WAContactsSyncRequest
import threading,time, base64
DEFAULT_CONFIG = os.path.expanduser("~")+"/.yowsup/auth"
COUNTRIES_CSV = "countries.csv"
CONFIG_HELP = """\
Yowsup Configuration
====================
Your configuration should contain info about your login credentials to Whatsapp. This typically consist of 3 fields:\n
cc: Your country code. See http://www.ipipi.com/help/telephone-country-codes.htm
If not set, it will be autodetected from phonenumber
phone: Your full phone number including country code, without '+' or '00'
id: This field is used in registration calls (-r|-R|-e), and for login if you are trying to use an existing account that is setup \
on a physical device. Whatsapp has recently deprecated using IMEI/MAC to generate the account's password in updated versions\
of their clients. Typically this field should contain the phone's IMEI if your account is setup on \
a Nokia or an Android device, or the phone's WLAN's MAC Address for iOS devices. If you are not trying to use existing credentials\
or want to register, you can leave this field blank or set it to some random text.\
Do not change this field after registering using Yowsup
password: Password to use for login. You obtain this password when you register using Yowsup.
You can specify those variables using -c argument, as a path to a file containing this configuration.
Config file Example:
##/home/user/my_whatsapp_config.txt#
phone=201111111111
id=FF:FF:FF:FF:FF:FF
password=S1nBGCvZhb6TBQrbm2sQCfSLkXM=
#########
Usage Example for listening to incoming messages:
yowsup-cli -c /home/user/my_whatsapp_config.txt -l
You can also use config.example as a template
"""
def startDbusInterface():
from dbus.mainloop.glib import DBusGMainLoop
from Yowsup.Interfaces.DBus.DBusInterface import DBusInitInterface
import gobject
DBusGMainLoop(set_as_default=True)
DBusInitInterface()
mainloop = gobject.MainLoop()
gobject.threads_init()
print("starting")
mainloop.run()
def resultToString(result):
unistr = str if sys.version_info >= (3, 0) else unicode
out = []
for k, v in result.items():
if v is None:
continue
out.append("%s: %s" %(k, v.encode("utf-8") if type(v) is unistr else v))
return "\n".join(out)
def getCredentials(config = DEFAULT_CONFIG):
if os.path.isfile(config):
f = open(config)
phone = ""
idx = ""
pw = ""
cc = ""
try:
for l in f:
line = l.strip()
if len(line) and line[0] not in ('#',';'):
prep = line.split('#', 1)[0].split(';', 1)[0].split('=', 1)
varname = prep[0].strip()
val = prep[1].strip()
if varname == "phone":
phone = val
elif varname == "id":
idx = val
elif varname =="password":
pw =val
elif varname == "cc":
cc = val
return (cc, phone, idx, pw);
except:
pass
return 0
def dissectPhoneNumber(phoneNumber):
try:
with open(COUNTRIES_CSV, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
if len(row) == 3:
country, cc, mcc = row
else:
country,cc = row
mcc = "000"
try:
if phoneNumber.index(cc) == 0:
print("Detected cc: %s"%cc)
return (cc, phoneNumber[len(cc):])
except ValueError:
continue
except:
pass
return False
parser = argparse.ArgumentParser(description='yowsup-cli Command line options')
clientsGroup = parser.add_argument_group("Client options")
regGroup = parser.add_argument_group("Registration options")
modes = clientsGroup.add_mutually_exclusive_group()
modes.add_argument('-l','--listen', help='Listen to messages', action="store_true", required=False, default=False)
modes.add_argument('-s','--send', help="Send message to phone number and close connection. Phone is full number including country code, without '+' or '00'", action="store", nargs=2, metavar=('<phone>','<message>'), required=False)
modes.add_argument('-i','--interactive', help="Start an interactive conversation with a contact. Phone is full number including country code, without '+' or '00'", action="store", metavar='<phone>', required=False)
modes.add_argument('-b','--broadcast', help="Broadcast message to multiple recepients, comma seperated", action="store", nargs=2, metavar=('<jids>', '<message>'), required=False)
#modes.add_argument('-b','--bot', help='Bot', action="store_true", required=False, default=False)
clientsGroup.add_argument('-w','--wait', help='If used with -s, then connection will not close until server confirms reception of the message', action="store_true", required=False, default=False)
clientsGroup.add_argument('-a','--autoack', help='If used with -l or -i, then a message received ack would be automatically sent for received messages', action="store_true", required=False, default=False)
clientsGroup.add_argument('-k','--keepalive', help="When used with -l or -i, Yowsup will automatically respond to server's ping requests to keep connection alive", action="store_true", required=False, default=False)
regSteps = regGroup.add_mutually_exclusive_group()
regSteps.add_argument("-r", '--requestcode', help='Request the 3 digit registration code from Whatsapp.', action="store", required=False, metavar="(sms|voice)")
regSteps.add_argument("-R", '--register', help='Register account on Whatsapp using the provided 3 digit code', action="store", required=False, metavar="code")
regSteps.add_argument("-e", '--exists', help='Check if account credentials are valid. WARNING: Whatsapp now changes your password everytime you use this. Make sure you update your config file if the output informs about a password change', action="store_true", required=False)
contactOptions = parser.add_argument_group("Contacts options").add_mutually_exclusive_group();
contactOptions.add_argument('--sync', help='Sync provided numbers. Numbers should be comma-separated. If a number is not in international format, Whatsapp will assume your own country code for it. Returned data indicate which numbers are whatsapp users and which are not. For Whatsapp users, it will return some info about each user, like user status.', metavar="numbers", action="store", required=False)
debugTools = parser.add_argument_group("Debug tools").add_mutually_exclusive_group();
debugTools.add_argument('--generatepassword', help="Generate password from given string in same way Whatsapp generates it from a given IMEI or MAC Address", action="store", metavar="input")
debugTools.add_argument('--decodestring', help="Decode byte arrays found in decompiled version of Whatsapp. Tested with S40 version. Input should be comma separated without the enclosing brackets. Example: ./yowsup-cli --decodestring 112,61,100,123,114,103,96,114,99,99,61,125,118,103", action="store", metavar="encoded_array")
parser.add_argument("--help-config", help="Display info about configuration format", action="store_true")
parser.add_argument('-c','--config', help="Path to config file containing authentication info. For more info about config format use --help-config", action="store", metavar="file", required=False, default=False)
#parser.add_argument('-D','--dbus', help='Start DBUS interface', action="store_true", required=False, default=False)
parser.add_argument("--ignorecached", help="Don't use cached token if exists", action="store_true", required=False, default=False)
parser.add_argument('-d','--debug', help='Enable debug messages', action="store_true", required=False, default=False)
parser.add_argument('-v', '--version', help="Print version info and exit", action='store_true', required=False, default=False)
args = vars(parser.parse_args())
if len(sys.argv) == 1:
parser.print_help()
elif args["help_config"]:
print(CONFIG_HELP)
elif args["version"]:
print("yowsup-cli %s, using Yowsup %s"%(__version__, Constants.v))
else:
credentials = getCredentials(args["config"] or DEFAULT_CONFIG)
if credentials:
countryCode, login, identity, password = credentials
identity = Utilities.processIdentity(identity)
password = base64.b64decode(bytes(password.encode('utf-8')))
if countryCode:
phoneNumber = login[len(countryCode):]
else:
dissected = dissectPhoneNumber(login)
if not dissected:
sys.exit("ERROR. Couldn't detect cc, you have to manually place it your config")
countryCode, phoneNumber = dissected
Debugger.enabled = args['debug']
if args["ignorecached"]:
Utilities.tokenCacheEnabled = False
if args["interactive"]:
val = args["interactive"]
wa = WhatsappCmdClient(val, args['keepalive'] ,args['autoack'])
wa.login(login, password)
elif args['send']:
phone = args["send"][0]
message = args["send"][1]
wa = WhatsappEchoClient(phone, message, args['wait'])
wa.login(login, password)
elif args['listen']:
wa = WhatsappListenerClient(args['keepalive'], args['autoack'])
wa.login(login, password)
elif args['broadcast']:
phones = args["broadcast"][0]
message = args["broadcast"][1]
wa = WhatsappEchoClient(phones, message, args['wait'])
wa.login(login, password)
elif args["requestcode"]:
method = args["requestcode"]
if method not in ("sms","voice"):
print("coderequest accepts only sms or voice as a value")
else:
wc = WACodeRequestV2(countryCode, phoneNumber, identity, method)
result = wc.send()
print(resultToString(result))
elif args["register"]:
code = args["register"]
code = "".join(code.split('-'))
wr = WARegRequestV2(countryCode, phoneNumber, code, identity)
result = wr.send()
print(resultToString(result))
elif args["exists"]:
we = WAExistsRequestV2(countryCode, phoneNumber, identity)
result = we.send()
print(resultToString(result))
if result["pw"] is not None:
print("\n=========\nWARNING: %s%s's has changed by server to \"%s\", you must update your config file with the new password\n=========" %(countryCode, phoneNumber, result["pw"]))
elif args["sync"]:
contacts = args["sync"].split(',')
wsync = WAContactsSyncRequest(login, password, contacts)
print("Syncing %s contacts" % len(contacts))
result = wsync.send()
print(resultToString(result))
elif args["dbus"]:
startDbusInterface()
elif args["generatepassword"]:
print(Utilities.processIdentity(args["generatepassword"]));
elif args["decodestring"]:
print(Utilities.decodeString(map(int, "".join(args["decodestring"].split(' ')).split(','))))
else:
print("Error: config file is invalid")