wantzel.py 9.1 KB
Newer Older
1 2
#encoding: utf-8
"""
Mindiell's avatar
Mindiell committed
3
Bot Wantzel from La Quadrature du Net.
4

Mindiell's avatar
Mindiell committed
5 6 7 8 9 10 11
License : AGPLv3
Doc     : https://wiki.laquadrature.net/Wantzel

TODO:
- Ajouter la gestion des droits pour certaines commandes
- Mettre une valeur par défaut pour les champs concernés
- Afficher les titres des urls fournies sur le canal
12 13 14 15 16 17 18 19 20 21 22
"""

from irc import IrcClientFactory
import MySQLdb
import re
from twisted.internet import reactor
import urllib

import config
from messages import messages

Mindiell's avatar
Mindiell committed
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
def get_cursor():
    """
    This function connects to a database and returns a usable cursor.
    """
    db = MySQLdb.connect(
        host=config.dbserver,
        user=config.dbuser,
        passwd=config.dbpassword,
        db=config.dbname
    )
    if db:
        return db.cursor()
    return None

def get_url(message, command=""):
    """
    Retrieve the url behind the command.
    """
    # Let's get what is behind the command
    result = re.search("!%s ([^ ]*)" % command, message)
    if not result:
        return ""
    url = result.group(1)
    # Verify the presence of http
    result = re.search("^(https?://)(.+)$", url)
    if not result:
        return "http"
    # Removing anchor if needed
    result = re.search("^([^#]*)", url)
    if result:
        url = result.group(1)
    # Removing trackers
    url = re.sub("[?&](utm_medium|utm_source|utm_campaign|xtor)=[^&]*", "", url)
    return url

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
class Wantzel(object):
    """
    Wantzel bot.
    """
    def __init__(self):
        """
        Initialization of bot over IRC.
        """
        self.irc = IrcClientFactory(config)
        self.irc.set_privmsg = self.set_privmsg
        reactor.connectTCP(config.server, config.port, self.irc)

    def set_privmsg(self):
        """
        This method set the methods to call for each callback received from IRC.
        """
        self.irc.client.privmsg = self.on_privmsg
        self.irc.client.joined = self.on_joined

    def send_message(self, channel, messages):
        """
        Sends a message on specified channel, cutting each line in a new message
        """
        for message in messages.splitlines():
            self.irc.client.msg(channel, message)

    def on_privmsg(self, user, channel, msg):
        """
        Wantzel can understand some commands :
        - help
            Returns a message about how to use the bot.
            If a command is passed after help, the message explains how to use
            the command. 
        - rp(acp)
Mindiell's avatar
Mindiell committed
92
            Add an article in the database
93
        - stats
Mindiell's avatar
Mindiell committed
94
            Show some statistics about the RP
95
        - kill
Mindiell's avatar
Mindiell committed
96
            Kill an article by giving it a score of -100
97 98
        """
        # Cleaning user name
Mindiell's avatar
Mindiell committed
99 100 101 102 103 104 105 106 107
        user = re.search("([^!]*)!", user).group(1)
        print("Message received: %s %s %s" % (user, channel, msg))
        # Never answer to botself
        if user!=config.nickname:
            # If it's a query, bot should answer to the user as the channel
            if "#" not in channel:
                channel = user
            # Help command, specific
            if "wantzel" in msg and ("help" in msg or "aide" in msg):
108
                self.help(user, channel, msg)
Mindiell's avatar
Mindiell committed
109 110 111 112 113 114 115 116 117 118 119 120 121
            # Find known command
            command = re.search("!(rp[acp]*|kill|help|stats)", msg)
            if command:
                command = command.group(1)
                print("Command: %s" % command)
                if command.startswith("rp"):
                    self.rp(command, user, channel, msg)
                elif command=="help":
                    self.help(user, channel, msg)
                elif command=="kill":
                    self.kill(user, channel, msg)
                elif command=="stats":
                    self.stats(user, channel, msg)
Mindiell's avatar
Mindiell committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        # Whatever is done, get the title of an existing url in a message
        if "http" in msg:
            content = ""
            title = ""
            website = ""
            try:
                url = re.search("(http[^ ]*)", msg).group(1)
                website = re.search("//([^/]*)", url).group(1)
                f = urllib.URLopener().open(url)
                content = f.read()
                title = re.search("<title>([^<]+)</title>", content).group(1)
            except:
                pass
            if title and website:
                self.send_message(channel, messages["title"] % (title, website))
137 138 139 140 141

    def on_joined(self, channel):
        """
        Say hello to everyone.
        """
Mindiell's avatar
Mindiell committed
142 143 144 145 146 147
        print("Joined channel %s" % channel)
        # Specific message for specific channel
        if "hello_"+channel[1:] in messages:
            self.send_message(channel, messages["hello_"+channel[1:]])
        else:
            self.send_message(channel, messages["hello"])
148 149 150 151 152 153 154 155

    def help(self, user, channel, msg):
        """
        Show global help.
        If a known command is behind the !help command, an adequate message is
        returned.
        """
        print("help command")
