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

9
import random
10
import re
11 12
import sqlite3
import time
13 14 15 16

import feedparser
from irc import IrcClientFactory
import MySQLdb
17
from twisted.internet import reactor
18
from twitter import Twitter, OAuth
19 20 21 22

import config
from messages import messages

Mindiell's avatar
Mindiell committed
23 24 25 26 27 28 29
LOG_FILE = "wantzel.log"
DEBUG = 3
WARNING = 2
INFO = 1
ERROR = 0
LOG_LEVEL = DEBUG

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 58 59 60 61 62
animals = [
    {
        "left": """><((('>""",
        "right": """<')))><""",
        "sound": "blub",
    },
    {
        "left": """=^..^=""",
        "right": """=^..^=""",
        "sound": "meow",
    },
    {
        "left": """ˁ˚ᴥ˚ˀ""",
        "right": """ˁ˚ᴥ˚ˀ""",
        "sound": "wouf",
    },
    {
        "left": """\_o<""",
        "right": """>o_/""",
        "sound": "coin",
    },
    {
        "left": """^(*(oo)*)^""",
        "right": """^(*(oo)*)^""",
        "sound": "grouïk",
    },
    {
        "left": """~~(__^·>""",
        "right": """<·^__)~~""",
        "sound": "yiik",
    },
]

Mindiell's avatar
Mindiell committed
63
class Utils(object):
64 65 66
    """
    Simple utility class to log easily.
    """
Mindiell's avatar
Mindiell committed
67 68
    @classmethod
    def log(cls, message):
69 70 71 72 73
        """
        Logging message with timestamp.
        """
        actual_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        with open(LOG_FILE, 'a') as file_handle:
74
            try:
75
                file_handle.write("%s: %s\n" % (actual_time, message.encode("utf-8")))
76 77
            except UnicodeDecodeError:
                file_handle.write("%s: %s\n" % (actual_time, message))
Mindiell's avatar
Mindiell committed
78 79 80

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

    @classmethod
    def warning(cls, message):
89 90 91 92
        """
        Manage WARNING level of logging.
        """
        if LOG_LEVEL >= WARNING:
Mindiell's avatar
Mindiell committed
93 94 95 96
            cls.log("%s: %s" % ("WARNING", message))

    @classmethod
    def info(cls, message):
97 98 99 100
        """
        Manage INFO level of logging.
        """
        if LOG_LEVEL >= INFO:
Mindiell's avatar
Mindiell committed
101 102 103 104
            cls.log("%s: %s" % ("INFO", message))

    @classmethod
    def error(cls, message):
105 106 107 108
        """
        Manage ERROR level of logging.
        """
        if LOG_LEVEL >= ERROR:
Mindiell's avatar
Mindiell committed
109 110 111 112
            cls.log("%s: %s" % ("ERROR", message))



Mindiell's avatar
Mindiell committed
113 114
def get_cursor():
    """
115
    This function connects to a MySQL database and returns a usable cursor.
Mindiell's avatar
Mindiell committed
116
    """
117
    connection = MySQLdb.connect(
Mindiell's avatar
Mindiell committed
118 119 120 121 122
        host=config.dbserver,
        user=config.dbuser,
        passwd=config.dbpassword,
        db=config.dbname
    )
123 124
    if connection:
        return connection.cursor()
Mindiell's avatar
Mindiell committed
125 126
    return None

127

128
def get_url(message):
Mindiell's avatar
Mindiell committed
129
    """
130
    Retrieve the url in the message.
Mindiell's avatar
Mindiell committed
131
    """
132 133
    # Let's get the url
    result = re.search("(https?[^ ]+)", message)
Mindiell's avatar
Mindiell committed
134
    if not result:
135
        return
136
    url = result.group(1)
Mindiell's avatar
Mindiell committed
137 138 139 140 141 142 143 144
    # 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

145

146 147 148 149 150 151 152
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, ))
153
    if int(cursor.fetchone()[0]) == 1:
154 155 156 157
        return True
    return False


158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
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


