wantzel.py 19.8 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
License : AGPLv3
Doc     : https://wiki.laquadrature.net/Wantzel

TODO:
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 feedparser
17
import HTMLParser
18
import importlib
19 20 21
from irc import IrcClientFactory
import MySQLdb
import re
22 23
import sqlite3
import time
24
from twisted.internet import reactor
25
from twitter import Twitter, OAuth
26 27 28 29 30
import urllib

import config
from messages import messages

Mindiell's avatar
Mindiell committed
31 32 33 34 35 36 37 38 39 40 41
LOG_FILE = "wantzel.log"
DEBUG = 3
WARNING = 2
INFO = 1
ERROR = 0
LOG_LEVEL = DEBUG

class Utils(object):
    @classmethod
    def log(cls, message):
        with open(LOG_FILE, 'a') as f:
42 43 44 45 46 47 48 49
            try:
                f.write("%s: %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), message.encode("utf-8")))
            except:
                f.write("%s: Erreur de log\n" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                try:
                    f.write("%s: %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), message))
                except:
                    f.write("%s: Seconde erreur de log\n" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
Mindiell's avatar
Mindiell committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

    @classmethod
    def debug(cls, message):
        if LOG_LEVEL>=DEBUG:
            cls.log("%s: %s" % ("DEBUG", message))

    @classmethod
    def warning(cls, message):
        if LOG_LEVEL>=WARNING:
            cls.log("%s: %s" % ("WARNING", message))

    @classmethod
    def info(cls, message):
        if LOG_LEVEL>=INFO:
            cls.log("%s: %s" % ("INFO", message))

    @classmethod
    def error(cls, message):
        if LOG_LEVEL>=ERROR:
            cls.log("%s: %s" % ("ERROR", message))



Mindiell's avatar
Mindiell committed
73 74
def get_cursor():
    """
75
    This function connects to a MySQL database and returns a usable cursor.
Mindiell's avatar
Mindiell committed
76
    """
77
    connection = MySQLdb.connect(
Mindiell's avatar
Mindiell committed
78 79 80 81 82
        host=config.dbserver,
        user=config.dbuser,
        passwd=config.dbpassword,
        db=config.dbname
    )
83 84
    if connection:
        return connection.cursor()
Mindiell's avatar
Mindiell committed
85 86
    return None

87
def get_url(message):
Mindiell's avatar
Mindiell committed
88
    """
89
    Retrieve the url in the message.
Mindiell's avatar
Mindiell committed
90
    """
91 92
    # Let's get the url
    result = re.search("(https?[^ ]+)", message)
Mindiell's avatar
Mindiell committed
93 94
    if not result:
        return "http"
95
    url = result.group(1)
Mindiell's avatar
Mindiell committed
96 97 98 99 100 101 102 103
    # 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

104 105 106
def get_title(message):
    title = ""
    website = ""
107 108 109 110
    exceptions = [
        "twitter.com",
        "github.com",
    ]
111
    try:
112 113 114 115
        url = get_url(message)
        for exception in exceptions:
            if exception in url:
                return ("", "")
116 117 118 119
        website = re.search("//([^/]*)", url).group(1)
        f = urllib.URLopener().open(url)
        content = f.read()
        title = re.search("<title>([^<]+)</title>", content).group(1)
120 121
        # Unescaping HTML entities and removing multiple lines
        title = HTMLParser.HTMLParser().unescape(re.sub("\n|\r", "", title))
122
    except:
123
        return ("", "")
124 125
    return (title, website)

126 127 128 129 130 131 132 133 134 135 136 137
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, ))
    if int(cursor.fetchone()[0])==1:
        return True
    return False


138 139 140 141 142 143 144 145
class Wantzel(object):
    """
    Wantzel bot.
    """
    def __init__(self):
        """
        Initialization of bot over IRC.
        """
146
        self.number = None
147 148 149 150 151 152 153 154 155
        # 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"
            )
156
        Utils.debug("Dernier tweet: %s" % self.last_entry_published)
157 158 159
        self.irc = IrcClientFactory(config)
        self.irc.set_privmsg = self.set_privmsg
        reactor.connectTCP(config.server, config.port, self.irc)
160 161 162 163 164 165 166
        # Prepare timer
        reactor.callLater(config.timer, self.timer)

    def timer(self):
        """
        This method launches function regularly (see config.timer).
        """
Mindiell's avatar
Mindiell committed
167
        Utils.debug("Timer called")
168 169 170 171 172
        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)
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

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

    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):
        """
189 190
        Wantzel can understand a lot of commands. Commands followed by a (*)
        are accessible only to moderators:
191 192 193 194 195
        - 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
196
            Add an article in the database
197
        - stats
Mindiell's avatar
Mindiell committed
198
            Show some statistics about the RP
199
        - kill (*)
Mindiell's avatar
Mindiell committed
200
            Kill an article by giving it a score of -100
201
        - admin list (*)
202
            List rights in private
203
        - admin add (*)
204
            Add a new moderator to list
205
        - admin remove (*)
206
            Remove a moderator from list
207
        - admin timer
208
            Relaunch a timer
209 210
        """
        # Cleaning user name
