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

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

TODO:
Mindiell's avatar
Mindiell committed
9
10
11
12
13
- Ajouter des commandes permettant de gérer le mediakit (moderators only)
    - Parser les urls et voir ce qu'on peut faire:
        - upload de vidéo
        - tag de vidéo
        - obtenir un lien vers une vidéo
14
15
16
"""

import re
Mindiell's avatar
Mindiell committed
17
18
import sqlite3
import time
19
20
21
22

import feedparser
from irc import IrcClientFactory
import MySQLdb
23
from twisted.internet import reactor
Mindiell's avatar
Mindiell committed
24
from twitter import Twitter, OAuth
25
26
27
28

import config
from messages import messages

Mindiell's avatar
Mindiell committed
29
30
31
32
33
34
35
36
LOG_FILE = "wantzel.log"
DEBUG = 3
WARNING = 2
INFO = 1
ERROR = 0
LOG_LEVEL = DEBUG

class Utils(object):
37
38
39
    """
    Simple utility class to log easily.
    """
Mindiell's avatar
Mindiell committed
40
41
    @classmethod
    def log(cls, message):
42
43
44
45
46
        """
        Logging message with timestamp.
        """
        actual_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        with open(LOG_FILE, 'a') as file_handle:
47
            try:
48
49
50
                file_handle.write("%s: %s\n" % (actual_time, message.encode("utf-8")))
            except Exception:
                file_handle.write("%s: Erreur de log\n" % actual_time)
51
                try:
52
53
54
                    file_handle.write("%s: %s\n" % (actual_time, message))
                except Exception:
                    file_handle.write("%s: Seconde erreur de log\n" % actual_time)
Mindiell's avatar
Mindiell committed
55
56
57

    @classmethod
    def debug(cls, message):
58
59
60
61
        """
        Manage DEBUG level of logging.
        """
        if LOG_LEVEL >= DEBUG:
Mindiell's avatar
Mindiell committed
62
63
64
65
            cls.log("%s: %s" % ("DEBUG", message))

    @classmethod
    def warning(cls, message):
66
67
68
69
        """
        Manage WARNING level of logging.
        """
        if LOG_LEVEL >= WARNING:
Mindiell's avatar
Mindiell committed
70
71
72
73
            cls.log("%s: %s" % ("WARNING", message))

    @classmethod
    def info(cls, message):
74
75
76
77
        """
        Manage INFO level of logging.
        """
        if LOG_LEVEL >= INFO:
Mindiell's avatar
Mindiell committed
78
79
80
81
            cls.log("%s: %s" % ("INFO", message))

    @classmethod
    def error(cls, message):
82
83
84
85
        """
        Manage ERROR level of logging.
        """
        if LOG_LEVEL >= ERROR:
Mindiell's avatar
Mindiell committed
86
87
88
89
            cls.log("%s: %s" % ("ERROR", message))



Mindiell's avatar
Mindiell committed
90
91
def get_cursor():
    """
Mindiell's avatar
Mindiell committed
92
    This function connects to a MySQL database and returns a usable cursor.
Mindiell's avatar
Mindiell committed
93
    """
Mindiell's avatar
Mindiell committed
94
    connection = MySQLdb.connect(
Mindiell's avatar
Mindiell committed
95
96
97
98
99
        host=config.dbserver,
        user=config.dbuser,
        passwd=config.dbpassword,
        db=config.dbname
    )
Mindiell's avatar
Mindiell committed
100
101
    if connection:
        return connection.cursor()
Mindiell's avatar
Mindiell committed
102
103
    return None

104

105
def get_url(message):
Mindiell's avatar
Mindiell committed
106
    """
107
    Retrieve the url in the message.