177 178 179 180 181 182 183 184
class Wantzel(object):
    """
    Wantzel bot.
    """
    def __init__(self):
        """
        Initialization of bot over IRC.
        """
185
        self.number = None
186
        # default last_entry_published for tweets
187 188 189 190 191 192 193 194
        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"
            )
195
        Utils.debug("Dernier tweet: %s" % self.last_entry_published)
196 197 198 199 200 201 202 203 204 205 206
        # default last_entry_published for wiki
        self.last_entry_updated = 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_updated FROM wikis"):
            self.last_entry_updated = time.strptime(
                row[0].encode("utf-8"),
                "%Y-%m-%d %H:%M:%S %Z"
            )
        Utils.debug("Dernière mise à jour du wiki: %s" % self.last_entry_updated)

207 208 209
        self.irc = IrcClientFactory(config)
        self.irc.set_privmsg = self.set_privmsg
        reactor.connectTCP(config.server, config.port, self.irc)
210 211 212 213 214 215 216
        # Prepare timer
        reactor.callLater(config.timer, self.timer)

    def timer(self):
        """
        This method launches function regularly (see config.timer).
        """
Mindiell's avatar
Mindiell committed
217
        Utils.debug("Timer called")
218 219 220
        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()
221
        self.op_verification()
222
        self.wiki_updates()
223 224
        # Recalling the timer
        reactor.callLater(config.timer, self.timer)
225 226 227 228 229 230

    def set_privmsg(self):
        """
        This method set the methods to call for each callback received from IRC.
        """
        self.irc.client.privmsg = self.on_privmsg
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
        self.irc.client.irc_unknown = self.test_unknown
        self.irc.client.modeChanged = self.mode_changed

    def test_unknown(self, prefix, command, params):
        Utils.debug("UNKNOWN %s %s %s" % (prefix, command, params))
        if command=="RPL_NAMREPLY":
            self.names(params)

    def op_verification(self):
        """
        Verify if wantzel is chan operator, if not it complains on the chan <3.
        """
        Utils.debug("op_verification method")
        # On liste les utilisateurs du canal de la rp
        self.irc.client.sendLine("NAMES #lqdn-rp")

    def mode_changed(self, user, channel, flag_set, modes, args):
        Utils.debug("Mode changed : %s %s %s %s %s" % (user, channel, flag_set, modes, args))
Mindiell's avatar
Mindiell committed
249
        if "o" in modes and self.irc.client.nickname in args:
250 251 252 253 254 255 256 257 258 259 260 261 262
            # Cleaning user name
            user = re.search("([^!]*)!", user).group(1)
            if flag_set:
                self.send_message(channel, messages["oped"] % user)
            else:
                self.send_message(channel, messages["deoped"] % user)

    def names(self, params):
        Utils.debug("Names : %s" % params)
        if params[2]=="#lqdn-rp":
            ops = [user[1:] for user in params[3].split() if user[0]=="@"]
            if "@"+self.irc.client.nickname not in params[3]:
                self.send_message(params[2], messages["please_op"] % ", ".join(ops))
263

264
    def send_message(self, channel, multiline_message):
265 266 267
        """
        Sends a message on specified channel, cutting each line in a new message
        """
268
        for message in multiline_message.splitlines():
269 270 271 272
            self.irc.client.msg(channel, message)

    def on_privmsg(self, user, channel, msg):
        """
273 274
        Wantzel can understand a lot of commands. Commands followed by a (*)
        are accessible only to moderators:
275 276 277
        - help
            Returns a message about how to use the bot.
            If a command is passed after help, the message explains how to use
278
            the command.
279
        - rp(acp) <url>
Mindiell's avatar
Mindiell committed
280
            Add an article in the database
281 282
        - status <url>
            Retrieve some informations about an article in the database
283
        - stats
Mindiell's avatar
Mindiell committed
284
            Show some statistics about the RP
285
        - kill (*)
Mindiell's avatar
Mindiell committed
286
            Kill an article by giving it a score of -100
287
        - admin list (*)
288
            List rights in private
289
        - admin add (*)
290 291 292
            Add one or more new moderator to list
        - admin del (*)
            Delete one or more moderator from list
293
        - admin timer
294
            Relaunch a timer
295 296
        """
        # Cleaning user name
