Пример #1
0
def topic(chat_id=False, title=False):
    """
    Use API call to have the bot change topic
    :param chat_id:  chat id to locate user into
    :param title: new title to set
    :return:
    """

    logger = logging.getLogger(__name__)
    result = {'ok': False}

    if chat_id and title:
        logger.debug(msg=_L('Setting new title to %s') % title)
        url = "%s%s/setChatTitle?chat_id=%s&title=%s" % (
            stampy.plugin.config.config(key='url'),
            stampy.plugin.config.config(key='token'), chat_id,
            urllib.quote_plus(title.encode('utf-8')))

        try:
            result = json.load(urllib.urlopen(url))
        except:
            result = {'ok': False}
    else:
        result = {'ok': False}

    if result['ok'] is True or result['ok'] == 'True':
        logger.info(msg=_L("Topic %s has been updated on  %s") %
                    (title, chat_id))
    else:
        logger.error(msg=_L("Error when modifying topic: %s") % result)

    return result
Пример #2
0
def kick(chat_id=False, user_id=False, ban=False):
    """
    Use API call to have the bot kick out of chat
    :param chat_id:  chat id to locate user into
    :param user_id:  user id to kick out of chat
    :param ban: ban user from reentering?
    :return:
    """

    logger = logging.getLogger(__name__)
    result = {'ok': False}

    if chat_id and user_id:
        url = "%s%s/kickChatMember?chat_id=%s&user_id=%s" % (
            stampy.plugin.config.config(key='url'),
            stampy.plugin.config.config(key='token'), chat_id, user_id)
        try:
            result = json.load(urllib.urlopen(url))
        except:
            result = {'ok': False}
    else:
        result = {'ok': False}

    if result['ok'] is True or result['ok'] == 'True':
        logger.info(msg=_L("User %s kicked and banned from %s") %
                    (user_id, chat_id))
        if not ban:
            unban(chat_id=chat_id, user_id=user_id)
    else:
        logger.error(msg=_L("Error when kicking user: %s") % result)

    return result
Пример #3
0
def whois(chat_id=False, user_id=False):
    """
    Use API call to retrieve userid
    :param chat_id:  chat id to locate user into
    :param user_id:  user id to kick out of chat
    :return: API information
    """

    logger = logging.getLogger(__name__)
    result = {'ok': False}

    if chat_id and user_id:
        url = "%s%s/getChatMember?chat_id=%s&user_id=%s" % (
            stampy.plugin.config.config(key='url'),
            stampy.plugin.config.config(key='token'), chat_id, user_id)
        try:
            result = json.load(urllib.urlopen(url))
        except:
            result = {'ok': False}
    else:
        result = {'ok': False}

    if result['ok'] is True or result['ok'] == 'True':
        logger.info(msg=_L("User %s information: %s") %
                    (user_id, result['result']))
    else:
        logger.error(msg=_L("Error /whois on user: %s") % result)

    return result
Пример #4
0
def mute(chat_id=False, user_id=False, extra=""):
    """
    Use API call to have the bot op user in
    :param chat_id:  chat id to locate user into
    :param user_id:  user id to op
    :param extra: permissions to set or 'op'|'deop' for full
    :return:
    """

    logger = logging.getLogger(__name__)
    result = {'ok': False}

    permissions = [
        "can_send_messages", "can_send_media_messages",
        "can_send_other_messages", "can_add_web_page_previews"
    ]

    # Enable all restrictions
    if extra == "" or extra == "mute":
        value = False
    elif extra == "unmute":
        value = True
        # Disable all restrictions
        extra = ""

    if chat_id and user_id:
        # Iterate over permissions to set new value
        for item in permissions:
            extra = "%s&%s=%s" % (extra, item, value)

        # For permissions we must assign all of them in a row or it will
        # reset other settings

        url = "%s%s/restrictChatMember?chat_id=%s&user_id=%s&%s" % (
            stampy.plugin.config.config(key='url'),
            stampy.plugin.config.config(key='token'), chat_id, user_id, extra)

        try:
            result = json.load(urllib.urlopen(url))
        except:
            result = {'ok': False}

        if result['ok'] is True or result['ok'] == 'True':
            logger.info(msg=_L("User %s has updated restrictions: %s on %s") %
                        (user_id, item, chat_id))
        else:
            logger.error(
                msg=_L("Error when modifying user restriction: %s: %s") %
                (item, result))

    else:
        result = {'ok': False}

    return result
