wantzel.py 17.7 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:
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
"""

Mindiell's avatar
Mindiell committed
16 17
import feedparser
import importlib
18 19 20
from irc import IrcClientFactory
import MySQLdb
import re
Mindiell's avatar
Mindiell committed
21 22
import sqlite3
import time
23
from twisted.internet import reactor
Mindiell's avatar
Mindiell committed
24
from twitter import Twitter, OAuth
25 26 27 28 29
import urllib

import config
from messages import messages

Mindiell's avatar
Mindiell committed
30 31
def get_cursor():
    """
Mindiell's avatar
Mindiell committed
32
    This function connects to a MySQL database and returns a usable cursor.
Mindiell's avatar
Mindiell committed
33
    """
Mindiell's avatar
Mindiell committed
34
    connection = MySQLdb.connect(
Mindiell's avatar
Mindiell committed
35 36 37 38 39
        host=config.dbserver,
        user=config.dbuser,
        passwd=config.dbpassword,
        db=config.dbname
    )
Mindiell's avatar
Mindiell committed
40 41
    if connection:
        return connection.cursor()
Mindiell's avatar
Mindiell committed
42 43
    return None

44
def get_url(message):
Mindiell's avatar
Mindiell committed
45
    """
46
    Retrieve the url in the message.
Mindiell's avatar
Mindiell committed
47
    """
48 49
    # Let's get the url
    result = re.search("(https?[^ ]+)", message)
Mindiell's avatar
Mindiell committed
50 51
    if not result:
        return "http"
52
    url = result.group(1)
Mindiell's avatar
Mindiell committed
53 54 55 56 57 58 59 60
    # 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

61 62 63
def get_title(message):
    title = ""
    website = ""
64 65 66 67
    exceptions = [
        "twitter.com",
        "github.com",
    ]
68
    try:
69 70 71 72
        url = get_url(message)
        for exception in exceptions:
            if exception in url:
                return ("", "")
73 74 75 76 77 78 79 80
        website = re.search("//([^/]*)", url).group(1)
        f = urllib.URLopener().open(url)
        content = f.read()
        title = re.search("<title>([^<]+)</title>", content).group(1)
    except:
        pass
    # Unescaping HTML entities
    if title:
Mindiell's avatar
Mindiell committed
81 82 83 84 85
        title = re.sub("&gt;|&#062;", ">", title)
        title = re.sub("&lt;|&#060;", "<", title)
        title = re.sub("&quot;|&#034;", '"', title)
        title = re.sub("&apos;|&#039;", "'", title)
        title = re.sub("&amp;|&#038;", "&", title)
Mindiell's avatar
Mindiell committed
86
        title = re.sub("&ndash;|&#8211;", "–", title)
87 88
    # Multiple lines titles are compressed
    title = re.sub("\n|\r", "", title)
89 90
    return (title, website)

Mindiell's avatar
Mindiell committed
91 92 93 94 95 96 97 98 99 100 101 102
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


103 104 105 106 107 108 109 110
class Wantzel(object):
    """
    Wantzel bot.
    """
    def __init__(self):
        """
        Initialization of bot over IRC.
        """
Mindiell's avatar
Mindiell committed
111 112 113 114 115 116 117 118 119 120
        self.number = 0
        # 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"
            )
121 122 123
        self.irc = IrcClientFactory(config)
        self.irc.set_privmsg = self.set_privmsg
        reactor.connectTCP(config.server, config.port, self.irc)
Mindiell's avatar
Mindiell committed
124 125 126 127 128 129 130 131 132 133 134 135 136
        # Prepare timer
        reactor.callLater(config.timer, self.timer)

    def timer(self):
        """
        This method launches function regularly (see config.timer).
        """
        print("Timer called")
        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)
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

    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):
        """
Mindiell's avatar
Mindiell committed
154 155
        Wantzel can understand a lot of commands. Commands followed by a (*)
        are accessible only to moderators:
156 157 158 159 160
        - 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
161
            Add an article in the database
162
        - stats
Mindiell's avatar
Mindiell committed
163
            Show some statistics about the RP
Mindiell's avatar
Mindiell committed
164
        - kill (*)