Mindiell's avatar
Mindiell committed
297
        user = re.search("([^!]*)!", user).group(1)
Mindiell's avatar
Mindiell committed
298
        Utils.debug("Message received: %s %s %s" % (user, channel, msg))
Mindiell's avatar
Mindiell committed
299
        # Never answer to botself
300
        if user != config.nickname:
Mindiell's avatar
Mindiell committed
301 302 303 304 305
            # 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):
306
                self.help(user, channel, msg)
Mindiell's avatar
Mindiell committed
307
            # Find known command
308
            command = re.search("[!~](rp[acp]*|status|kill|help|stats|admin)", msg)
Mindiell's avatar
Mindiell committed
309
            Utils.debug("Command: %s" % command)
Mindiell's avatar
Mindiell committed
310
            if command:
Mindiell's avatar
Mindiell committed
311
                Utils.debug("group(0): %s" % command.group(0))
Mindiell's avatar
Mindiell committed
312
                command = command.group(1)
Mindiell's avatar
Mindiell committed
313
                Utils.debug("Command: %s" % command)
Mindiell's avatar
Mindiell committed
314
                if command.startswith("rp"):
Mindiell's avatar
Mindiell committed
315
                    Utils.debug("Calling self.rp")
316
                    self.rp(command, user, channel, msg)
317 318 319
                if command.startswith("status"):
                    Utils.debug("Calling self.status")
                    self.status(command, user, channel, msg)
320
                elif command == "help":
Mindiell's avatar
Mindiell committed
321
                    Utils.debug("Calling self.help")
322
                    self.help(user, channel, msg)
323
                elif command == "kill":
Mindiell's avatar
Mindiell committed
324
                    Utils.debug("Calling self.kill")
Mindiell's avatar
Mindiell committed
325
                    self.kill(user, channel, msg)
326
                elif command == "stats":
Mindiell's avatar
Mindiell committed
327
                    Utils.debug("Calling self.stats")
328 329
                    self.stats(channel)
                elif command == "admin":
Mindiell's avatar
Mindiell committed
330
                    Utils.debug("Calling self.admin")
331
                    self.admin(user, channel, msg)
332
            if user/lower()=="deltree" and msg=="\_o< ~ Coin ~ >o_/":
333 334 335 336 337 338 339
                animal = random.choice(animals)
                self.send_message(channel, messages["coin_deltree"] % (
                    animal["left"],
                    animal["sound"],
                    animal["sound"],
                    animal["right"],
                ))
340 341 342
        # No more giving the title of an url
        #if title and website:
        #    self.send_message(channel, messages["title"] % (title, website))
343

344
    def help(self, user, channel, msg):
345 346
        """
        Show global help.
347
        If a known command is behind the ~!help command, an adequate message is
348 349
        returned.
        """
Mindiell's avatar
Mindiell committed
350
        Utils.debug("help command")
Mindiell's avatar
Mindiell committed
351
        # Searching for a command after help keyword
352
        command = re.search("[!~]help (help|rp|status|stats|kill|admin)", msg)
Mindiell's avatar
Mindiell committed
353 354
        if command:
            command = command.group(1)
355
            self.send_message(user, messages["help_"+command])
Mindiell's avatar
Mindiell committed
356
        else:
357
            self.send_message(user, messages["help"])
358

359
    def rp(self, command, user, channel, msg):
360 361 362
        """
        Adding the article in rp database.
        """
Mindiell's avatar
Mindiell committed
363 364 365 366
        Utils.debug("rp command : %s" % command)
        Utils.debug("rp user : %s" % user)
        Utils.debug("rp channel : %s" % channel)
        Utils.debug("rp msg : %s" % msg)
367
        cite = 0
368
        note = 1
369
        url = get_url(msg)
Mindiell's avatar
Mindiell committed
370
        Utils.debug("url: %s" % url)