Пример #5
0
def comiccommands(message):
    """
    Processes comic commands in the message texts
    :param message: Message to process
    :return:
    """

    logger = logging.getLogger(__name__)

    msgdetail = stampy.stampy.getmsgdetail(message)

    texto = msgdetail["text"]
    chat_id = msgdetail["chat_id"]
    message_id = msgdetail["message_id"]
    who_un = msgdetail["who_un"]

    logger.debug(msg=_L("Command: %s by %s") % (texto, who_un))

    if stampy.stampy.is_owner_or_admin(message):
        logger.debug(msg=_L("Command: %s by Owner: %s") % (texto, who_un))
        try:
            command = texto.split(' ')[1]
        except:
            command = False

        for case in stampy.stampy.Switch(command):
            if case('list'):
                text = listcomics()
                stampy.stampy.sendmessage(chat_id=chat_id,
                                          text=text,
                                          reply_to_message_id=message_id,
                                          disable_web_page_preview=True,
                                          parse_mode="Markdown")
                break

            if case('trigger'):
                comics()
                break

            if case('all'):
                comics(name=False, message=message, all=True)
                break

            if case():
                # we might been have called by direct triggers or by comic
                # name, so show only that comic
                trigger = texto.split(' ')[0]
                if "/" in trigger and trigger != "/comic":
                    comics(name=trigger[1:], message=message, all=True)
                else:
                    comics(name=command, message=message, all=True)
                break
    return
Пример #6
0
def hilightwords(message):
    """
    Finds hilight words in messages
    :param message: message to process
    :return:
    """

    logger = logging.getLogger(__name__)

    msgdetail = stampy.stampy.getmsgdetail(message)
    text_to_process = msgdetail["text"].lower()
    chat_name = msgdetail["chat_name"]
    chat_id = msgdetail["chat_id"]
    msgtype = msgdetail["chat_type"]

    keywords = gethilightwords(uid=False)
    uids = gethilightuids(word=False)

    try:
        value = stampy.plugin.stats.getstats(type=msgtype, id=chat_id)
    except:
        value = False

    if value:
        memberid = stampy.stampy.getitems(value[5])
    else:
        memberid = []

    for uid in uids:
        forward = False
        # Only forward if user is member of group
        if int(uid) in memberid:
            logger.debug(msg=_L('User %s is member of group %s') % (uid, chat_id))
            for hilight in keywords:
                if hilight in text_to_process:
                    if hilight in gethilightwords(uid=uid):
                        logger.debug(msg=_L('Word %s is in text and forwarding for user') % hilight)
                        forward = True
        else:
            logger.debug(msg=_L('User %s NOT member of group %s (%s)') % (uid, chat_id, memberid))

        if forward:
            text = _("Message sent to chat: %s") % chat_name
            stampy.stampy.sendmessage(chat_id=uid, text=text)
            result = stampy.plugin.forward.doforward(message=message, target=uid)
            if result == 'blocked':
                # User has blocked bot, remove forwards
                logger.debug(msg=_L('User %s has blocked bot direct communication, deleting hilights') % uid)
                for hilight in gethilightwords(uid=uid):
                    deletehilight(word=hilight, uid=uid)

    return
Пример #7
0
def createalias(word, value, gid=0):
    """
    Creates an alias for a word
    :param gid: Group ID to create alias on
    :param word: word to use as base for the alias
    :param value: values to set as alias
    :return:
    """

    logger = logging.getLogger(__name__)
    if getalias(value, gid=gid) == word or word.lower() == value.lower():
        logger.error(
            msg=_L("createalias: circular reference %s=%s for gid %s") %
            (word, value, gid))
    else:
        if not getalias(word, gid) or getalias(word, gid) == word:
            # Removing duplicates on karma DB and add
            # the previous values
            old = stampy.plugin.karma.getkarma(word=word, gid=gid)
            stampy.plugin.karma.updatekarma(word=word, change=-old, gid=gid)
            stampy.plugin.karma.updatekarma(word=value, change=old, gid=gid)
            sql = "INSERT INTO alias(key, value, gid) VALUES('%s','%s', '%s');" % (
                word, value, gid)
            logger.debug(msg="createalias: %s=%s for gid %s" %
                         (word, value, gid))
            stampy.stampy.dbsql(sql)
            return
    return False