Mindiell's avatar
Mindiell committed
165
            Kill an article by giving it a score of -100
Mindiell's avatar
Mindiell committed
166 167 168 169 170 171
        - moderate list (*)
            List rights in private
        - moderate add (*)
            Add a new moderator to list
        - moderate remove (*)
            Remove a moderator from list
172 173
        """
        # Cleaning user name
Mindiell's avatar
Mindiell committed
174 175
        user = re.search("([^!]*)!", user).group(1)
        print("Message received: %s %s %s" % (user, channel, msg))
176 177
        # Whatever is done, get the title of an existing url in a message
        title = ""
178
        if "http" in msg:
179
            title, website = get_title(msg)
Mindiell's avatar
Mindiell committed
180 181 182 183 184 185 186
        # 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):
187
                self.help(user, channel, msg)
Mindiell's avatar
Mindiell committed
188
            # Find known command
Mindiell's avatar
Mindiell committed
189
            command = re.search("!(rp[acp]*|kill|help|stats|admin)", msg)
Mindiell's avatar
Mindiell committed
190 191 192 193
            if command:
                command = command.group(1)
                print("Command: %s" % command)
                if command.startswith("rp"):
194
                    self.rp(command, user, channel, msg, title)
Mindiell's avatar
Mindiell committed
195 196 197 198 199 200
                elif command=="help":
                    self.help(user, channel, msg)
                elif command=="kill":
                    self.kill(user, channel, msg)
                elif command=="stats":
                    self.stats(user, channel, msg)
Mindiell's avatar
Mindiell committed
201 202
                elif command=="admin":
                    self.admin(user, channel, msg)
203 204
        if title and website:
            self.send_message(channel, messages["title"] % (title, website))
205 206 207 208 209

    def on_joined(self, channel):
        """
        Say hello to everyone.
        """
Mindiell's avatar
Mindiell committed
210 211 212 213 214 215
        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"])
216 217 218 219 220 221 222 223

    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
224
        # Searching for a command after help keyword
Mindiell's avatar
Mindiell committed
225
        command = re.search("!help (stats|rp|help|kill|admin)", msg)
Mindiell's avatar
Mindiell committed
226 227
        if command:
            command = command.group(1)
228
            self.send_message(channel, messages["help_"+command])            
Mindiell's avatar
Mindiell committed
229 230
        else:
            self.send_message(channel, messages["help"])
231

232
    def rp(self, command, user, channel, msg, title=""):
233 234 235 236 237 238
        """
        Adding the article in rp database.
        """
        print("rp command %s" % command)
        cite = 0
        note = 0
239
        url = get_url(msg)
240
        print("url: %s" % url)
Mindiell's avatar
Mindiell committed
241 242 243 244 245
        if url=="":
            return
        elif url=="http":
            self.send_message(channel, messages["rp_http"] % user)
            return
246

Mindiell's avatar
Mindiell committed
247 248
        # Looking for such an article in database
        cursor = get_cursor()
249 250 251 252 253 254 255 256 257 258 259 260
        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
Mindiell's avatar
Mindiell committed
261
            print("Adding an article by %s: %s" % (user, url))
262
            result = cursor.execute(
263 264 265 266 267
                """INSERT INTO presse SET 
                url=%s, provenance=%s, cite=%s, note=%s, datec=NOW(), title=%s,
                lang='', published=0, nid=0, screenshot=0, fetched=0, seemscite=0
                """,
                (url, user, cite, note, title)
268
            )
Mindiell's avatar
Mindiell committed
269
            self.send_message(channel, messages["rp_new_article"] % user)
270 271
        else:
            if rows[0][2]!=user:
Mindiell's avatar
Mindiell committed
272
                print("Adding a point by %s on %s" % (user, rows[0][0]))
273 274 275 276 277
                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
278
                self.send_message(channel, messages["rp_known_article"] % user)
279
            else:
Mindiell's avatar
Mindiell committed
280
                self.send_message(channel, messages["rp_taken_article"] % user)
Mindiell's avatar
Mindiell committed
281 282
                # Update number of articles to do
                self.count_articles()
283 284 285

    def kill(self, user, channel, msg):
        """