371
        if not url:
Mindiell's avatar
Mindiell committed
372
            return
373

374 375 376 377 378 379 380 381 382 383 384
        # Managing flags
        # LQdN is quoted
        if "c" in command:
            cite += 1
        # the article speak about LQdN
        if command.count("p") > 1:
            cite += 2
        # Archive this article
        if "a" in command:
            cite += 4

Mindiell's avatar
Mindiell committed
385 386
        # Looking for such an article in database
        cursor = get_cursor()
387 388 389 390 391 392 393 394 395 396 397 398
        # We need to be able to retrieve an url with "http" or "https"
        if url.startswith("https"):
            url2 = "http" + url[5:]
        else:
            url2 = "https" + url[4:]
        cursor.execute("""
            SELECT id, note, provenance
            FROM presse
            WHERE url = %s
            OR url = %s""",
            (url, url2)
        )
399 400
        rows = cursor.fetchall()
        if not rows:
Mindiell's avatar
Mindiell committed
401
            Utils.debug("Adding an article by %s: %s" % (user, url))
402 403
            cursor.execute("""
                INSERT INTO presse SET
404
                url=%s, provenance=%s, cite=%s, note=%s, datec=NOW(), title='',
405 406
                lang='', published=0, nid=0, screenshot=0, fetched=0, seemscite=0
                """,
407
                (url, user, cite, note)
408
            )
Mindiell's avatar
Mindiell committed
409
            self.send_message(channel, messages["rp_new_article"] % user)
410
        else:
411
            if rows[0][2] != user:
Mindiell's avatar
Mindiell committed
412
                Utils.debug("Adding a point by %s on %s" % (user, rows[0][0]))
413
                cursor.execute(
414 415 416
                    "UPDATE presse SET note=note+1 WHERE id=%s",
                    (rows[0][0], )
                )
417
            if (rows[0][1]+1) < 3:
Mindiell's avatar
Mindiell committed
418
                self.send_message(channel, messages["rp_known_article"] % user)
419
            else:
Mindiell's avatar
Mindiell committed
420
                self.send_message(channel, messages["rp_taken_article"] % user)
421 422
                # Update number of articles to do
                self.count_articles()
423

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    def status(self, command, user, channel, msg):
        """
        Retrieving status of the article in rp database.
        """
        Utils.debug("rp command : %s" % command)
        Utils.debug("rp user : %s" % user)
        Utils.debug("rp channel : %s" % channel)
        Utils.debug("rp msg : %s" % msg)
        url = get_url(msg)
        Utils.debug("url: %s" % url)
        if not url:
            return

        # Looking for such an article in database
        cursor = get_cursor()
439 440 441 442 443
        # We need to be able to retrieve an url with "http" or "https"
        if url.startswith("https"):
            url2 = "http" + url[5:]
        else:
            url2 = "https" + url[4:]
444
        cursor.execute("""
445
            SELECT cite, nid, note
446
            FROM presse
447 448 449 450
            WHERE url = %s
            OR url = %s""",
            (url, url2)
        )
451 452 453 454
        rows = cursor.fetchall()
        if not rows:
            self.send_message(channel, messages["status_unknown_article"] % user)
        else:
455 456 457 458 459 460 461 462 463
            message = "%s: note %s / " % (user, rows[0][2])
            if rows[0][0] & 1:
                message += "cite LQdN / "
            if rows[0][0] & 2:
                message += "parle de LQdN / "
            if rows[0][0] & 4:
                message += "archivé / "
            if rows[0][1] > 0:
                message += "publié (https://laquadrature.net/node/%s) / " % rows[0][1]
464
            else:
465 466
                message += "non publié / "
            self.send_message(channel, message[:-3])
467

468 469
    def kill(self, user, channel, msg):
        """
Mindiell's avatar
Mindiell committed
470
        Kill an article by setting its score to -100.
471
        """
Mindiell's avatar
Mindiell committed
472
        Utils.debug("kill command")
473 474
        if is_moderator(user):
            url = get_url(msg)