Mindiell's avatar
Mindiell committed
211
        user = re.search("([^!]*)!", user).group(1)
Mindiell's avatar
Mindiell committed
212
        Utils.debug("Message received: %s %s %s" % (user, channel, msg))
213
        # Whatever is done, get the title of an existing url in a message
214 215 216
        title = ""
        if "http" in msg:
            title, website = get_title(msg)
Mindiell's avatar
Mindiell committed
217 218 219 220 221 222 223
        # 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):
224
                self.help(user, channel, msg)
Mindiell's avatar
Mindiell committed
225
            # Find known command
226
            command = re.search("[!~](rp[acp]*|kill|help|stats|admin)", msg)
Mindiell's avatar
Mindiell committed
227
            Utils.debug("Command: %s" % command)
Mindiell's avatar
Mindiell committed
228
            if command:
Mindiell's avatar
Mindiell committed
229
                Utils.debug("group(0): %s" % command.group(0))
230 231
                if command.group(0).startswith('!'):
                    self.send_message(channel, messages["new_starter"])
Mindiell's avatar
Mindiell committed
232
                command = command.group(1)
Mindiell's avatar
Mindiell committed
233
                Utils.debug("Command: %s" % command)
Mindiell's avatar
Mindiell committed
234
                if command.startswith("rp"):
Mindiell's avatar
Mindiell committed
235
                    Utils.debug("Calling self.rp")
236
                    self.rp(command, user, channel, msg)
Mindiell's avatar
Mindiell committed
237
                elif command=="help":
Mindiell's avatar
Mindiell committed
238
                    Utils.debug("Calling self.help")
Mindiell's avatar
Mindiell committed
239 240
                    self.help(user, channel, msg)
                elif command=="kill":
Mindiell's avatar
Mindiell committed
241
                    Utils.debug("Calling self.kill")
Mindiell's avatar
Mindiell committed
242 243
                    self.kill(user, channel, msg)
                elif command=="stats":
Mindiell's avatar
Mindiell committed
244
                    Utils.debug("Calling self.stats")
Mindiell's avatar
Mindiell committed
245
                    self.stats(user, channel, msg)
246
                elif command=="admin":
Mindiell's avatar
Mindiell committed
247
                    Utils.debug("Calling self.admin")
248
                    self.admin(user, channel, msg)
249 250 251
        # No more giving the title of an url
        #if title and website:
        #    self.send_message(channel, messages["title"] % (title, website))
252 253 254 255

    def help(self, user, channel, msg):
        """
        Show global help.
256
        If a known command is behind the ~help command, an adequate message is
257 258
        returned.
        """
Mindiell's avatar
Mindiell committed
259
        Utils.debug("help command")
Mindiell's avatar
Mindiell committed
260
        # Searching for a command after help keyword
261
        command = re.search("~help (help|rp|stats|kill|admin|timer)", msg)
Mindiell's avatar
Mindiell committed
262 263
        if command:
            command = command.group(1)
264
            self.send_message(channel, messages["help_"+command])            