Mindiell's avatar
Mindiell committed
286
        Kill an article by setting its score to -100.
287 288
        """
        print("kill command")
Mindiell's avatar
Mindiell committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
        if is_moderator(user):
            url = get_url(msg)
            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)
Mindiell's avatar
Mindiell committed
306
        else:
Mindiell's avatar
Mindiell committed
307
            self.send_message(channel, messages["not_moderator"])
308 309 310 311 312 313

    def stats(self, user, channel, msg):
        """
        Returns stats on articles in press review.
        """
        print("stats command")
Mindiell's avatar
Mindiell committed
314
        cursor = get_cursor()
315 316 317 318 319 320 321
        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
322
            result = result + "note>=%s: " % note
323 324 325 326 327 328 329 330 331 332 333 334
            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
335
                    somethingatall = 1
336 337
            if notnull:
                result = result[:-2] + "\n"
Mindiell's avatar
Mindiell committed
338 339
        if somethingatall==0:
            result = messages["stats_bravo"] % periods[-1]
340 341
        self.send_message(channel, result)

Mindiell's avatar
Mindiell committed
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
    def admin(self, user, channel, msg):
        """
        Manage moderation.
        A sub-command should be behind the !admin command.
        """
        print("admin command")
        # Searching for a command after admin keyword
        command = re.search("!admin (list|add|del)", msg)
        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)

    def admin_list(self, user, channel, msg):
        """
        List actual moderators.
        """
        print("admin_list command")
        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.
        """
        print("admin_add command")
        if is_moderator(user):
            try:
                names = []
                connection = sqlite3.connect(config.sqlite_db)
                result = re.search("!admin add (([^,]+, ?)+)?(.*)", msg)
                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.
        """
        print("admin_del command")
        if is_moderator(user):
            try:
                names = []
                result = re.search("!admin del (([^,]+, ?)+)?(.*)", msg)
                if result.group(1):
                    names = [name for name in result.group(1).split(", ") if name!=""]
                names.append(result.group(3))
                names = set(names)
                print(names)
                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"])

    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
433
        print("count_articles method")
Mindiell's avatar
Mindiell committed
434 435 436 437 438 439 440 441
        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])
        if self.number!=number:
Mindiell's avatar
Mindiell committed
442
            self.irc.client.topic("#lqdn-rp", messages["topic"] % number)
Mindiell's avatar
Mindiell committed
443 444 445 446 447 448 449 450 451 452 453 454 455
            pass
        self.number = number

    def rp_to_twitter(self, rss):
        """
        By parsing the RSS feed of the press-review, we know what to tweet.
        """
        print("rp_to_twitter method")
        now = time.localtime()
        today = time.strptime("%s-%s-%s %s" % (
                now.tm_year,
                now.tm_mon,
                now.tm_mday,
Mindiell's avatar
Mindiell committed
456
                time.tzname[0]
Mindiell's avatar
Mindiell committed
457 458 459
            ),
            "%Y-%m-%d %Z"
        )
Mindiell's avatar
Mindiell committed
460 461 462
        language = "fr"
        if "/en/" in rss:
            language = "en"
Mindiell's avatar
Mindiell committed
463 464 465 466 467 468 469
        entries = feedparser.parse(rss)['entries']
        entries.reverse()
        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
470
                    self.tweet(messages["tweet_rp_%s" % language] % (
Mindiell's avatar
Mindiell committed
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
                        entry.title.encode("utf-8"),
                        entry.link.encode("utf-8")
                    ))
                    print(entry.published_parsed)
                    print(entry.title)
                    # 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

    def tweet(self, message):
        """
        Tweet message on specified account
        """
        print("tweet method")
        auth = OAuth(
            config.TOKEN,
            config.TOKENSEC,
            config.CONSKEY,
            config.CONSSEC
        )
        twitter = Twitter(auth=auth)
        try:
Mindiell's avatar
Mindiell committed
504 505
            print("Tweeting: %s" % message)
            twitter.statuses.update(status=message)
Mindiell's avatar
Mindiell committed
506 507 508
        except:
            pass

509 510 511 512

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