Mindiell's avatar
Mindiell committed
475
            Utils.debug("url: %s" % url)
476
            if url == "":
477
                return
478
            elif url == "http":
479 480 481 482
                self.send_message(channel, messages["rp_http"] % user)
                return
            # Looking for such an article in database
            cursor = get_cursor()
483 484 485 486 487 488 489 490 491 492 493 494
            # We need to be able to retrieve an url with "http" or "https"
            if url.startswith("https"):
                url2 = "http" + url[5:]
            else:
                url2 = "https" + url[4:]
            cursor.execute("""
                SELECT id, note
                FROM presse
                WHERE url = %s
                OR url = %s""",
                (url, url2)
            )
495 496 497 498 499 500
            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
501
        else:
502
            self.send_message(channel, messages["not_moderator"])
503

504
    def stats(self, channel):
505 506 507
        """
        Returns stats on articles in press review.
        """
Mindiell's avatar
Mindiell committed
508
        Utils.debug("stats command")
509
        cursor = get_cursor()
510
        periods = [1, 3, 7, 15]
511
        notes = [0, 3, 4]
512 513 514 515
        notnull = 0
        somethingatall = 0
        for note in notes:
            notnull = 0
516
            period_result = ""
517
            for period in periods:
518 519 520
                cursor.execute("""
                    SELECT COUNT(id) AS cid
                    FROM presse
521 522 523 524 525 526
                    WHERE nid=0
                    AND datec>(NOW()-INTERVAL %s DAY)
                    AND note>=%s""",
                    (period, note)
                )
                rows = cursor.fetchall()
527
                if rows[0][0] > 0:
528
                    period_result = period_result + "%sj:%s, " % (period, rows[0][0])
529
                    notnull = 1
Mindiell's avatar
Mindiell committed
530
                    somethingatall = 1
531
            if notnull:
532
                self.send_message(channel, "note>=%s: " % note + period_result[:-2])
533
        if somethingatall == 0:
534
            self.send_message(channel, messages["stats_bravo"] % periods[-1])
535

536 537 538
    def admin(self, user, channel, msg):
        """
        Manage moderation.
539
        A sub-command should be behind the !~admin command.
540
        """
Mindiell's avatar
Mindiell committed
541
        Utils.debug("admin command")
542
        # Searching for a command after admin keyword
543
        command = re.search("[~!]admin (list|add|del|timer)", msg)
544 545
        if command:
            command = command.group(1)
546 547 548
            if command == "list":
                self.admin_list(user, channel)
            elif command == "add":
549
                self.admin_add(user, channel, msg)
550
            elif command == "del":
551
                self.admin_del(user, channel, msg)
552 553
            elif command == "timer":
                self.admin_timer(user, channel)
554

555
    def admin_list(self, user, channel):
556 557 558
        """
        List actual moderators.
        """
Mindiell's avatar
Mindiell committed
559
        Utils.debug("admin_list command")
560 561 562 563 564
        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"))
565
            self.send_message(channel, messages["admin_list"] % ", ".join(sorted(names)))
566 567 568 569 570 571 572
        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
573
        Utils.debug("admin_add command")
574 575 576 577
        if is_moderator(user):
            try:
                names = []
                connection = sqlite3.connect(config.sqlite_db)
578
                result = re.search("[!~]admin add (([^,]+, ?)+)?(.*)", msg)
579
                if result.group(1):
580
                    names = [name.strip() for name in result.group(1).split(",") if name.strip() != ""]
581 582 583 584 585
                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"))
586
                names = list(set([name for name in names if name not in moderators]))
587 588 589 590 591 592 593 594
                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"])
595
            except Exception:
596 597 598 599 600 601 602 603
                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
604
        Utils.debug("admin_del command")
605 606 607
        if is_moderator(user):
            try:
                names = []
608
                result = re.search("[!~]admin del (([^,]+, ?)+)?(.*)", msg)
609
                if result.group(1):
610
                    names = [name.strip() for name in result.group(1).split(",") if name.strip() != ""]
611
                names.append(result.group(3))
612
                names = list(set(names))