Пример #8
0
def listalias(word=False, gid=0):
    """
    Lists the alias defined for a word, or all the aliases
    :param gid: Group ID to work on
    :param word: word to return value for or everything
    :return: table with alias stored
    """

    logger = logging.getLogger(__name__)
    if word:
        # if word is provided, return the alias for that word
        string = (word, gid)
        sql = "SELECT key,value FROM alias WHERE key='%s' AND gid='%s' ORDER by key ASC;" % string
        cur = stampy.stampy.dbsql(sql)
        value = cur.fetchone()

        try:
            # Get value from SQL query
            value = value[1]

        except:
            # Value didn't exist before, return 0 value
            value = 0
        text = _("%s has an alias %s") % (word, value)

    else:
        sql = "select key,value from alias WHERE gid='%s' ORDER BY key ASC;" % gid
        cur = stampy.stampy.dbsql(sql)
        text = _("Defined aliases:\n")
        table = from_db_cursor(cur)
        text = "%s\n```%s```" % (text, table.get_string())
    logger.debug(msg=_L("Returning aliases %s for word %s for gid %s") %
                 (text, word, gid))
    return text
Пример #9
0
def info(message):
    """
    Processes info commands in the messages
    :param message: message to process
    :return:
    """

    logger = logging.getLogger(__name__)

    msgdetail = stampy.stampy.getmsgdetail(message)

    chat_id = msgdetail["chat_id"]
    message_id = msgdetail["message_id"]

    text = _("This is update *%s* ") % msgdetail["update_id"]
    text += _("with message id *%s*.\n") % msgdetail["message_id"]
    text += _("This has been sent on chat *%s*, named *%s* on *%s*\n") % (
        msgdetail["chat_id"], msgdetail["chat_name"], msgdetail["datefor"])
    text += _(
        "This message was sent by user id *%s*, with given name *%s*, long name *%s* and username *%s*\n"
    ) % (msgdetail["who_id"], msgdetail["who_gn"], msgdetail["who_ln"],
         msgdetail["who_un"])

    logger.debug(msg=_L("Returning %s") % text)

    stampy.stampy.sendmessage(chat_id=chat_id,
                              text=text,
                              reply_to_message_id=message_id,
                              disable_web_page_preview=True,
                              parse_mode='markdown')
    return
Пример #10
0
def idfromuser(idorname=False, chat_id=False):
    logger = logging.getLogger(__name__)
    string = "%" + "%s" % idorname + "%"
    sql = "select id,name from stats where (name like '%s' or id like '%s')" % (
        string, string)

    if chat_id:
        string = "%" + "%s" % chat_id + "%"
        sql = sql + " and memberid like '%s'" % string

    sql = sql + ";"

    # Find user ID provided in database for current channel

    cur = stampy.stampy.dbsql(sql)
    results = []

    for row in cur:
        # Process each word returned
        results.append({"id": row[0], "name": row[1]})

    logger.debug(msg=_L("Found users with id(%s)/chat(%s): %s") %
                 (idorname, chat_id, results))

    return results
Пример #11
0
def showstats(type=False, name=None):
    """
    Shows stats for defined type or all if missing
    :param name: name to search in the stats database
    :param type: user or chat or empy for combined
    :return: table with the results
    """
    logger = logging.getLogger(__name__)
    if type:
        sql = "select type,id,name,date,count from stats WHERE type='%s'" % type

        if name:
            string = "%" + "%s" % name + "%"
            sql = sql + " and name like '%s'" % string
    else:
        sql = "select type,id,name,date,count from stats"

        if name:
            string = "%" + "%s" % name + "%"
            sql = sql + " WHERE name like '%s'" % string

    sql = sql + " ORDER BY count DESC LIMIT 10"

    cur = stampy.stampy.dbsql(sql)
    table = from_db_cursor(cur)
    text = _("Defined stats:\n")
    text = "%s\n```%s```" % (text, table.get_string())
    logger.debug(msg=_L("Returning stats %s") % text)
    return text