Mindiell's avatar
Mindiell committed
108
    """
109
110
    # Let's get the url
    result = re.search("(https?[^ ]+)", message)
Mindiell's avatar
Mindiell committed
111
112
    if not result:
        return "http"
113
    url = result.group(1)
Mindiell's avatar
Mindiell committed
114
115
116
117
118
119
120
121
    # 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

122

Mindiell's avatar
Mindiell committed
123
124
125
126
127
128
129
def is_moderator(name):
    """
    This function verify if a user is a moderator.
    """
    connection = sqlite3.connect(config.sqlite_db)
    cursor = connection.cursor()
    cursor.execute("SELECT count(*) FROM moderator WHERE name=?", (name, ))
130
    if int(cursor.fetchone()[0]) == 1:
Mindiell's avatar
Mindiell committed
131
132
133
134
        return True
    return False


135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def tweet(message):
    """
    Tweet message on specified account
    """
    Utils.debug("tweet method")
    auth = OAuth(
        config.TOKEN,
        config.TOKENSEC,
        config.CONSKEY,
        config.CONSSEC
    )
    twitter = Twitter(auth=auth)
    try:
        Utils.debug("Tweeting: %s" % message)
        twitter.statuses.update(status=message)
    except Exception:
        pass


154
155
156
157
158
159
160
161
class Wantzel(object):
    """
    Wantzel bot.
    """
    def __init__(self):
        """
        Initialization of bot over IRC.
        """
162
        self.number = None
Mindiell's avatar
Mindiell committed
163
164
165
166
167
168
169
170
171
        # default last_entry_published
        self.last_entry_published = time.strptime("2000-01-01", "%Y-%m-%d")
        # See if there is something in the db
        connection = sqlite3.connect(config.sqlite_db)
        for row in connection.execute("SELECT last_entry_published FROM tweets"):
            self.last_entry_published = time.strptime(
                row[0].encode("utf-8"),
                "%Y-%m-%d %H:%M:%S %Z"
            )
172
        Utils.debug("Dernier tweet: %s" % self.last_entry_published)
173
174
175
        self.irc = IrcClientFactory(config)
        self.irc.set_privmsg = self.set_privmsg
        reactor.connectTCP(config.server, config.port, self.irc)
Mindiell's avatar
Mindiell committed
176
177
178
179
180
181
182
        # Prepare timer
        reactor.callLater(config.timer, self.timer)

    def timer(self):
        """
        This method launches function regularly (see config.timer).
        """
Mindiell's avatar
Mindiell committed
183
        Utils.debug("Timer called")
Mindiell's avatar
Mindiell committed
184
185
186
187
188
        self.rp_to_twitter("http://www.laquadrature.net/fr/revue-de-presse/feed")
        self.rp_to_twitter("http://www.laquadrature.net/en/press-review/feed")
        self.count_articles()
        # Recalling the timer
        reactor.callLater(config.timer, self.timer)
189
190
191
192
193
194
195

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

196
    def send_message(self, channel, multiline_message):
197
198
199
        """
        Sends a message on specified channel, cutting each line in a new message
        """
200
        for message in multiline_message.splitlines():
201
202
203
204
            self.irc.client.msg(channel, message)

    def on_privmsg(self, user, channel, msg):
        """
Mindiell's avatar
Mindiell committed
205
206
        Wantzel can understand a lot of commands. Commands followed by a (*)
        are accessible only to moderators:
207
208
209
        - help
            Returns a message about how to use the bot.
            If a command is passed after help, the message explains how to use
210
            the command.
211
        - rp(acp)
Mindiell's avatar
Mindiell committed
212
            Add an article in the database
213
        - stats
Mindiell's avatar
Mindiell committed
214
            Show some statistics about the RP
Mindiell's avatar
Mindiell committed
215
        - kill (*)
Mindiell's avatar
Mindiell committed
216
            Kill an article by giving it a score of -100
217
        - admin list (*)
Mindiell's avatar
Mindiell committed
218
            List rights in private
219
        - admin add (*)
220
221
222
            Add one or more new moderator to list
        - admin del (*)
            Delete one or more moderator from list
223
        - admin timer
224
            Relaunch a timer
