j'ai pas mal fait évoluer mon script depuis le dernier sujet que j'ai posté sur la zone générale, et je voulais le partager, histoire d'éviter les galères que j'ai pu rencontrer lors de son élaboration.
Le rôle de ce script est d'ouvrir Open Office pour compléter un document, qui génère un certain nombre de fichiers via des macros, puis d'envoyer certains de ces documents de manière automatique à un destinataire donné.
La grosse difficulté que j'ai rencontré, et qui a fait enfler le script de manière assez importante, est l'incompatibilité manifeste des fonctions contenant wait et de Windows 2000 (en ayant compilé mon programme sous Windows XP).
J'ai donc dû pas mal siouxer pour arriver à mes fins.
► Afficher le texte
Code : Tout sélectionner
; ------------------------------------------------------------------
; * SCRIPT D'AUTOMATISATION D'ENVOI DE FICHIER *
; * Ecrit par Pierre CHEVALIER, pour la société STANDARD - BLUE BOX*
; * Juin 2009 *
; ------------------------------------------------------------------
; Bréviaire des erreurs :
; -----------------------
; ERREUR FICHIER n°1 = le fichier original n'est pas présent à l'emplacement prévu
; ERREUR FICHIER n°2 = le fichier copié n'est pas modifiable en "non lecture seule"
; ERREUR FICHIER n°3 = le fichier n'a pas été copié dans le repertoire destination
; ERREUR FICHIER n°4 = le repertoire de transit ne contient pas de fichier ODS après la sauvegarde des modifications
; ERREUR FICHIER n°5 = il n'y a qu'un seul fichier dans le repertoire de transit (non bloquant)
#Include <File.au3>
#Include <mail.au3>
; ------------------------------------------------------------------------------
; * DECLARATION *
; ------------------------------------------------------------------------------
$NomFichierOriginal = "planning_original.ods"
$NomFichierCopie = "planning_copie.ods"
$CheminLog = (@WindowsDir&"\system32\planning_log.txt")
$CheminFichierOriginal = (@WindowsDir&"\system32\"&$NomFichierOriginal)
$RepertoireBackup = (@MyDocumentsDir&"\planning\"&@YEAR&"\")
$RepertoireTransit = (@WindowsDir&"\planning\")
$RepertoireErreurEnvoi = (@MyDocumentsDir&"\planning\erreur_envoi\")
$Contact = " : contactez le Service Informatique."
; ------------------------------------------------------------------------------
; * FONCTIONS *
; ------------------------------------------------------------------------------
func _ExpedMail()
; Déclaration paramètres mail.au3
$s_SmtpServer = "smtp.fr.oleane.com" ; address for the smtp-server to use - REQUIRED
$s_FromName = "Reporting planning" ; name from who the email was sent
$s_FromAddress = "totoro@totoro.fr" ; address from where the mail should come
$s_ToAddress = "totoro@totoro.fr" ; destination address of the email - REQUIRED
;$s_ToAddress = "totoro@totoro.fr" ; destination address of the email - REQUIRED
$s_CcAddress = "" ; address for cc - leave blank if not needed
$s_BccAddress = "" ; address for bcc - leave blank if not needed
$s_Username = "boiteaidee@totoro" ; username for the account used from where the mail gets sent - Optional (Needed for eg GMail)
$s_Password = "totoro" ; password for the account used from where the mail gets sent - Optional (Needed for eg GMail)
$IPPort = 25 ; port used for sending the mail
$ssl = 0 ; enables/disables secure socket layer sending - put to 1 if using httpS
$mail=""
$as_Body = ""
$s_AttachFiles =$RepertoireTransit&$PremierFichier&";"&$RepertoireTransit&$SecondFichier
$s_Subject = (stringleft($premierfichier,(stringlen($premierfichier)-4)))
$mail=_INetSmtpMailCom ($s_SmtpServer, $s_FromName, $s_FromAddress, $s_ToAddress, $s_Subject, $as_Body,$s_AttachFiles)
If $mail=0 Then
MsgBox(0,"","Le planning a été envoyé avec succès.")
; Une fois le mail envoyé, on déplace les fichiers dans un répertoire de backup
FileSetAttrib ($RepertoireBackup&"*.*", "-R")
FileMove($RepertoireTransit&"*.*",$RepertoireBackup,1)
FileMove($RepertoireBackup&"*.xls",$RepertoireBackup&"XLS\",1)
FileSetAttrib ($RepertoireBackup&"*.*", "+R")
Else
; Sinon, on le laisse sur place, pour proposer le renvoi à la prochaine relance du programme
MsgBox(0,"","Erreur messagerie n°"&@error&" "&$contact". Il vous sera proposé de renvoyer ce planning au prochain lancement du programme.")
EndIf
EndFunc
; ------------------------------------------------------------------------------
func _LanceOOOw2k()
FileDelete("c:\windows\test.xls")
If FileExists(@ProgramFilesDir&"\OpenOffice.org 3\program\scalc.exe") Then
Run(@ProgramFilesDir&"\OpenOffice.org 3\program\scalc.exe -norestore c:\windows\planning\"&$NomFichierCopie)
Else
; Modif spéciale pour le magasin 1215 : OpenOffice installé sur C: avec l'OS sur D:
Run("c:\Program Files\OpenOffice.org 3\program\scalc.exe -norestore c:\windows\planning\"&$NomFichierCopie)
EndIf
While FileExists("c:\windows\test.xls")<>1
WinWait("Totoro","",10)
WEnd
EndFunc
; ------------------------------------------------------------------------------
func _LanceOOOwXP()
If FileExists(@ProgramFilesDir&"\OpenOffice.org 3\program\scalc.exe") Then
$pid=Run(@ProgramFilesDir&"\OpenOffice.org 3\program\scalc.exe -norestore c:\windows\planning\"&$NomFichierCopie)
MsgBox(0,"",$pid)
WinWait("","",5)
While ProcessExists($pid)<>0
; WinWait("","",5)
WEnd
Else
; Modif spéciale pour le magasin 1215 : OpenOffice installé sur C: avec l'OS sur D:
$pid=Run("c:\Program Files\OpenOffice.org 3\program\scalc.exe -norestore c:\windows\planning\"&$NomFichierCopie)
WinWait("","",5)
While ProcessExists($pid)<>0
WinWait("","",5)
WEnd
EndIf
EndFunc
; ------------------------------------------------------------------------------
func _NettoyageOffice()
$program="soffice.bin"
$program1="soffice.exe"
$program2="scalc.exe"
If ProcessExists($program) Or ProcessExists($program1) Or ProcessExists($program2) Then
MsgBox (0,"ATTENTION","Toutes les fenêtres d'OpenOffice ouvertes vont être fermées sans sauvegarde. Merci de sauvegarder et de quitter OpenOffice avant de cliquer sur Ok.")
While ProcessExists($program)
ProcessClose($program)
WEnd
While ProcessExists($program)
ProcessClose($program)
WEnd
While ProcessExists($program)
ProcessClose($program)
WEnd
EndIf
EndFunc
; ------------------------------------------------------------------------------
func _NettoyagePlanning()
$program="planning.exe"
While ProcessExists($program)
ProcessClose($program)
WEnd
EndFunc
; ------------------------------------------------------------------------------
func _VerifConnec()
$var = Ping("www.google.com",10000)
EndFunc
; ------------------------------------------------------------------------------
; * PROGRAMME *
; ------------------------------------------------------------------------------
; On vérifie que les repertoires déclarés existent
DirCreate($RepertoireTransit)
DirCreate($RepertoireBackup)
DirCreate($RepertoireBackup&"XLS\")
DirCreate($RepertoireBackup&"erreur_envoi\")
_NettoyageOffice()
; On vérifie que le fichier existe bien à l'emplacement convenu
$verif = FileExists($CheminFichierOriginal)
If $verif Then
Else
MsgBox(0,"ERREUR !","ERREUR FICHIER n°1"&$Contact)
Exit
EndIf
; On vérifie qu'il ne reste rien à envoyer dans le repertoire de transit
FileDelete($RepertoireTransit&$NomFichierCopie)
Filedelete($RepertoireTransit&".~lock.*")
$Recherche = FileFindFirstFile($RepertoireTransit&"Planning_1*.*")
$PremierFichier = FileFindNextFile($Recherche)
$SecondFichier = FileFindNextFile($Recherche)
; Si les deux fichiers portent le même nom, hors extension, alors
If stringleft($premierfichier,(stringlen($premierfichier)-4)) = stringleft($premierfichier,(stringlen($SecondFichier)-4)) and stringleft($premierfichier,(stringlen($SecondFichier)-4))<>"" Then
$MessageRenvoi = MsgBox(3, "QUESTION", "Des fichiers non envoyés ont été detectés : cliquez sur Oui pour les envoyer, Non pour les effacer, Annuler pour abandonner la saisie du planning.")
If $MessageRenvoi = 6 then
$var = Ping("www.google.com",10000)
; Si le ping passe, on continue la procédure
If $var>0 Then
; On expédie le mail
_ExpedMail()
; Sinon, on quitte le programme afin de laisser les fichiers en place pour le prochain lancement -> reexpedition
Else
Msgbox(0,"ERREUR !","PROBLEME DE CONNEXION N°"& @error&". Il vous sera proposé de renvoyer ce planning au prochain lancement du programme.")
Exit
EndIf
EndIf
If $MessageRenvoi = 7 Then
FileDelete("c:\windows\planning\*.*")
EndIf
If $MessageRenvoi = 2 Then
Exit
EndIf
MsgBox(0,"","Merci de relancer l'application si vous souhaitez remplir un nouveau planning.")
Exit
EndIf
; On efface le contenu du repertoire de transit, et on crée une copie (et on crée le repertoire au besoin)
FileDelete("c:\windows\planning\*.*")
FileCopy($CheminFichierOriginal,"c:\windows\planning\"&$NomFichierCopie,9)
; On retire l'attribut Lecture Seule hérité de l'original à la copie (et on vérifie que la copie s'est bien passée)
If FileExists("c:\windows\planning\"&$NomFichierCopie) Then
If Not FileSetAttrib("c:\windows\planning\"&$NomFichierCopie, "-R") Then
MsgBox(0,"ERREUR !", "ERREUR FICHIER n°2"&$Contact)
Exit
EndIf
Else
MsgBox(0,"ERREUR !", "ERREUR FICHIER n°3"&$Contact)
Exit
EndIf
; On lance OOO, de manière différente suivant l'OS (problème de surcharge CPU dans le cas de XP si l'on utilise la fonction _LanceOOOw2k)
if @OSVersion <> "WIN_2000" Then
_LanceOOOw2k()
Else
_LanceOOOw2k()
EndIf
; On supprime planning_copie.ods et la "mule", puis on recopie le contenu de c:\windows\planning dans
; le rep "officiel" de Windows (cas des machines ayant deux disques et Windows installé sur D:)
FileDelete ("c:\windows\test.xls")
FileDelete ("c:\windows\planning\"&$NomFichierCopie)
FileMove("c:\windows\planning\*.*",$RepertoireTransit,1)
; On récupère le nom des deux premiers fichiers du répertoire
$Recherche = FileFindFirstFile($RepertoireTransit&"Planning_1*.*")
$PremierFichier = FileFindNextFile($Recherche)
If $PremierFichier = -1 Then
MsgBox(0, "ERREUR !", "ERREUR FICHIER n°4"&$Contact)
Exit
EndIf
; Test de présence du second fichier (erreur non bloquante)
$SecondFichier = FileFindNextFile($Recherche)
If $SecondFichier = "" Then
$message1=MsgBox(0, "ERREUR NON BLOQUANTE !", "ERREUR FICHIER n°5"&$Contact&". Cette erreur n'est pas bloquante.")
EndIf
; On teste l'état de la connexion
$var = Ping("www.google.com",10000)
; Si le ping passe, on continue la procédure
If $var>0 Then
; On expédie le mail
_ExpedMail()
; Sinon, on quitte le programme afin de laisser les fichiers en place pour le prochain lancement -> reexpedition
Else
Msgbox(0,"ERREUR !","PROBLEME DE CONNEXION N°"& @error&". Il vous sera proposé de renvoyer ce planning au prochain lancement du programme.")
Exit
EndIf
_NettoyagePlanning()
_NettoyageOffice()
En espérant que cela puisse aider des gens ...
Edit du 4/8/9 : erreur "corrigée", suite au non-envoi des mails lorsque _ExpedMail() est employé en fin de programme --> intégration des variables dans la fonction (faute de mieux).
Edit du 17/8/9 : correction d'un petit oubli (mauvaise variable utilisée pour la vérification du répertoire de transit avant effacement)