Mindiell's avatar
Mindiell committed
265 266
        else:
            self.send_message(channel, messages["help"])
267

268
    def rp(self, command, user, channel, msg):
269 270 271
        """
        Adding the article in rp database.
        """
Mindiell's avatar
Mindiell committed
272 273 274 275
        Utils.debug("rp command : %s" % command)
        Utils.debug("rp user : %s" % user)
        Utils.debug("rp channel : %s" % channel)
        Utils.debug("rp msg : %s" % msg)
276
        cite = 0
277
        note = 1
278
        url = get_url(msg)
Mindiell's avatar
Mindiell committed
279
        Utils.debug("url: %s" % url)
Mindiell's avatar
Mindiell committed
280 281 282 283 284
        if url=="":
            return
        elif url=="http":
            self.send_message(channel, messages["rp_http"] % user)
            return
285

Mindiell's avatar
Mindiell committed
286 287
        # Looking for such an article in database
        cursor = get_cursor()
288 289 290 291 292 293 294 295 296 297 298
        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:
299
                note = -2
Mindiell's avatar
Mindiell committed
300
            Utils.debug("Adding an article by %s: %s" % (user, url))
301
            result = cursor.execute(
302
                """INSERT INTO presse SET 
303
                url=%s, provenance=%s, cite=%s, note=%s, datec=NOW(), title='',
304 305
                lang='', published=0, nid=0, screenshot=0, fetched=0, seemscite=0
                """,
306
                (url, user, cite, note)
307
            )
Mindiell's avatar
Mindiell committed
308
            self.send_message(channel, messages["rp_new_article"] % user)
309 310
        else:
            if rows[0][2]!=user:
Mindiell's avatar
Mindiell committed
311
                Utils.debug("Adding a point by %s on %s" % (user, rows[0][0]))
312 313 314 315 316
                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
317
                self.send_message(channel, messages["rp_known_article"] % user)
318
            else:
Mindiell's avatar
Mindiell committed
319
                self.send_message(channel, messages["rp_taken_article"] % user)
320 321
                # Update number of articles to do
                self.count_articles()
322 323 324

    def kill(self, user, channel, msg):
        """
Mindiell's avatar
Mindiell committed
325
        Kill an article by setting its score to -100.
326
        """
Mindiell's avatar
Mindiell committed
327
        Utils.debug("kill command")
328 329
        if is_moderator(user):
            url = get_url(msg)
Mindiell's avatar
Mindiell committed
330
            Utils.debug("url: %s" % url)
331 332 333 334 335 336 337 338 339 340 341 342 343 344
            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)
Mindiell's avatar
Mindiell committed
345
        else:
346
            self.send_message(channel, messages["not_moderator"])
347 348 349 350 351

    def stats(self, user, channel, msg):
        """
        Returns stats on articles in press review.
        """
Mindiell's avatar
Mindiell committed
352
        Utils.debug("stats command")
353
        cursor = get_cursor()
354 355 356 357 358 359 360
        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
361
            result = result + "note>=%s: " % note
362 363 364 365 366 367 368 369 370 371 372 373
            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
374
                    somethingatall = 1
375 376
            if notnull:
                result = result[:-2] + "\n"
Mindiell's avatar
Mindiell committed
377 378
        if somethingatall==0:
            result = messages["stats_bravo"] % periods[-1]
379 380
        self.send_message(channel, result)

381 382 383
    def admin(self, user, channel, msg):
        """
        Manage moderation.
384
        A sub-command should be behind the ~admin command.
385
        """
Mindiell's avatar
Mindiell committed
386
        Utils.debug("admin command")
387
        # Searching for a command after admin keyword
Mindiell's avatar
Mindiell committed
388
        command = re.search("~admin (list|add|del|timer)", msg)
389 390 391 392 393 394 395 396
        if command:
            command = command.group(1)
            if command=="list":
                self.admin_list(user, channel, msg)
            elif command=="add":
                self.admin_add(user, channel, msg)
            elif command=="del":
                self.admin_del(user, channel, msg)