225
226
        """
        # Cleaning user name
Mindiell's avatar
Mindiell committed
227
        user = re.search("([^!]*)!", user).group(1)
Mindiell's avatar
Mindiell committed
228
        Utils.debug("Message received: %s %s %s" % (user, channel, msg))
Mindiell's avatar
Mindiell committed
229
        # Never answer to botself
230
        if user != config.nickname:
Mindiell's avatar
Mindiell committed
231
232
233
234
235
            # 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):
236
                self.help(channel, msg)
Mindiell's avatar
Mindiell committed
237
            # Find known command
238
            command = re.search("[!~](rp[acp]*|kill|help|stats|admin)", msg)
Mindiell's avatar
Mindiell committed
239
            Utils.debug("Command: %s" % command)
Mindiell's avatar
Mindiell committed
240
            if command:
Mindiell's avatar
Mindiell committed
241
                Utils.debug("group(0): %s" % command.group(0))
242
243
                if command.group(0).startswith('!'):
                    self.send_message(channel, messages["new_starter"])
Mindiell's avatar
Mindiell committed
244
                command = command.group(1)
Mindiell's avatar
Mindiell committed
245
                Utils.debug("Command: %s" % command)
Mindiell's avatar
Mindiell committed
246
                if command.startswith("rp"):
Mindiell's avatar
Mindiell committed
247
                    Utils.debug("Calling self.rp")
248
                    self.rp(command, user, channel, msg)
249
                elif command == "help":
Mindiell's avatar
Mindiell committed
250
                    Utils.debug("Calling self.help")
251
252
                    self.help(channel, msg)
                elif command == "kill":
Mindiell's avatar
Mindiell committed
253
                    Utils.debug("Calling self.kill")
Mindiell's avatar
Mindiell committed
254
                    self.kill(user, channel, msg)
255
                elif command == "stats":
Mindiell's avatar
Mindiell committed
256
                    Utils.debug("Calling self.stats")
257
258
                    self.stats(channel)
                elif command == "admin":
Mindiell's avatar
Mindiell committed
259
                    Utils.debug("Calling self.admin")
Mindiell's avatar
Mindiell committed
260
                    self.admin(user, channel, msg)
Mindiell's avatar
Mindiell committed
261
262
263
        # No more giving the title of an url
        #if title and website:
        #    self.send_message(channel, messages["title"] % (title, website))
264

265
    def help(self, channel, msg):
266
267
        """
        Show global help.
268
        If a known command is behind the ~help command, an adequate message is
269
270
        returned.
        """
Mindiell's avatar
Mindiell committed
271
        Utils.debug("help command")
Mindiell's avatar
Mindiell committed
272
        # Searching for a command after help keyword
273
        command = re.search("~help (help|rp|stats|kill|admin)", msg)
Mindiell's avatar
Mindiell committed
274
275
        if command:
            command = command.group(1)
276
            self.send_message(channel, messages["help_"+command])
Mindiell's avatar
Mindiell committed
277
278
        else:
            self.send_message(channel, messages["help"])
279

280
    def rp(self, command, user, channel, msg):
281
282
283
        """
        Adding the article in rp database.
        """
Mindiell's avatar
Mindiell committed
284
285
286
287
        Utils.debug("rp command : %s" % command)
        Utils.debug("rp user : %s" % user)
        Utils.debug("rp channel : %s" % channel)
        Utils.debug("rp msg : %s" % msg)
288
        cite = 0
289
        note = 1
290
        url = get_url(msg)
Mindiell's avatar
Mindiell committed
291
        Utils.debug("url: %s" % url)
292
        if url == "":
Mindiell's avatar
Mindiell committed
293
            return
294
        elif url == "http":
Mindiell's avatar
Mindiell committed
295
296
            self.send_message(channel, messages["rp_http"] % user)
            return
297

Mindiell's avatar
Mindiell committed
298
299
        # Looking for such an article in database
        cursor = get_cursor()
300
301
302
303
304
305
306
        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
307
            if command.count("p") > 1:
308
309
310
                cite += 2
            # Archive this article
            if "a" in command:
311
                note = -2
Mindiell's avatar
Mindiell committed
312
            Utils.debug("Adding an article by %s: %s" % (user, url))
313
314
            cursor.execute(
                """INSERT INTO presse SET