Mindiell's avatar
Mindiell committed
613
                Utils.debug(names)
614 615 616 617 618
                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))
619
            except Exception:
620 621 622 623
                pass
        else:
            self.send_message(channel, messages["not_moderator"])

624
    def admin_timer(self, user, channel):
625 626 627 628 629 630 631 632
        """
        Relaunch a timer.
        """
        Utils.debug("admin_timer command")
        if is_moderator(user):
            try:
                # Recalling the timer
                reactor.callLater(config.timer, self.timer)
633
            except Exception:
634 635 636 637
                pass
        else:
            self.send_message(channel, messages["not_moderator"])

638 639 640 641 642
    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
643
        Utils.debug("count_articles method")
644 645 646 647 648 649 650
        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])
651
        Utils.debug("Found %s articles." % number)
652
        if self.number != number:
Mindiell's avatar
Mindiell committed
653
            self.irc.client.topic("#lqdn-rp", messages["topic"] % number)
654 655 656 657 658 659
        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
660
        Utils.debug("rp_to_twitter method")
661 662
        now = time.localtime()
        today = time.strptime("%s-%s-%s %s" % (
663 664 665 666 667
            now.tm_year,
            now.tm_mon,
            now.tm_mday,
            time.tzname[0]
            ), "%Y-%m-%d %Z")
Mindiell's avatar
Mindiell committed
668 669 670
        language = "fr"
        if "/en/" in rss:
            language = "en"
671 672
        entries = feedparser.parse(rss)['entries']
        entries.reverse()
673
        Utils.debug(self.last_entry_published)
674 675 676 677 678
        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:
okhin's avatar
okhin committed
679 680 681 682
                    # Let's see if we can truncate the lenght of the tweet
                    # We have 5 chars for the language, so max-length is 135
                    title = entry.title.encode("utf-8")
                    link = entry.link.encode("utf-8")
683
                    if len(title) + min(len(link),23) > 135:
okhin's avatar
okhin committed
684
                        # What is the number of chars we need to remove
685 686
                        excess = len(title) + min(len(link),23) - 135
                        title = ''.join([title[:-(excess + 4)], ' ...'])
687
                    tweet(messages["tweet_rp_%s" % language] % (
okhin's avatar
okhin committed
688 689
                        title,
                        link
690
                    ))
Mindiell's avatar
Mindiell committed
691
                    Utils.debug(entry.published_parsed)
Mindiell's avatar
Mindiell committed
692
                    Utils.debug(entry.title)
693 694 695 696 697 698 699 700 701 702 703 704 705 706
                    # 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
707 708 709
                else:
                    Utils.debug(entry.title)
                    Utils.debug(entry.published_parsed)
710

711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    def wiki_updates(self):
        url = "https://wiki.laquadrature.net/api.php?days=1&limit=50&translations=filter&action=feedrecentchanges&feedformat=atom"
        now = time.localtime()
        today = time.strptime("%s-%s-%s %s" % (
            now.tm_year,
            now.tm_mon,
            now.tm_mday,
            time.tzname[0]
            ), "%Y-%m-%d %Z")
        entries = feedparser.parse(url)['entries']
        for entry in entries:
            # if date of update is greater than today midnight
            if today < entry.updated_parsed:
                if self.last_entry_updated < entry.updated_parsed:
                    # Ecriture de la mise à jour sur le canal de travail
726
                    self.send_message("#lqdn-travail", messages["wiki_update"] % (
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
                        entry.author.encode("utf-8"),
                        entry.title.encode("utf-8"),
                        entry.link.encode("utf-8"),
                    ))
                    # Save last_entry_published
                    self.last_entry_updated = entry.updated_parsed
                    last_entry_updated = time.strftime(
                        "%Y-%m-%d %H:%M:%S %Z",
                        self.last_entry_updated
                    )
                    connection = sqlite3.connect(config.sqlite_db)
                    connection.execute(
                        "UPDATE wikis SET last_entry_updated=?",
                        (last_entry_updated,)
                    )
                    connection.commit()

744 745

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