397 398
            elif command=="del":
                self.admin_timer(user, channel, msg)
399 400 401 402 403

    def admin_list(self, user, channel, msg):
        """
        List actual moderators.
        """
Mindiell's avatar
Mindiell committed
404
        Utils.debug("admin_list command")
405 406 407 408 409 410 411 412 413 414 415 416 417
        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
418
        Utils.debug("admin_add command")
419 420 421 422
        if is_moderator(user):
            try:
                names = []
                connection = sqlite3.connect(config.sqlite_db)
423
                result = re.search("~admin add (([^,]+, ?)+)?(.*)", msg)
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
                if result.group(1):
                    names = [name for name in result.group(1).split(", ") if name!=""]
                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"))
                names = set([name for name in names if name not in moderators])
                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"])
            except:
                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
449
        Utils.debug("admin_del command")
450 451 452
        if is_moderator(user):
            try:
                names = []
453
                result = re.search("~admin del (([^,]+, ?)+)?(.*)", msg)
454 455 456 457
                if result.group(1):
                    names = [name for name in result.group(1).split(", ") if name!=""]
                names.append(result.group(3))
                names = set(names)
Mindiell's avatar
Mindiell committed
458
                Utils.debug(names)
459 460 461 462 463 464 465 466 467 468
                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))
            except:
                pass
        else:
            self.send_message(channel, messages["not_moderator"])

469 470 471 472 473 474 475 476 477 478 479 480 481 482
    def admin_timer(self, user, channel, msg):
        """
        Relaunch a timer.
        """
        Utils.debug("admin_timer command")
        if is_moderator(user):
            try:
                # Recalling the timer
                reactor.callLater(config.timer, self.timer)
            except:
                pass
        else:
            self.send_message(channel, messages["not_moderator"])

483 484 485 486 487
    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
488
        Utils.debug("count_articles method")
489 490 491 492 493 494 495
        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])
496
        Utils.debug("Found %s articles." % number)
497
        if self.number!=number:
Mindiell's avatar
Mindiell committed
498
            self.irc.client.topic("#lqdn-rp", messages["topic"] % number)
499 500 501 502 503 504 505
            pass
        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
506
        Utils.debug("rp_to_twitter method")
507 508 509 510 511
        now = time.localtime()
        today = time.strptime("%s-%s-%s %s" % (
                now.tm_year,
                now.tm_mon,
                now.tm_mday,
Mindiell's avatar
Mindiell committed
512
                time.tzname[0]
513 514 515
            ),
            "%Y-%m-%d %Z"
        )
Mindiell's avatar
Mindiell committed
516 517 518
        language = "fr"
        if "/en/" in rss:
            language = "en"
519 520
        entries = feedparser.parse(rss)['entries']
        entries.reverse()
521
        Utils.debug(self.last_entry_published)
522 523 524 525 526
        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:
Mindiell's avatar
Mindiell committed
527
                    self.tweet(messages["tweet_rp_%s" % language] % (
528 529 530
                        entry.title.encode("utf-8"),
                        entry.link.encode("utf-8")
                    ))
Mindiell's avatar
Mindiell committed
531
                    Utils.debug(entry.published_parsed)
Mindiell's avatar
Mindiell committed
532
                    Utils.debug(entry.title)
533 534 535 536 537 538 539 540 541 542 543 544 545 546
                    # 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
547 548 549
                else:
                    Utils.debug(entry.title)
                    Utils.debug(entry.published_parsed)
550 551 552 553 554

    def tweet(self, message):
        """
        Tweet message on specified account
        """
Mindiell's avatar
Mindiell committed
555
        Utils.debug("tweet method")
556 557 558 559 560 561 562 563
        auth = OAuth(
            config.TOKEN,
            config.TOKENSEC,
            config.CONSKEY,
            config.CONSSEC
        )
        twitter = Twitter(auth=auth)
        try:
Mindiell's avatar
Mindiell committed
564
            Utils.debug("Tweeting: %s" % message)
Mindiell's avatar
Mindiell committed
565
            twitter.statuses.update(status=message)
566 567 568
        except:
            pass

569 570 571 572

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