wantzel.py 8.48 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)
122
123
124
125
126

    def on_joined(self, channel):
        """
        Say hello to everyone.
        """
Mindiell's avatar
Mindiell committed
127
128
129
130
131
132
        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"])
133
134
135
136
137
138
139
140

    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
141
142
143
144
145
146
147
        # 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"])
148
149
150
151
152
153
154
155

    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
156
        url = get_url(msg, command)
157
        print("url: %s" % url)
Mindiell's avatar
Mindiell committed
158
159
160
161
162
        if url=="":
            return
        elif url=="http":
            self.send_message(channel, messages["rp_http"] % user)
            return
163

Mindiell's avatar
Mindiell committed
164
165
        # Looking for such an article in database
        cursor = get_cursor()
166
167
168
169
170
171
172
173
174
175
176
177
178
        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
179
180
            # lang, published, nid, screenshot, title, fetched, seemscite
            print("Adding an article by %s: %s" % (user, url))
181
182
183
184
            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
185
            self.send_message(channel, messages["rp_new_article"] % user)
186
187
        else:
            if rows[0][2]!=user:
Mindiell's avatar
Mindiell committed
188
                print("Adding a point by %s on %s" % (user, rows[0][0]))
189
190
191
192
193
                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
194
                self.send_message(channel, messages["rp_known_article"] % user)
195
            else:
Mindiell's avatar
Mindiell committed
196
                self.send_message(channel, messages["rp_taken_article"] % user)
197
198
199

    def kill(self, user, channel, msg):
        """
Mindiell's avatar
Mindiell committed
200
        Kill an article by setting its score to -100.
201
        """
Mindiell's avatar
Mindiell committed
202
        #TODO: Gérer les droits de cette commande
203
        print("kill command")
Mindiell's avatar
Mindiell committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
        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)
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234

    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
235
            result = result + "note>=%s: " % note
236
237
238
239
240
241
242
243
244
245
246
247
            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
248
                    somethingatall = 1
249
250
            if notnull:
                result = result[:-2] + "\n"
Mindiell's avatar
Mindiell committed
251
252
        if somethingatall==0:
            result = messages["stats_bravo"] % periods[-1]
253
254
255
256
257
258
        self.send_message(channel, result)


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