Пример #12
0
def getoutcommands(message):
    """
    Processes getout commands in the messages
    :param message: message to process
    :return:
    """

    logger = logging.getLogger(__name__)

    msgdetail = stampy.stampy.getmsgdetail(message)

    texto = msgdetail["text"]
    chat_id = msgdetail["chat_id"]
    who_un = msgdetail["who_un"]

    if stampy.stampy.is_owner(message):
        logger.debug(msg=_L("Owner getout: %s by %s") % (texto, who_un))
        try:
            command = texto.split(' ')[1]
        except:
            command = False

        if command == 'here':
            command = chat_id

        if command:
            try:
                getoutofchat(chat_id=command)
            except:
                pass
    return
Пример #13
0
def unban(chat_id=False, user_id=False):
    """
    Use API call to have the bot unban user
    :param chat_id: Channel ID to unban user on
    :param user_id: User ID to unban
    :return:
    """

    logger = logging.getLogger(__name__)
    result = {'ok': False}

    if chat_id and user_id:
        url = "%s%s/unbanChatMember?chat_id=%s&user_id=%s" % (
            stampy.plugin.config.config(key='url'),
            stampy.plugin.config.config(key='token'), chat_id, user_id)

        try:
            result = json.load(urllib.urlopen(url))
        except:
            result = {'ok': False}

        logger.debug(msg="RESULT: %s" % result)

    if result['ok'] is True or result['ok'] == 'True':
        logger.info(msg=_L("User %s unbaned from %s") % (user_id, chat_id))

    return result
Пример #14
0
def autokarmawords(message):
    """
    Finds commands affecting autokarma in messages
    :param message: message to process
    :return:
    """

    logger = logging.getLogger(__name__)

    msgdetail = stampy.stampy.getmsgdetail(message)
    text_to_process = msgdetail["text"].lower()
    chat_id = msgdetail['chat_id']
    gid = stampy.stampy.geteffectivegid(gid=chat_id)

    wordadd = []

    keywords = getautokeywords(gid=gid)
    for autok in keywords:
        if autok in text_to_process:
            # If trigger word is there, add the triggered action
            for word in getautok(key=autok, gid=gid):
                wordadd.append(word + "++")

    if wordadd:
        # Reduce text in message to just the words we encountered to optimize
        msgdetail["text"] = " ".join(wordadd)
        logger.debug(msg=_L("Autokarma words %s encountered for processing") %
                     msgdetail["text"])
        stampy.plugin.karma.karmaprocess(msgdetail)

    return
Пример #15
0
def forwardmessage(message):
    """
    Forwards a message based on id/chatid to target chatid
    :param message: Message to process (contaning all details)
    :return:
    """

    logger = logging.getLogger(__name__)

    # If forward plugin is enabled, process
    forward = False
    for i in stampy.stampy.plugs:
        try:
            if 'forward' in i.__name__:
                forward = True
        except:
            continue
    if forward:
        msgdetail = stampy.stampy.getmsgdetail(message)
        chat_id = msgdetail["chat_id"]

        for target in getforward(source=chat_id):
            doforward(message=message, target=target)
    else:
        logger.debug(msg=_L("Forward plugin not enabled, skipping"))
    return
Пример #16
0
def listhilight(uid, word=False):
    """
    Lists the hilight defined for a gid or all
    :param uid: filter to group id
    :param word: word to return value for or everything
    :return: table with hilight stored
    """

    logger = logging.getLogger(__name__)
    wordtext = ""

    if not word:
        sql = "select word from hilight WHERE gid='%s' ORDER BY word ASC;" % uid
    else:
        string = (word, uid)
        sql = "SELECT word FROM hilight WHERE word='%s' AND gid='%s' ORDER by word ASC;" % string
        wordtext = _("for word %s for uid %s") % (word, uid)

    cur = stampy.stampy.dbsql(sql)

    try:
        # Get value from SQL query
        text = _("Defined hilight triggers %s:\n") % wordtext
        table = from_db_cursor(cur)
        text = "%s\n```%s```" % (text, table.get_string())

    except:
        # Value didn't exist before
        text = _("%s has no trigger hilight") % word

    logger.debug(msg=_L("Returning hilight %s for word %s") % (text, word))
    return text
