From a86b42d66c92442aada8630b3aeaffc149b90045 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Lo=C3=AFc=20Wikle=20DUBARD?= <loic97429@gmail.com>
Date: Mon, 19 Aug 2019 07:02:43 +0200
Subject: [PATCH] fix:remplacement du os.system(mp321) par la librairie
 playsound pour crossplatform

---
 CHANGELOG.md                              |  12 ++
 Jarvis.py                                 |  23 +++-
 README.md                                 |   2 +-
 myimports.py                              |  14 +-
 requirements.txt                          |   5 +-
 usefull/__init__.py                       |   3 +-
 usefull/__pycache__/chacon.cpython-37.pyc | Bin 0 -> 1559 bytes
 usefull/chacon.py                         |  48 +++++++
 useless/__init__.py                       |   2 +-
 useless/guess.py                          | 161 +++++++++++++++++++---
 10 files changed, 238 insertions(+), 32 deletions(-)
 create mode 100644 usefull/__pycache__/chacon.cpython-37.pyc
 create mode 100755 usefull/chacon.py

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8095597..fc72324 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,17 @@
 # CHANGELOG:
 
+## 19 aout 2019
+**Fixes:**
+- remplacement du os.system('mp321 sounds/compris.mp3') par la librairie 'playsound' pour compatibilité windows
+
+---
+
+## 18 aout 2019
+**Ajouts:**
+- scripts prises connectées chacon
+
+---
+
 ## 17 aout 2019
 **Ajouts:**
 - meteo : on peut demander des prévisions dans n heures
diff --git a/Jarvis.py b/Jarvis.py
index cac044d..a801c8f 100755
--- a/Jarvis.py
+++ b/Jarvis.py
@@ -32,14 +32,14 @@ def get_speech(message="entrée"):
                     r.adjust_for_ambient_noise(source, duration=2)
                     audio = r.listen(source, timeout=1)
                     print('[speech_detected]')
-                    os.system('mpg321 sounds/compris.mp3 2>/dev/null')
+                    play_compris_sound()
                 entre = r.recognize_google(audio, language="fr")
                 understand = True
                 print(entre)
-                os.system('mpg321 sounds/compris.mp3 2>/dev/null')
+                play_compris_sound()
             except:
                 print("[!] impossible de comprendre votre charabia [!]")
-                os.system('mpg321 sounds/pascompris.mp3 2>/dev/null')
+                play_pascompris_sound()
                 entre = ''
     else:
         entre = input('[-] %s (clavier) :' % message)
@@ -240,6 +240,21 @@ def tests(entre):
     compris = 0
     merci = 0
 
+    if all(word in entre for word in ['allume', 'lumiere']):
+        for device in chacon_device_list:
+            try:
+                device.switch_on()
+                parle('Le switch {} est alumé'.format(device.get_name()))
+            except:
+                parle('Le switch {} est déjà alumé'.format(device.get_name()))
+    if all(word in entre for word in ['etein', 'lumiere']):
+        for device in chacon_device_list:
+            try:
+                device.switch_off()
+                parle('Le switch {} est éteint'.format(device.get_name()))
+            except:
+                parle('Le switch {} est déjà éteint'.format(device.get_name()))
+
     # location
     if any(ext in entre for ext in ['ou est ', 'ou se situe ', 'ou se trouve ', 'est ou ']):
         location(entre)
@@ -393,7 +408,7 @@ def tests(entre):
             parle("je n'ai pas compris.")
         else:
             print("je n'ai pas compris")
-            os.system('mpg321 sounds/pascompris.mp3 2>/dev/null')
+            play_pascompris_sound()
         if not currently_playing:
             dire_un_truc_en_mode_random(verbosity)
         compris = 0
diff --git a/README.md b/README.md
index 1b54181..11f0ce7 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@ Mon Jarvis pour windows et linux (peut-être un truc sur android aussi :°°)
 
 # INSTALLATION
 - debian :
-    > * `sudo apt install python3 python3-pyaudio python3-pip mpg321`
+    > * `sudo apt install python3 python3-pyaudio python3-pip mpg321 gstreamer1.0-python3-plugin-loader`
     > * `git clone https://git.iiens.net/dubard2018/jarvis.git cd jarvis/`
     > * `pip3 install -r requirements.txt`
     > * `chmod +x jarvis.py`
diff --git a/myimports.py b/myimports.py
index 3f700f6..8444eaa 100644
--- a/myimports.py
+++ b/myimports.py
@@ -15,7 +15,8 @@ from email.mime.multipart import MIMEMultipart
 import smtplib
 import warnings
 import requests
-import mutagen.mp3
+# import mutagen.mp3
+from playsound import playsound
 import useless  # package de fonctions inutiles mais marrantes
 # import pyttsx3
 import usefull  # package de fonctions utiles
@@ -67,6 +68,9 @@ bot_name = "jarvis"  # défini le nom auquel répondra l'ia
 compris = 0
 comprispreced = 0
 verbosity = 3
