utils.py 1.65 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
# encoding: utf-8
"""
Utility functions for Wantzel bot.
"""

import MySQLdb
import re
import sqlite3

import config
from logs import Log

def get_cursor():
    """
    This function connects to a MySQL database and returns a usable cursor.
    """
    connection = MySQLdb.connect(
        host=config.dbserver,
        user=config.dbuser,
        passwd=config.dbpassword,
        db=config.dbname
    )
    if connection:
        return connection.cursor()
    return None


def get_url(message):
    """
    Retrieve the url in the message.
    """
    # Let's get the url
    result = re.search("(https?[^ ]+)", message)
    if not result:
        return
    url = result.group(1)
    # 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


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


def tweet(message):
    """
    Tweet message on specified account
    """
    Log.debug("tweet method")
    auth = OAuth(
        config.TOKEN,
        config.TOKENSEC,
        config.CONSKEY,
        config.CONSSEC
    )
    twitter = Twitter(auth=auth)
    try:
        Log.debug("Tweeting: %s" % message)
        twitter.statuses.update(status=message)
    except Exception as e:
        Log.error("Erreur lors du tweet : " + str(e))