Пример #17
0
def listautok(word=False, gid=0):
    """
    Lists the autok pairs defined for a word, or all the autok
    :param gid: filter to group id
    :param word: word to return value for or everything
    :return: table with autok stored
    """

    logger = logging.getLogger(__name__)
    wordtext = ""

    if not word:
        sql = "select key,value from autokarma ORDER BY key ASC;"
    else:
        string = (word, gid)
        sql = "SELECT key,value FROM autokarma WHERE key='%s' AND gid='%s' ORDER by key ASC;" % string
        wordtext = _("for word %s for gid %s") % (word, gid)

    cur = stampy.stampy.dbsql(sql)

    try:
        # Get value from SQL query
        text = _("Defined autokarma triggers %s:\n") % wordtext
        table = from_db_cursor(cur)
        text = "%s\n```%s```" % (text, table.get_string())

    except:
        # Value didn't exist before
        text = _("%s has no trigger autokarma") % word

    logger.debug(msg=_L("Returning autokarma %s for word %s") % (text, word))
    return text
Пример #18
0
def feedadd(name=False, url=False, gid=0, interval=30):
    """
    Adds a quote for a specified username
    :param gid: group id to filter
    :param name: name of feed
    :param url: rss feed url
    :param interval: interval in minutes between checks
    :return: returns feed ID entry in database
    """

    logger = logging.getLogger(__name__)
    if name and url:
        date = datetime.datetime.now()
        lastchecked = date.strftime('%Y/%m/%d %H:%M:%S')
        sql = "INSERT INTO feeds(name, url, gid, lastchecked, interval) VALUES('%s','%s', '%s', '%s', '%s');" % (
            name, url, gid, lastchecked, interval)
        cur = stampy.stampy.dbsql(sql)
        logger.debug(msg=_L("feedadd: %s on %s for group %s") %
                     (name, url, gid))
        # Retrieve last id
        sql = "select last_insert_rowid();"
        cur = stampy.stampy.dbsql(sql)
        lastrowid = cur.fetchone()[0]
    else:
        lastrowid = False

    return lastrowid
Пример #19
0
def showconfig(key=False, gid=0):
    """
    Shows configuration in database for a key or all values
    :param gid: group ID to check
    :param key: key to return value for
    :return: Value stored
    """
    logger = logging.getLogger(__name__)
    if key:
        # if word is provided, return the config for that key
        string = (key, )
        sql = "SELECT key,value FROM config WHERE key='%s' AND id='%s';" % (
            string, gid)
        cur = stampy.stampy.dbsql(sql)
        value = cur.fetchone()

        try:
            # Get value from SQL query
            value = value[1]

        except:
            # Value didn't exist before, return 0 value
            value = 0
        text = _("%s has a value of %s for id %s") % (key, value, gid)

    else:
        sql = "select key,value from config WHERE id='%s' ORDER BY key ASC;" % gid
        cur = stampy.stampy.dbsql(sql)
        text = _("Defined configurations for gid %s:\n") % gid
        table = from_db_cursor(cur)
        text = "%s\n```%s```" % (text, table.get_string())
    logger.debug(msg=_L("Returning config %s for key %s for id %s") %
                 (text, key, gid))
    return text
Пример #20
0
def basecommands(message):
    """
    Processes link commands in the message
    :param message: message to process
    :return:
    """
    msgdetail = stampy.stampy.getmsgdetail(message)

    texto = msgdetail["text"]
    who_un = msgdetail["who_un"]

    logger = logging.getLogger(__name__)

    # Only users defined as 'owner' or 'admin' can perform commands
    if stampy.stampy.is_owner(message):
        logger.debug(msg=_L("Command: %s by %s") % (texto, who_un))
        try:
            command = texto.split(' ')[0]
        except:
            command = False

        for case in stampy.stampy.Switch(command):
            if case('/quit'):
                stampy.plugin.config.setconfig('daemon', False)
                break
            if case():
                break
    return