315
                url=%s, provenance=%s, cite=%s, note=%s, datec=NOW(), title='',
316
317
                lang='', published=0, nid=0, screenshot=0, fetched=0, seemscite=0
                """,
318
                (url, user, cite, note)
319
            )
Mindiell's avatar
Mindiell committed
320
            self.send_message(channel, messages["rp_new_article"] % user)
321
        else:
322
            if rows[0][2] != user:
Mindiell's avatar
Mindiell committed
323
                Utils.debug("Adding a point by %s on %s" % (user, rows[0][0]))
324
                cursor.execute(
325
326
327
                    "UPDATE presse SET note=note+1 WHERE id=%s",
                    (rows[0][0], )
                )
328
            if (rows[0][1]+1) < 3:
Mindiell's avatar
Mindiell committed
329
                self.send_message(channel, messages["rp_known_article"] % user)
330
            else:
Mindiell's avatar
Mindiell committed
331
                self.send_message(channel, messages["rp_taken_article"] % user)
Mindiell's avatar
Mindiell committed
332
333
                # Update number of articles to do
                self.count_articles()
334
335
336

    def kill(self, user, channel, msg):
        """
Mindiell's avatar
Mindiell committed
337
        Kill an article by setting its score to -100.
338
        """
Mindiell's avatar
Mindiell committed
339
        Utils.debug("kill command")
Mindiell's avatar
Mindiell committed
340
341
        if is_moderator(user):
            url = get_url(msg)
Mindiell's avatar
Mindiell committed
342
            Utils.debug("url: %s" % url)
343
            if url == "":
Mindiell's avatar
Mindiell committed
344
                return
345
            elif url == "http":
Mindiell's avatar
Mindiell committed
346
347
348
349
350
351
352
353
354
355
356
                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)
Mindiell's avatar
Mindiell committed
357
        else:
Mindiell's avatar
Mindiell committed
358
            self.send_message(channel, messages["not_moderator"])
359

360
    def stats(self, channel):
361
362
363
        """
        Returns stats on articles in press review.
        """
Mindiell's avatar
Mindiell committed
364
        Utils.debug("stats command")
Mindiell's avatar
Mindiell committed
365
        cursor = get_cursor()
366
        periods = [1, 3, 7, 15]
367
        notes = [0, 3, 4]
368
369
370
371
372
        notnull = 0
        somethingatall = 0
        result = ""
        for note in notes:
            notnull = 0
Mindiell's avatar
Mindiell committed
373
            result = result + "note>=%s: " % note
374
375
            for period in periods:
                cursor.execute(
376
                    """SELECT COUNT(id) AS cid FROM presse
377
378
379
380
381
382
                    WHERE nid=0
                    AND datec>(NOW()-INTERVAL %s DAY)
                    AND note>=%s""",
                    (period, note)
                )
                rows = cursor.fetchall()
383
                if rows[0][0] > 0:
384
385
                    result = result + "%sj:%s, " % (period, rows[0][0])
                    notnull = 1
Mindiell's avatar
Mindiell committed
386
                    somethingatall = 1
387
388
            if notnull:
                result = result[:-2] + "\n"
389
        if somethingatall == 0:
Mindiell's avatar
Mindiell committed
390
            result = messages["stats_bravo"] % periods[-1]
391
392
        self.send_message(channel, result)

Mindiell's avatar
Mindiell committed
393
394
395
    def admin(self, user, channel, msg):
        """
        Manage moderation.
396
        A sub-command should be behind the ~admin command.
