Petit système mnémonique en Python/SQLite [2/4]

Salut à tous,
Nous allons continuer notre petit chatBot mnémonique avec un script python. Ensuite nous ajouterons la base une base de donnée SQLite.
Il y a quelques années, j'avais poster un petit script Python faisant office de Bot XMPP (Xee XMPP Bot). Je vais partir sur la même base.
au préalable il vous faudra installer deux petites librairie python:
sudo apt-get install python-xmpp sqlite3
Au passage j'en profite pour vous passer un fichier *.DB avec tout le dictionnaire français.
#!/usr/bin/python
# -*- coding: utf8 -*-
import sys, os, string
try: import xmpp
except ImportError:
print >> sys.stderr, """
You need to install xmpppy from http://xmpppy.sf.net/.
On Debian-based systems, install the python-xmpp package.
apt-get install python-xmpp
"""
sys.exit(-1)
intro="""XEE XMPP BOT
GNU/GPL v3
XEE is a bot for the XMPP protocol
Create by BeHuman (craft at ckdevelop.org)"""
############################ bot logic start #####################################
bonjour=["salut", "slt", "bonjour", "bjr", "yop", "yo", "hello", "hi", "lu"]
def messageCB(conn,mess):
text=mess.getBody()
retour="Désolé, je ne suis qu'un bot pré-programmé,\nje ne comprend pas ce que vous me dîtes."
for a in bonjour:
if a in text:
retour="Salut, je suis Xee le bot de "+NameUser+".\nIl n'ai pas là pour le moment."
conn.send(xmpp.Message(mess.getFrom(),retour))
nick=mess.getFrom().getNode()
############################# bot logic stop #####################################
def StepOn(conn):
try:
conn.Process(1)
except KeyboardInterrupt:
return 0
return 1
def GoOn(conn):
while StepOn(conn): pass
def help():
print(intro+"""\nUsage:
xee
Help:
xee -h or --help""")
sys.exit(1)
if len(sys.argv)<2:
if sys.argv[1] == "-h" or sys.argv[1] == "--help":
help()
else:
print("\n[!]Mauvais nombre d\'arguments[!]\n")
help()
else:
if sys.argv[1] == "-h" or sys.argv[1] == "--help":
help()
jid=xmpp.JID(sys.argv[1])
user,server,password=jid.getNode(),jid.getDomain(),sys.argv[2]
conn=xmpp.Client(server)#,debug=[])
conres=conn.connect()
if not conres:
print "Unable to connect to server %s!"%server
sys.exit(1)
if conres<>'tls':
print "Warning: unable to estabilish secure connection - TLS failed!"
authres=conn.auth(user,password)
if not authres:
print "Unable to authorize on %s - check login/password."%server
sys.exit(1)
if authres<>'sasl':
print "Warning: unable to perform SASL auth os %s. Old authentication method used!"%server
conn.RegisterHandler('message',messageCB)
conn.sendInitPresence()
print "Bot started."
GoOn(conn)
Maintenant que l'on a notre base, nous allons ajouter à ce script la gestion SQLite. On commence par charger la librairie adéquat au début de notre script. Juste en dessous de.
try: import xmpp
except ImportError:
print >> sys.stderr, """
You need to install xmpppy from http://xmpppy.sf.net/.
On Debian-based systems, install the python-xmpp package.
apt-get install python-xmpp
"""
sys.exit(-1)
On ajoute.
try: import sqlite3
except ImportError:
print >> sys.stderr, """
On Debian-based systems, install the sqlite3 package.
apt-get install sqlite3
"""
sys.exit(-1)
On va maintenant charger la base de donnée. Juste après la ligne.
conres=conn.connect()
On ajoute.
''' Gestion Base de donnée '''
BDD = sqlite3.connect('xee.db') # ('xee%s.db' %datetime.now())
REQ = BDD.cursor()
BDD_CUST=None
CUST=None
REQ.execute("""
CREATE TABLE IF NOT EXISTS `synapse`(
`name` TEXT NOT NULL,
`attribute` TEXT NOT NULL DEFAULT '',
`operator` TEXT NOT NULL DEFAULT '',
`value` TEXT NOT NULL DEFAULT ''
)
""")
REQ.execute("""
CREATE TABLE IF NOT EXISTS `dictionary`(
`name` TEXT NOT NULL,
`type` TEXT NOT NULL DEFAULT '',
`genre` TEXT NOT NULL DEFAULT '',
`temps` TEXT NOT NULL DEFAULT '',
`desc` TEXT NOT NULL DEFAULT ''
)
""")
BDD.commit()
Maintenant nous avons un script fonctionnel.
#!/usr/bin/python
# -*- coding: utf8 -*-
import sys, os, string
try: import xmpp
except ImportError:
print >> sys.stderr, """
You need to install xmpppy from http://xmpppy.sf.net/.
On Debian-based systems, install the python-xmpp package.
apt-get install python-xmpp
"""
sys.exit(-1)
try: import sqlite3
except ImportError:
print >> sys.stderr, """
On Debian-based systems, install the sqlite3 package.
apt-get install sqlite3
"""
sys.exit(-1)
intro="""XEE XMPP BOT
GNU/GPL v3
XEE is a bot for the XMPP protocol
Create by BeHuman (craft at ckdevelop.org)"""
############################ bot logic start #####################################
bonjour=["salut", "slt", "bonjour", "bjr", "yop", "yo", "hello", "hi", "lu"]
def messageCB(conn,mess):
text=mess.getBody()
retour="Désolé, je ne suis qu'un bot pré-programmé,\nje ne comprend pas ce que vous me dîtes."
for a in bonjour:
if a in text:
retour="Salut, je suis Xee le bot de "+NameUser+".\nIl n'ai pas là pour le moment."
conn.send(xmpp.Message(mess.getFrom(),retour))
nick=mess.getFrom().getNode()
############################# bot logic stop #####################################
def StepOn(conn):
try:
conn.Process(1)
except KeyboardInterrupt:
return 0
return 1
def GoOn(conn):
while StepOn(conn): pass
def help():
print(intro+"""\nUsage:
xee
Help:
xee -h or --help""")
sys.exit(1)
if len(sys.argv)<2:
if sys.argv[1] == "-h" or sys.argv[1] == "--help":
help()
else:
print("\n[!]Mauvais nombre d\'arguments[!]\n")
help()
else:
if sys.argv[1] == "-h" or sys.argv[1] == "--help":
help()
jid=xmpp.JID(sys.argv[1])
user,server,password=jid.getNode(),jid.getDomain(),sys.argv[2]
conn=xmpp.Client(server)#,debug=[])
conres=conn.connect()
''' Gestion Base de donnée '''
BDD = sqlite3.connect('xee.db') # ('xee%s.db' %datetime.now())
REQ = BDD.cursor()
BDD_CUST=None
CUST=None
REQ.execute("""
CREATE TABLE IF NOT EXISTS `synapse`(
`name` TEXT NOT NULL,
`attribute` TEXT NOT NULL DEFAULT '',
`operator` TEXT NOT NULL DEFAULT '',
`value` TEXT NOT NULL DEFAULT ''
)
""")
REQ.execute("""
CREATE TABLE IF NOT EXISTS `dictionary`(
`name` TEXT NOT NULL,
`type` TEXT NOT NULL DEFAULT '',
`genre` TEXT NOT NULL DEFAULT '',
`temps` TEXT NOT NULL DEFAULT '',
`desc` TEXT NOT NULL DEFAULT ''
)
""")
BDD.commit()
if not conres:
print "Unable to connect to server %s!"%server
sys.exit(1)
if conres<>'tls':
print "Warning: unable to estabilish secure connection - TLS failed!"
authres=conn.auth(user,password)
if not authres:
print "Unable to authorize on %s - check login/password."%server
sys.exit(1)
if authres<>'sasl':
print "Warning: unable to perform SASL auth os %s. Old authentication method used!"%server
conn.RegisterHandler('message',messageCB)
conn.sendInitPresence()
print "Bot started."
GoOn(conn)
Dans la prochaine et avant dernière partie nous allons codé en python les requêtes SQLite pour lier les mots de la DICTIONARY à la table SYSNAPSE
++