Пример #21
0
def uptime(message):
    """
    Processes uptime commands in the messages
    :param message: message to process
    :return:
    """

    logger = logging.getLogger(__name__)

    msgdetail = stampy.stampy.getmsgdetail(message)

    chat_id = msgdetail["chat_id"]
    message_id = msgdetail["message_id"]

    datelast = stampy.stampy.utize(dateutil.parser.parse(stampy.plugin.config.config(key='uptime', gid=0)))
    datelastfor = datelast.strftime('%Y/%m/%d %H:%M:%S')
    datelastts = time.mktime(datelast.timetuple())
    date = stampy.stampy.utize(datetime.datetime.now())
    datefor = date.strftime('%Y/%m/%d %H:%M:%S')
    dateforts = time.mktime(date.timetuple())
    elapsed = dateforts - datelastts

    text = _("Bot was started at: %s\n") % datelastfor
    text += _("Now it is: %s\n") % datefor
    text += _("Elapsed time: %s (seconds)\n") % elapsed
    text += _("Elapsed time: %s \n") % format_timedelta(datetime.timedelta(seconds=elapsed), locale=stampy.stampy.language)

    logger.debug(msg=_L("Returning %s") % text)

    stampy.stampy.sendmessage(chat_id=chat_id, text=text,
                              reply_to_message_id=message_id,
                              disable_web_page_preview=True,
                              parse_mode='markdown')
    return
Пример #22
0
def stock(message):
    """
    Processes stock commands
    :param message: Message with the command
    :return:
    """

    logger = logging.getLogger(__name__)
    c = IEXAPI()

    msgdetail = stampy.stampy.getmsgdetail(message)

    texto = msgdetail["text"]
    chat_id = msgdetail["chat_id"]
    message_id = msgdetail["message_id"]
    who_un = msgdetail["who_un"]

    logger.debug(msg=_L("Command: %s by %s" % (texto, who_un)))

    # We might be have been given no command, just stock
    try:
        command = texto.split(' ')[1]
    except:
        command = False

    if not command:
        stock = stampy.plugin.config.gconfig(key="stock",
                                             default="RHT",
                                             gid=chat_id).split(" ")
    else:
        stock = texto.split(" ")[1::]

    text = "```\n"
    currency = stampy.plugin.config.gconfig(key="currency",
                                            default="EUR",
                                            gid=chat_id)
    if currency != 'USD':
        rate = get_currency_rate('USD', currency)
    else:
        rate = 1
    text += _("USD/%s rate " % currency + str(rate) + "\n")
    for ticker in stock:
        try:
            quote = c.get(ticker.upper())
            text += "%s Quote " % quote["t"] + " " + str(
                quote["l_cur"]) + " " + str(
                    quote["c"]) + " (%s%%)" % str(quote["cp"])
            quoteUSD = quote["l_cur"]
            quoteEur = float(quoteUSD * rate)
            text += " (%s %s)\n" % ("{0:.2f}".format(quoteEur), currency)
        except:
            text += ""

    text += "```"
    stampy.stampy.sendmessage(chat_id=chat_id,
                              text=text,
                              reply_to_message_id=message_id,
                              disable_web_page_preview=True,
                              parse_mode="Markdown")
Пример #23
0
def cn(message):
    """
    Processes cn commands
    :param message: Message with the command
    :return:
    """

    logger = logging.getLogger(__name__)

    msgdetail = stampy.stampy.getmsgdetail(message)

    texto = msgdetail["text"]
    chat_id = msgdetail["chat_id"]
    message_id = msgdetail["message_id"]
    who_un = msgdetail["who_un"]

    logger.debug(msg=_L("Command: %s by %s" % (texto, who_un)))

    # We might be have been given no command, just stock
    try:
        command = texto.split(' ')[1]
    except:
        command = False

    if not command:
        url = "https://api.chucknorris.io/jokes/random"
    else:
        url = "https://api.chucknorris.io/jokes/search?query=%s" % command

    text = "``` "
    # we might get more than one result
    try:
        result = json.loads(requests.get(url).content)
    except:
        result = None

    if result:
        if 'result' in result:
            if result['total'] != 0:
                try:
                    totalelem = len(result['result'])
                except:
                    totalelem = 0
                if totalelem > 1:
                    elem = random.randint(0, totalelem - 1)
                else:
                    elem = 0
                text += result['result'][elem]['value']
            else:
                text += "Chuck Norris didn't said a word about it."
        else:
            text += result['value']

    text += " ```"
    stampy.stampy.sendmessage(chat_id=chat_id, text=text,
                              reply_to_message_id=message_id,
                              disable_web_page_preview=True,
                              parse_mode="Markdown")