+game = useless.Quizz()
+chacon_ip_list = {'salon': '192.168.1.33'}
+chacon_device_list = [usefull.Chacon(chacon_ip_list[name], name) for name in chacon_ip_list.keys()]
 entrepreced = ""
 _from = ""
 password = ""
@@ -93,3 +97,11 @@ fonctionnalités = [
 
 class BreakoutException(Exception):
     pass
+
+
+def play_compris_sound():
+    playsound('sounds/compris.mp3')
+
+
+def play_pascompris_sound():
+    playsound('sounds/pascompris.mp3')
diff --git a/requirements.txt b/requirements.txt
index 082fba5..59b6cc6 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,7 +1,8 @@
 wikipedia
 requests
-pyaudio
 pyttsx
 speechrecognition
 gtts
-googletrans
\ No newline at end of file
+googletrans
+pygame
+playsound
\ No newline at end of file
diff --git a/usefull/__init__.py b/usefull/__init__.py
index 3a08a63..4891b54 100644
--- a/usefull/__init__.py
+++ b/usefull/__init__.py
@@ -1,4 +1,5 @@
 # __init__.py
 
 from .wiki import *
-from .meteo import *
\ No newline at end of file
+from .meteo import *
+from .chacon import *
\ No newline at end of file
diff --git a/usefull/__pycache__/chacon.cpython-37.pyc b/usefull/__pycache__/chacon.cpython-37.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84e1c00850006e0873557724b403635c5b2b0950
GIT binary patch
literal 1559
zcmZ?b<>g{vU|?wAi;N9qVPJR+;=nKq0|SEt0|P^G5Ca243PTh_3S$aW4r3IfJ3|U{
z3QG$^3QH<eGjkMkDoYA$HdB#bDsu{33VSbO6l*G5D(eFFg$&J%j0~x)3pf@sFft&E
zr7#6EXmV7UaXBjFWR{fVq$(6A7iAWdD3s(YB<JUq6y@hAlw_nTBxfWh=jSPuXQpK;
z6qjd~BxfjCX>z>;xzH~eM8YsL%&mG13=F9ZQH&`JQA{a3V0SV`F{iMmu(dEmv81r4
zaI`Q)v8HgQaJ4W*v88YaGidVOVsi%DbBi@GB{wtg7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Y
jU>3*`w>WGdzOVzOnPN}?vM_Nl3y5<taxwBSaxek_6+Lr_

literal 0
HcmV?d00001

diff --git a/usefull/chacon.py b/usefull/chacon.py
new file mode 100755
index 0000000..747c511
--- /dev/null
+++ b/usefull/chacon.py
@@ -0,0 +1,48 @@
+#!/usr/bin/python3
+# coding: utf-8
+'''
+A little script to control the chacon wifi switch :)
+'''
+
+import requests
+
+
+class Chacon(object):
+    def __init__(self, ip, name='default', user='admin', password='Lumlink@100'):
+        assert 'HF Easy' in requests.get('http://{}/status'.format(ip)).content.decode(), 'Not Compatible Firmware'
+        self.ip = ip
+        self.name = name
+        self.user = user
+        self.password = password
+        self.session = requests.session()
+
+    def get_status(self):
+        '''retourne True si le switch est alumé, False sinon'''
+        try:
+            r = self.session.get('http://{}/status'.format(self.ip))
+            return 'Closed(On)' in r.content.decode()
+        except:
+            return 'WRONG IP OR OLD FIRMWARE see https://github.com/ljalves/hfeasy to upgrade'
+
+    def switch_on(self):
+        assert not self.get_status(), 'Device is already switched on'
+        self.session.get('http://{}/state?sw=1'.format(self.ip))
+        assert self.get_status(), 'Can\'t switch it on'
+
+    def switch_off(self):
+        assert self.get_status(), 'Device is already switched off'
+        self.session.get('http://{}/state?sw=0'.format(self.ip))
+        assert not self.get_status(), 'Can\'t switch it off'
+
+    def get_name(self):
+        return self.name
+
+    def get_ip(self):
+        return self.ip
+
+
+if __name__ == '__main__':
+    c1 = Chacon(ip='192.168.1.33')
+    print(c1.get_status())
+    c1.switch_off()
+    print(c1.get_status())
diff --git a/useless/__init__.py b/useless/__init__.py
index da54f6a..a13ef3a 100644
--- a/useless/__init__.py
+++ b/useless/__init__.py
@@ -7,4 +7,4 @@ from .nordpresse import nordpresse
 from .philotron import genererSujet
 from .pipotron import pipo
 from .haddock import haddock
-from .quizz import quizz
+from .quizz import *
diff --git a/useless/guess.py b/useless/guess.py
index d8c002e..88e391e 100755
--- a/useless/guess.py
+++ b/useless/guess.py
@@ -1,28 +1,145 @@
 #!/usr/bin/python3
 # coding: utf-8
 # https://fr.akinator.com/game
-import akinator
-
-aki = akinator.Akinator()
-def main():
-    
-    q = aki.start_game()
-    while aki.progression <= 85:
-        a = input(q + "\n\t")
-        if a == "b":
-            try:
-                q = aki.back()
-            except akinator.CantGoBackAnyFurther:
-                pass
-        else:
-            q = aki.answer(a)
-    aki.win()
-    correct = input(f"It's {aki.name} ({aki.description})! Was I correct?\n{aki.picture}\n\t")
-    if correct.lower() == "yes" or correct.lower() == "y":
-        print("Yay\n")
+import requests
+
+# Somebody told me that the link has changed, but I'm not
+# really maintaining this anymore, so here is something that
+# I think should fix it.
+
+NEW_SESSION_URL = "https://srv2.akinator.com:9157/ws/new_session?constraint=ETAT<>'AV'&partner=1"
+ANSWER_URL = "https://srv2.akinator.com:9157/ws/answer?constraint=ETAT<>'AV'"
+GET_GUESS_URL = "https://srv2.akinator.com:9157/ws/list?constraint=ETAT<>'AV'"
+CHOICE_URL = "https://srv2.akinator.com:9157/ws/choice?constraint=ETAT<>'AV'"
+EXCLUSION_URL = "https://srv2.akinator.com:9157/ws/exclusion?constraint=ETAT<>'AV'"
+GLB_URL = "https://pastebin.com/gTua3dg2"
+
+
+def ans_to_strint(ans: str):
+    ans = ans.lower()
+    if ans == "yes" or ans == "y":
+        return "0"
+    elif ans == "no" or ans == "n":
+        return "1"
+    elif ans == "i" or ans == "idk" or ans == "i dont know" or ans == "i don't know":
+        return "2"
+    elif ans == "probably" or ans == "p":
+        return "3"
+    elif ans == "probably not" or ans == "pn":
+        return "4"
+    else:
+        return "-1"
+
+
+game_over = False
+
+akinator_session = requests.get(NEW_SESSION_URL)
+akinator_data = akinator_session.json()
+
+
+try:
+    if akinator_data['completion'] == "OK":
+        success = True
     else:
-        print("Oof\n")
+        success = False
+except:
+    success = False
+if not success:
+    raise Exception('Error')
+
+print("Question " +
+      str(int(akinator_data['parameters']['step_information']['step']) + 1) +
+      ":\n" +
+      akinator_data['parameters']['step_information']['question'] +
+      '\n"yes", "no", "idk", "probably", "probably not"')
+response = input("> ")
+
+response = ans_to_strint(response)
+
+params = {
+    "session": akinator_data['parameters']['identification']['session'],
+    "signature": akinator_data['parameters']['identification']['signature'],
+    "step": akinator_data['parameters']['step_information']['step'],
+    "answer": response
+}
+
+session = akinator_data['parameters']['identification']['session']
+signature = akinator_data['parameters']['identification']['signature']
 
+akinator_session = requests.get(ANSWER_URL, params=params)
+akinator_data = akinator_session.json()
 
-if __name__ == '__main__':
-    main()
+can_guess = False
+guessed_wrong_once = False
+
+while not game_over:
+    while not can_guess:
+        if int(float(akinator_data['parameters']['progression'])) > 90 and not guessed_wrong_once:
+            can_guess = True
+            break
+
+        guessed_wrong_once = False
+
+        print(akinator_data['parameters']['progression'])
+        print("Question " +
+              str(int(akinator_data['parameters']['step']) + 1) +
+              ":\n" +
+              akinator_data['parameters']['question'] +
+              '\n"yes", "no", "idk", "probably", "probably not"')
+        response = input("> ")
+        response = ans_to_strint(response)
+
+        params = {
+            "session": session,
+            "signature": signature,
+            "step": akinator_data['parameters']['step'],
+            "answer": response
+        }
+
+        akinator_session = requests.get(ANSWER_URL, params=params)
+        akinator_data = akinator_session.json()
+
+    params = {
+        "session": session,
+        "signature": signature,
+        "step": akinator_data['parameters']['step']
+    }
+
+    guess_session = requests.get(GET_GUESS_URL, params=params)
+    guess_data = guess_session.json()
+
+    name = guess_data['parameters']['elements'][0]['element']['name']
+    desc = guess_data['parameters']['elements'][0]['element']['description']
+
+    print("Is this your character? [yes/no]\n" +
+          name + "\n" +
+          desc + "\n")
+    answer = input('> ')
+
+    if answer.lower() == "yes" or answer.lower() == "y":
+        #  TODO dump to choice_url
+        params = {
+            "session": session,
+            "signature": signature,
+            "step": akinator_data['parameters']['step'],
+            "element": guess_data['parameters']['elements'][0]['element']['id']
+        }
+        r = requests.get(CHOICE_URL, params=params)
+        print("I guessed right! Thanks for playing with me.")
+        game_over = True
+        break
+
+    elif answer.lower() == "no" or answer.lower() == "n":
+        #  TODO dump to exclusion_url
+        params = {
+            "session": session,
+            "signature": signature,
+            "step": akinator_data['parameters']['step'],
+            "forward_answer": response
+        }
+        r = requests.get(EXCLUSION_URL, params=params)
+        can_guess = False
+        guessed_wrong_once = True
+
+    else:
+        pass
\ No newline at end of file
-- 
GitLab