Mindiell's avatar
Mindiell committed
397
        """
Mindiell's avatar
Mindiell committed
398
        Utils.debug("admin command")
Mindiell's avatar
Mindiell committed
399
        # Searching for a command after admin keyword
Mindiell's avatar
Mindiell committed
400
        command = re.search("~admin (list|add|del|timer)", msg)
Mindiell's avatar
Mindiell committed
401
402
        if command:
            command = command.group(1)
403
404
405
            if command == "list":
                self.admin_list(user, channel)
            elif command == "add":
Mindiell's avatar
Mindiell committed
406
                self.admin_add(user, channel, msg)
407
            elif command == "del":
Mindiell's avatar
Mindiell committed
408
                self.admin_del(user, channel, msg)
409
410
            elif command == "timer":
                self.admin_timer(user, channel)
Mindiell's avatar
Mindiell committed
411

412
    def admin_list(self, user, channel):
Mindiell's avatar
Mindiell committed
413
414
415
        """
        List actual moderators.
        """
Mindiell's avatar
Mindiell committed
416
        Utils.debug("admin_list command")
Mindiell's avatar
Mindiell committed
417
418
419
420
421
422
423
424
425
426
427
428
429
        if is_moderator(user):
            connection = sqlite3.connect(config.sqlite_db)
            names = []
            for row in connection.execute("SELECT name FROM moderator"):
                names.append(row[0].encode("utf-8"))
            self.send_message(channel, messages["admin_list"] % ", ".join(names))
        else:
            self.send_message(channel, messages["not_moderator"])

    def admin_add(self, user, channel, msg):
        """
        Add some new moderators if not existing yet.
        """
Mindiell's avatar
Mindiell committed
430
        Utils.debug("admin_add command")
Mindiell's avatar
Mindiell committed
431
432
433
434
        if is_moderator(user):
            try:
                names = []
                connection = sqlite3.connect(config.sqlite_db)
435
                result = re.search("~admin add (([^,]+, ?)+)?(.*)", msg)
Mindiell's avatar
Mindiell committed
436
                if result.group(1):
437
                    names = [name for name in result.group(1).split(", ") if name != ""]
Mindiell's avatar
Mindiell committed
438
439
440
441
442
                names.append(result.group(3))
                # Do not add actual moderators
                moderators = []
                for row in connection.execute("SELECT name FROM moderator"):
                    moderators.append(row[0].encode("utf-8"))
443
                names = list(set([name for name in names if name not in moderators]))
Mindiell's avatar
Mindiell committed
444
445
446
447
448
449
450
451
                if names:
                    # Converting set in list of tuples
                    values = [(name,) for name in names]
                    connection.executemany("INSERT INTO moderator (name) VALUES (?)", values)
                    connection.commit()
                    self.send_message(channel, messages["admin_add"] % ", ".join(names))
                else:
                    self.send_message(channel, messages["admin_add_empty"])
452
            except Exception:
Mindiell's avatar
Mindiell committed
453
454
455
456
457
458
459
460
                pass
        else:
            self.send_message(channel, messages["not_moderator"])

    def admin_del(self, user, channel, msg):
        """
        Delete a moderator from list.
        """
Mindiell's avatar
Mindiell committed
461
        Utils.debug("admin_del command")
Mindiell's avatar
Mindiell committed
462
463
464
        if is_moderator(user):
            try:
                names = []
465
                result = re.search("~admin del (([^,]+, ?)+)?(.*)", msg)
Mindiell's avatar
Mindiell committed
466
                if result.group(1):
467
                    names = [name for name in result.group(1).split(", ") if name != ""]
Mindiell's avatar
Mindiell committed
468
                names.append(result.group(3))
469
                names = list(set(names))
Mindiell's avatar
Mindiell committed
470
                Utils.debug(names)
Mindiell's avatar
Mindiell committed
471
472
473
474
475
                connection = sqlite3.connect(config.sqlite_db)
                for name in names:
                    connection.execute("DELETE FROM moderator WHERE name=?", (name, ))
                connection.commit()
                self.send_message(channel, messages["admin_del"] % ", ".join(names))
476
            except Exception:
Mindiell's avatar
Mindiell committed
477
478
479
480
                pass
        else:
            self.send_message(channel, messages["not_moderator"])

481
    def admin_timer(self, user, channel):
482
483
484
485
486
487
488
489
        """
        Relaunch a timer.
        """
        Utils.debug("admin_timer command")
        if is_moderator(user):
            try:
                # Recalling the timer
                reactor.callLater(config.timer, self.timer)
490
            except Exception:
491
492
493
494
                pass
        else:
            self.send_message(channel, messages["not_moderator"])

Mindiell's avatar
Mindiell committed
495
496
497
498
499
    def count_articles(self):
        """
        Count number of articles not done in RP and updates the topic of the
        press review channel if needed.
        """
Mindiell's avatar
Mindiell committed
500
        Utils.debug("count_articles method")
Mindiell's avatar
Mindiell committed
501
502
503
504
505
506
507
        cursor = get_cursor()
        cursor.execute("""SELECT COUNT(*) FROM presse
            WHERE DATE_SUB(NOW(), INTERVAL 2 MONTH)<datec
            AND note > 2
            AND nid = 0""")
        rows = cursor.fetchall()
        number = int(rows[0][0])
508
        Utils.debug("Found %s articles." % number)
509
        if self.number != number:
Mindiell's avatar
Mindiell committed
510
            self.irc.client.topic("#lqdn-rp", messages["topic"] % number)
Mindiell's avatar
Mindiell committed
511
512
513
514
515
516
        self.number = number

    def rp_to_twitter(self, rss):
        """
        By parsing the RSS feed of the press-review, we know what to tweet.
        """
Mindiell's avatar
Mindiell committed
517
        Utils.debug("rp_to_twitter method")
Mindiell's avatar
Mindiell committed
518
519
        now = time.localtime()
        today = time.strptime("%s-%s-%s %s" % (
520
521
522
523
524
            now.tm_year,
            now.tm_mon,
            now.tm_mday,
            time.tzname[0]
            ), "%Y-%m-%d %Z")
Mindiell's avatar
Mindiell committed
525
526
527
        language = "fr"
        if "/en/" in rss:
            language = "en"
Mindiell's avatar
Mindiell committed
528
529
        entries = feedparser.parse(rss)['entries']
        entries.reverse()
530
        Utils.debug(self.last_entry_published)
Mindiell's avatar
Mindiell committed
531
532
533
534
535
        for entry in entries:
            # if date of publication is greater than today, midnight, and
            # lesser than future
            if today < entry.published_parsed < now:
                if self.last_entry_published < entry.published_parsed:
536
                    tweet(messages["tweet_rp_%s" % language] % (
Mindiell's avatar
Mindiell committed
537
538
539
                        entry.title.encode("utf-8"),
                        entry.link.encode("utf-8")
                    ))
Mindiell's avatar
Mindiell committed
540
                    Utils.debug(entry.published_parsed)
Mindiell's avatar
Mindiell committed
541
                    Utils.debug(entry.title)
Mindiell's avatar
Mindiell committed
542
543
544
545
546
547
548
549
550
551
552
553
554
555
                    # Save last_entry_published
                    self.last_entry_published = entry.published_parsed
                    last_entry_published = time.strftime(
                        "%Y-%m-%d %H:%M:%S %Z",
                        self.last_entry_published
                    )
                    connection = sqlite3.connect(config.sqlite_db)
                    connection.execute(
                        "UPDATE tweets SET last_entry_published=?",
                        (last_entry_published,)
                    )
                    connection.commit()
                    # Tweet only one message in order not to spam
                    return
556
557
558
                else:
                    Utils.debug(entry.title)
                    Utils.debug(entry.published_parsed)
Mindiell's avatar
Mindiell committed
559

560
561

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