Пример #24
0
def createforward(source, target):
    """
    Creates a forward for specified source
    :param source: chatid for source messages
    :param target: chatid for destination messages
    :return:
    """

    logger = logging.getLogger(__name__)
    if getforward(source) == target:
        logger.error(msg=_L("createforward: circular reference %s=%s") %
                     (source, target))
    else:
        sql = "INSERT INTO forward VALUES('%s','%s');" % (source, target)
        logger.debug(msg=_L("createforward: %s=%s" % (source, target)))
        stampy.stampy.dbsql(sql)
        return
    return False
Пример #25
0
def statscommands(message):
    """
    Processes stats commands in the messages
    :param message: message to process
    :return:
    """

    logger = logging.getLogger(__name__)

    msgdetail = stampy.stampy.getmsgdetail(message)

    texto = msgdetail["text"]
    chat_id = msgdetail["chat_id"]
    message_id = msgdetail["message_id"]
    who_un = msgdetail["who_un"]

    if stampy.stampy.is_owner(message):
        logger.debug(msg=_L("Owner Stat: %s by %s") % (texto, who_un))
        try:
            command = texto.split(' ')[1]
        except:
            command = False

        try:
            key = texto.split(' ')[2]
        except:
            key = ""

        for case in stampy.stampy.Switch(command):
            if case('show'):
                text = showstats(type=key)
                stampy.stampy.sendmessage(chat_id=chat_id,
                                          text=text,
                                          reply_to_message_id=message_id,
                                          disable_web_page_preview=True,
                                          parse_mode="Markdown")
                break
            if case('purge'):
                dochatcleanup()
                dousercleanup()

                break

            if case('search'):
                text = showstats(name=key)
                stampy.stampy.sendmessage(chat_id=chat_id,
                                          text=text,
                                          reply_to_message_id=message_id,
                                          disable_web_page_preview=True,
                                          parse_mode="Markdown")

                break

            if case():
                break

    return
Пример #26
0
def dokarmacleanup(word=False,
                   maxage=int(
                       stampy.plugin.config.config("maxage", default=180))):
    """
    Checks on the karma database the date of the last update in the word
    :param word: word to query in database
    :param maxage: defines maximum number of days to allow karma to be inactive
    """

    logger = logging.getLogger(__name__)

    if word:
        sql = "SELECT word,value,date FROM karma WHERE word=%s" % word
    else:
        sql = "SELECT word,value,date,gid FROM karma"

    words = []
    cur = stampy.stampy.dbsql(sql)

    logger.debug(msg=_L("Processing words for cleanup: %s") % words)

    for row in cur:
        # Process each word returned
        word = row[0]
        date = row[2]
        gid = row[3]

        if date and (date != "False"):
            worddate = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
        else:
            worddate = datetime.datetime.now()

        now = datetime.datetime.now()

        if (now - worddate).days > maxage:
            logger.debug(msg=_L(
                "Word %s with %s inactivity days is going to be purged") %
                         (word, (now - worddate).days))
            words.append({'word': word, 'gid': gid})

    for old in words:
        # Remove word from database based on prior loop
        putkarma(word=old['word'], value=0, gid=old['gid'])
    return
Пример #27
0
def helpcommands(message):
    """
    Searches for commands related to help
    :param message: nessage to process
    :return:
    """

    logger = logging.getLogger(__name__)

    msgdetail = stampy.stampy.getmsgdetail(message)

    texto = msgdetail["text"]
    chat_id = msgdetail["chat_id"]
    message_id = msgdetail["message_id"]
    who_un = msgdetail["who_un"]

    logger.debug(msg=_L("Command: %s by %s") % (texto, who_un))

    if chat_id != msgdetail['who_id']:
        # Provide text on public channel
        text = _("Message sent privately, open a chat with @%s and say hi to receive private messages or read https://github.com/iranzo/stampython/blob/master/README.md\n") % stampy.stampy.getme()
        stampy.stampy.sendmessage(chat_id=chat_id, text=text,
                                  reply_to_message_id=message_id)

        # We asked for help on public channel, answer privately
        chat_id = msgdetail['who_id']
        message_id = False

    # Call plugins to process help messages
    commandtext = ""

    for i in stampy.stampy.plugs:
        if i.__name__.split(".")[-1] != "help":
            commandtext += i.help(message=message)

    for i in stampy.stampy.plugs:
        if i.__name__.split(".")[-1] == "help":
            commandtext += i.help(message=message)

    logger.debug(msg=_L("Command: %s") % texto)

    return stampy.stampy.sendmessage(chat_id=chat_id, text=commandtext,
                                     reply_to_message_id=message_id,
                                     parse_mode="Markdown")
