mukulhase / WebWhatsapp-Wrapper

An API for sending and receiving messages over web.whatsapp [Working as of 18th May 2018]
https://webwhatsapi.readthedocs.io/en/latest/
MIT License
2.02k stars 797 forks source link

save_firefox_profile doesn't save session #91

Closed ghost closed 6 years ago

ghost commented 6 years ago

I just noticed that the function "save_firefox_profile" no longer saves the session. These are apparently no longer managed by the cookies. Is this problem already known and how can I avoid scanning the QR code again?

ghost commented 6 years ago

Edit: A firefox profile was created and given to the init function

Skull118 commented 6 years ago

Hello I had the same issue a couple hours ago, the way to fix this (in linux at least) is adding the "profile path" into your WhatsappDrive inicialization string.

First create a new profile called as you want, but in "Folder Selection" Section you must to specify the folder where you want to save that profile (this folder will contain all information about whatsapp), you can find how create the profile in Readme.md (but don't follow all process), after configured the new firefox profile, you can start to use the api with this string.

driver = WhatsAPIDriver(profile="/path_to_ your_project_or_firefox_folder_profile_configured/firefox_cache/P_R_O_F_I_L_E")

I hope I've helped you

ghost commented 6 years ago

Hello Skull118,

i already created a new profile and defined the Path (/root/.mozilla/firefox/2lnisra1.whatsapp) in the script. It is also creating a directory in the profile called "webdriver-py-profilecopy", but it only stores a cookies.pkl-File with the size of 6 Byte. After a new run it created the directory "webdriver-py-profilecopy" in the old directory (/root/.mozilla/firefox/2lnisra1.whatsapp/webdriver-py-profilecopy) and so on... It's a Linux server, so I can't create the profile by the Profile Manager, but I were able to create it by command line. Do you have an idea why this doesn't work?

Skull118 commented 6 years ago

The basic function of this library is help to automate whatsapp with whatsapp web site , but I think you need GUI enviroment on server to work with this library, because you must scan the QR code of whatsapp web and I some cases re-scan the QR code to work with this library.

dashtail commented 6 years ago

to run in ubuntu server look this #18

ghost commented 6 years ago

The API is working on the server without any problems.. I can scan the QR-Code and I haven't had any problems until i tried to save the profile. Today I noticed, that the temporary profile in the "/tmp/rust_moz..." directory hasn't stored the cookies correctly, too. Has anyone an idea?

ghost commented 6 years ago

Edit: The print in the "save_firefox_profile"-method returns an empty array "[]". I Also tried to use the default profile from the root user -> same problem

ghost commented 6 years ago

I found a solution for my problem: I'm storing the JavaScript "localStorage" in a file and set it by each new startup. I added the following methods to the WhatsAPIDriver-Class:

//Edit: After using the load_whatsapp_storage() mathod, we have to use wait_for_login(). Otherwise it will crash somethimes

    def save_whatsapp_storage(self):
        if self.driver:
            config_file = os.path.join(self._profile_path, "whatsapp.ini")
            os.remove(config_file)
            configfile = open(config_file, "w")
            storage = self.driver.execute_script("return localStorage")
            for key, value in storage.iteritems():
                configfile.write(str(urllib.pathname2url(key))+" = "+str(value)+"\r\n")
            configfile.close()

    def load_whatsapp_storage(self):
        if self.driver:
            config_file = os.path.join(self._profile_path, "whatsapp.ini")
            if os.path.isfile(config_file):
                configfile = open(config_file, "r")
                lines = configfile.readlines()
                for item in lines:
                    item_parts = item.replace("\r\n", "").split(" = ", 2)
                    self.driver.execute_script("localStorage.setItem('"+urllib.url2pathname(item_parts[0])+"', '"+item_parts[1]+"');")
                self.driver.get(self._URL)

And the startup is like the following:

print("started")
driver = WhatsAPIDriver(profile="/home/user/.mozilla/firefox/e4qumwi2.default")
driver.load_whatsapp_storage()
driver.wait_for_login() #added
status = driver.get_status()
if status == "NotLoggedIn" or status == "Unknown":
    print("has to login")
    driver.get_qr()
    print("Waiting for QR")
    driver.wait_for_login()
else:
    print("Already logged in")
driver.save_firefox_profile()
driver.save_whatsapp_storage()
print("Bot started")
Ch-Sh commented 6 years ago

@Spielie I wanna skip the QRcode by setting up a profile but can not managed with just save_firefox_profile. I followed your soluton but get error in save_whatsapp_storage os.remove(config_file) for "no whatsapp.ini found" B.T.W, as for the profile setting, I created new folder with firefox manager and pass its absolute path when I instatited a driver object. Then, the script launch the borwer slowly ca. 1-2 mins. Wondering whether I work properly for persistent login.

ghost commented 6 years ago

@Ch-Sh I edited the WhatsAPIDriver-Script directly in the installation dir (Linux: /usr/local/lib/python2.7/dist-packages/webwhatsapi/init.py). The startup (until the message "Bot started") takes about 45 seconds in my case. This is a little bit longer, than using the save_firefox_profile()-function, but it works every time and doesn't require any initialized profile (only the profile_path for saving the whatsapp.ini). Were I able to help you with this answer?

Ch-Sh commented 6 years ago

@Spielie thanks for quick answer. I manged to run the your new methods. But got new error as update. Sorry, I am a newby for web area. Could u give me a naive instruction how I should I setup this persistent login(I work on Mac). I have found any whatsapp.ini or firefox_cache.

ghost commented 6 years ago

@Ch-Sh What is the output error?

Ch-Sh commented 6 years ago

@Spielie it turns out to be following the error. The script is totally same as yours. So, the load_whatsap_storage no error. Traceback (most recent call last): File "new_chatbot.py", line 413, in driver.save_whatsapp_storage() File "/Library/Python/2.7/site-packages/webwhatsapi-2.0.1-py2.7.egg/webwhatsapi/init.py", line 317, in save_whatsapp_storage.os.remove(config_file) OSError: [Errno 2] No such file or directory: '/mypath/firefox_profile/whatsapp.ini'

ghost commented 6 years ago

I'm just on the way home; i'll tell you the fix in about 30-45 minutes.

ghost commented 6 years ago

@Ch-Sh change the load_whatsapp_storage function to the following (changed lines are marked):

    def load_whatsapp_storage(self):
        if self.driver:
            config_file = os.path.join(self._profile_path, "whatsapp.ini")
            cfile = Path(config_file) #added
            if cfile.exists(): #edited
                configfile = open(config_file, "r")
                lines = configfile.readlines()
                for item in lines:
                    item_parts = item.replace("\r\n", "").split(" = ", 2)
                    self.driver.execute_script("localStorage.setItem('"+urllib.url2pathname(item_parts[0])+"', '"+item_parts[1]+"');")
                self.driver.get(self._URL)

I do not know why the other query is not running for you.

//Edit: Don't forget to add the following line to your imports: from pathlib import Path

Ch-Sh commented 6 years ago

Get error: /init.py", line 328, in load_whatsapp_storage cfile = Path(config_file) NameError: global name 'Path' is not defined

ghost commented 6 years ago

@Ch-Sh please read the edit (include the Path)

Ch-Sh commented 6 years ago

@Spielie yeah. I forget that. But still get the same problem. I found something weird. I passed the absolute folder path in webdriver like "XXX/xxx.default". Each time when the script start and run your codes. save_firefox_profile will create a folder webdriver-py-profilencopy inside the lowest folder level and generate two fils times.json and user.js. B.T.W there is no whatsapp.ini. Could u tell me how u setup your profile? I mean the folder and where is in it before u run the script and after running.

ghost commented 6 years ago

Strange... try to create the whatsapp.ini by yourself and try again (without any file content)