Mindiell's avatar
Mindiell committed
156 157 158 159 160 161 162
        # Searching for a command after help keyword
        command = re.search("!help (stats|rp|help|kill)", msg)
        if command:
            command = command.group(1)
            self.send_message(user, messages["help_"+command])            
        else:
            self.send_message(channel, messages["help"])
163 164 165 166 167 168 169 170

    def rp(self, command, user, channel, msg):
        """
        Adding the article in rp database.
        """
        print("rp command %s" % command)
        cite = 0
        note = 0
Mindiell's avatar
Mindiell committed
171
        url = get_url(msg, command)
172
        print("url: %s" % url)
Mindiell's avatar
Mindiell committed
173 174 175 176 177
        if url=="":
            return
        elif url=="http":
            self.send_message(channel, messages["rp_http"] % user)
            return
178

Mindiell's avatar
Mindiell committed
179 180
        # Looking for such an article in database
        cursor = get_cursor()
181 182 183 184 185 186 187 188 189 190 191 192 193
        cursor.execute("SELECT id, note, provenance FROM presse WHERE url = %s", (url, ))
        rows = cursor.fetchall()
        if not rows:
            # LQdN is quoted
            if "c" in command:
                cite += 2
            # the article speak about LQdN
            if command.count("p")>1:
                cite += 2
            # Archive this article
            if "a" in command:
                note -= 2
            #TODO: Gérer les autres champs qui n'ont pas de valeur par défaut
Mindiell's avatar
Mindiell committed
194 195
            # lang, published, nid, screenshot, title, fetched, seemscite
            print("Adding an article by %s: %s" % (user, url))
196 197 198 199
            result = cursor.execute(
                "INSERT INTO presse SET url=%s, provenance=%s, cite=%s, note=%s, datec=NOW()",
                (url, user, cite, note)
            )
Mindiell's avatar
Mindiell committed
200
            self.send_message(channel, messages["rp_new_article"] % user)
201 202
        else:
            if rows[0][2]!=user:
Mindiell's avatar
Mindiell committed
203
                print("Adding a point by %s on %s" % (user, rows[0][0]))
204 205 206 207 208
                result = cursor.execute(
                    "UPDATE presse SET note=note+1 WHERE id=%s",
                    (rows[0][0], )
                )
            if (rows[0][1]+1)<3:
Mindiell's avatar
Mindiell committed
209
                self.send_message(channel, messages["rp_known_article"] % user)
210
            else:
Mindiell's avatar
Mindiell committed
211
                self.send_message(channel, messages["rp_taken_article"] % user)
212 213 214

    def kill(self, user, channel, msg):
        """
Mindiell's avatar
Mindiell committed
215
        Kill an article by setting its score to -100.
216
        """
Mindiell's avatar
Mindiell committed
217
        #TODO: Gérer les droits de cette commande
218
        print("kill command")
Mindiell's avatar
Mindiell committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        url = get_url(msg, "kill")
        print("url: %s" % url)
        if url=="":
            return
        elif url=="http":
            self.send_message(channel, messages["rp_http"] % user)
            return
        # Looking for such an article in database
        cursor = get_cursor()
        cursor.execute("SELECT id, note FROM presse WHERE url=%s", (url, ))
        rows = cursor.fetchall()
        if not rows:
            self.send_message(channel, messages["kill_none"] % url)
        else:
            cursor.execute("UPDATE presse SET note=-100 WHERE id=%s", (rows[0][0], ))
            self.send_message(channel, messages["kill_done"] % url)
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249

    def stats(self, user, channel, msg):
        """
        Returns stats on articles in press review.
        """
        print("stats command")
        db = MySQLdb.connect(host="localhost", user="root", passwd="root", db="site")
        cursor = db.cursor()
        periods = [1, 3, 7, 15]
        notes = [0, 3 ,4]
        notnull = 0
        somethingatall = 0
        result = ""
        for note in notes:
            notnull = 0
Mindiell's avatar
Mindiell committed
250
            result = result + "note>=%s: " % note
251 252 253 254 255 256 257 258 259 260 261 262
            for period in periods:
                cursor.execute(
                    """SELECT COUNT(id) AS cid FROM presse 
                    WHERE nid=0
                    AND datec>(NOW()-INTERVAL %s DAY)
                    AND note>=%s""",
                    (period, note)
                )
                rows = cursor.fetchall()
                if rows[0][0]>0:
                    result = result + "%sj:%s, " % (period, rows[0][0])
                    notnull = 1
Mindiell's avatar
Mindiell committed
263
                    somethingatall = 1
264 265
            if notnull:
                result = result[:-2] + "\n"
Mindiell's avatar
Mindiell committed
266 267
        if somethingatall==0:
            result = messages["stats_bravo"] % periods[-1]
268 269 270 271 272 273
        self.send_message(channel, result)


if __name__ == '__main__':
    wantzel = Wantzel()
    reactor.run()