Пример #28
0
def hilightcommands(message):
    """
    Processes hilight commands in the message texts
    :return:
    """

    logger = logging.getLogger(__name__)

    msgdetail = stampy.stampy.getmsgdetail(message)

    texto = msgdetail["text"]
    chat_id = msgdetail["chat_id"]
    message_id = msgdetail["message_id"]
    who_un = msgdetail["who_un"]
    who_id = msgdetail["who_id"]

    logger.debug(msg=_L("Command: %s by user: %s") % (texto, who_un))
    try:
        command = texto.split(' ')[1]
    except:
        command = False
    try:
        word = texto.split(' ')[2]
    except:
        word = ""

    for case in stampy.stampy.Switch(command):
        if case('list'):
            text = listhilight(word=word, uid=who_id)
            stampy.stampy.sendmessage(chat_id=chat_id, text=text,
                                      reply_to_message_id=message_id,
                                      disable_web_page_preview=True,
                                      parse_mode="Markdown")
            break
        if case('delete'):
            text = _("Deleting hilight for `%s`") % word
            stampy.stampy.sendmessage(chat_id=chat_id, text=text,
                                      reply_to_message_id=message_id,
                                      disable_web_page_preview=True,
                                      parse_mode="Markdown")
            deletehilight(word=word, uid=who_id)
            break

        if case('add'):
            text = _("Adding hilight for `%s`") % word
            stampy.stampy.sendmessage(chat_id=chat_id, text=text,
                                      reply_to_message_id=message_id,
                                      disable_web_page_preview=True,
                                      parse_mode="Markdown")
            createhilight(word=word, uid=who_id)
            break

        if case():
            break

    return
Пример #29
0
def changenmastertoken(message):
    """
    Generates Master token for channel
    :param message: Message to process
    :return:
    """

    msgdetail = stampy.stampy.getmsgdetail(message)

    chat_id = msgdetail["chat_id"]
    message_id = msgdetail["message_id"]

    logger = logging.getLogger(__name__)

    if not stampy.plugin.config.config(key='link', default=False, gid=chat_id):
        if not stampy.plugin.config.config(key='link-master', default=False, gid=chat_id):
            charset = string.letters + string.digits
            size = 20
            token = ''.join((random.choice(charset)) for x in range(size))
            generatedtoken = "%s:%s" % (chat_id, token)
            stampy.plugin.config.setconfig(key='link-master', gid=chat_id,
                                           value=generatedtoken)
            logger.debug(msg=_L("Generated token %s for channel %s") % (token, chat_id))
            text = _("Token for linking against this channel has been generated "
                     "as %s") % generatedtoken
        else:
            generatedtoken = stampy.plugin.config.config(key='link-master', default=False, gid=chat_id)
            logger.debug(msg=_L("Already generated token %s for channel %s") % (generatedtoken, chat_id))
            text = _("A token for linking against this channel already existed as %s") % generatedtoken

        text = text + _("\n\nChannel has also been enabled as running in isolated "
                        "mode, use ```/gconfig delete isolated``` to revert back to "
                        "global karma")
        stampy.plugin.config.setconfig(key='isolated', gid=chat_id, value=True)

    else:
        text = _("This channel is a slave for another one, cannot generate token")

    stampy.stampy.sendmessage(chat_id=chat_id, text=text,
                              reply_to_message_id=message_id,
                              disable_web_page_preview=True,
                              parse_mode="Markdown")
    return
Пример #30
0
def deleteconfig(key, gid=0):
    """
    Deletes a config parameter in database
    :param gid: group ID to check
    :param key: key to remove
    :return:
    """

    logger = logging.getLogger(__name__)
    sql = "DELETE FROM config WHERE key='%s' AND id='%s';" % (key, gid)
    logger.debug(msg=_L("rmconfig: %s for id %s") % (key, gid))
    stampy.stampy.dbsql(sql)
    return