Example #1
0
def parse(templateFile, data):
		if data.settings['DEBUG']:
				data.debug.append("nestCounter: " + str(data.nestCounter) + "\ttemplate: " + templateFile)
		data.nestCounter += 1
		page = ""
		global nestCounter
		templateFile = data.settings['TEMPLATE_DIR'] + templateFile
		#check if tempalete file exist
		if os.path.isfile(templateFile):
				#match variables, templaset and blocks and so on..
				variableRe = re.compile('#.*#')
				templateRe = re.compile('{.*}')
				blockRe = re.compile('\[.*\]')
				linkRe = re.compile('\$.*\$.*\$')
				conditionRe = re.compile('.*\@.*\@.*\@.*')
				templVariableRe = re.compile('.*\%.*\%.*')

				#open file
				f = open( templateFile ,"r")
				for line in f:
						#Add variables
						if templVariableRe.match(line):
								newLine = line
								lineLen = len(line)
								lineLenTemp = len(line)
								paramTemp = []
								firstChar = 0
								secondChar = 0
								#find variables, check if exist and append
								while (lineLen > 0):
										#find first % character
										firstChar = line.find('%',firstChar, lineLenTemp)
										#second character
										secondChar = line.find('%', firstChar+1, lineLenTemp)
										#there is no first char, so break
										if firstChar < 0:
												break

										tempString = line[firstChar:secondChar+1].replace("%","")
										
										#check is there is data for variable
										try:
												data.variables[tempString]
										except KeyError:
												data.warnings.append("No variable " + tempString)
												#remove it?
												if data.settings['DEBUG']:
														newLine = newLine.replace("%"+tempString+"%","<b>%"+tempString+"%</b>")
												else:
														newLine = newLine.replace("%"+tempString+"%", "")
										else:
												newLine = newLine.replace("%"+tempString+"%", data.variables[tempString])

										firstChar = secondChar + 1
								line = newLine
						if variableRe.match(line):
								#pick data from variables
								parse_variables(line.replace("\n", ""), data)
						elif conditionRe.match(line):
								#test conditions and parse templates is conditions are true
								page = page + parse_conditions(line.replace("\n", ""), data)
						elif templateRe.match(line):
								#import other templates and parse it
								if data.nestCounter > data.maxNest:
										data.warnings.append("Too many recursives on templates: maxNest="+str(data.maxNest)+", nestCounter="+str(data.nestCounter)+"\n")
								page = page + parse_templates(line.replace("\n", ""), data)
						elif blockRe.match(line):
								#add plugins
								page = page + plugin.add_plugin(line.replace("\n", ""), data)
						elif linkRe.match(line):
								#parse links
								page = page + parse_links(line.replace("\n", ""),data)
						else:
								page = page + line
				f.close()
		else:
				#there is no requested temlate
				data.errors.append("No Such file: " + templateFile)

		return page
Example #2
0
import fetcher
import plugin

URL = r'https://open.spotify.com/%s/%s'


def build_spotify_url_from_uri(uri):
    uri_parts = uri.split(':')
    unit = uri_parts[1]
    spotify_id = uri_parts[2]
    return URL % (unit, spotify_id)


def resolve_spotify_uri(irc, _user, target, line):
    regexp = re.compile(r'spotify:[a-z]*:[a-zA-Z0-9]*', re.IGNORECASE)
    uris = re.findall(regexp, line)
    for uri in uris:
        url = build_spotify_url_from_uri(uri)
        page = fetcher.fetch_page(url)
        tree = html.fromstring(page)
        title = tree.xpath('/html/head/title/text()')
        if len(title) >= 1:
            msg = 'Title: %s - %s' % (title[0], url)
            msg = msg.replace('\n', ' ')
            msg = re.sub(r'\s+', ' ', msg).strip()
            irc.msg(target, msg)


plugin.add_plugin('spotify:', resolve_spotify_uri)
Example #3
0
import random

import plugin


def decide(irc, _user, target, msg):
    items = msg.split(' ')
    # return if there are no choices to choose from
    if len(items) <= 2:
        return

    # remove empty "items"
    items = [item for item in items if item != '']
    # skip the first item, which is '!decide '
    rnd = random.randint(1, len(items) - 1)
    item = items[rnd]
    item = item.lstrip().rstrip()
    irc.msg(target, item)


plugin.add_plugin('^!decide ', decide)
plugin.add_help('!decide',
                'Randomly select an option. Example: !decide tea coffee beer')
Example #4
0
import time

import plugin

MAX_LINES = 12

hist_lines = []


def history(irc, user, _target, msg):
    usernick, _ = user.split('!', 1)

    if msg == '!history':
        for timestamp, nick, line in hist_lines:
            result = '%s <%s> %s' % (timestamp, nick, line)
            irc.msg(usernick, result)
    else:
        now = time.strftime('UTC %Y.%m.%d %H:%M:%S', time.gmtime())
        hist_lines.append([now, usernick, msg])
        if len(hist_lines) > MAX_LINES:
            hist_lines.pop(0)


plugin.add_plugin('', history)
plugin.add_help('!history',
                'Sends you the last %s messages on the channel' % MAX_LINES)
Example #5
0
import re

import plugin


def help(irc, _user, target, msg):
    if re.search('^!help\Z', msg):
        doc = 'Available commands: %s' % plugin.get_help()
        irc.msg(target, doc)
    elif re.search('^!help !.+', msg):
        cmd, plug = msg.split(None, 1)
        doc = plugin.get_help(plug)
        irc.msg(target, doc)
    else:
        irc.msg(target, "Usage example: !help !wp")


plugin.add_plugin('^!help', help)
plugin.add_help('!help', 'Help command. Example: !help !wp')
Example #6
0
            params=dict(q=query),
        )
        return self._parse_video_links_from_string(response.content)

    def _parse_video_links_from_string(self, response):
        xpath_query = '//div[@class="h-box"]/p/a[starts-with(@href, "/watch?v=")]'

        tree = html.fromstring(response)
        elements = tree.xpath(xpath_query)

        return self._process_links_from_elements(elements)

    def _process_links_from_elements(self, elements):
        """
        :type elements: list[Element]
        :rtype: dict[str, str]
        """
        links = {}

        for link in elements:
            url = "https://www.youtube.com" + link.get('href')
            links[url] = link.text

        return links


plugin.add_plugin('^!yt', youtube)
plugin.add_help(
    '!yt',
    'Search for a youtube video and select a *random* from the search result.')
Example #7
0
import re

from lxml import html

import fetcher
import plugin


def get_url_title(irc, _user, target, line):
    regexp = re.compile(
        r'https?://'
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
        r'localhost|'
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|'
        r'\[?[A-F0-9]*:[A-F0-9:]+\]?)'
        r'(?::\d+)?'
        r'(?:/?\S+)', re.IGNORECASE)
    urls = re.findall(regexp, line)
    for url in urls:
        page = fetcher.fetch_page(url)
        tree = html.fromstring(page)
        title = tree.xpath('/html//title/text()')
        if len(title) >= 1:
            msg = 'URL title: %s' % title[0]
            msg = msg.replace('\n', ' ')
            msg = re.sub(r'\s+', ' ', msg).strip()
            irc.msg(target, msg)


plugin.add_plugin('https?://', get_url_title)
Example #8
0
import plugin


def wttr(irc, user, target, msg):
    nick = user.partition('!')[0]
    items = msg.split(' ')
    if len(items) <= 1:
        city = "Budapest"
    else:
        city = "+".join(items[1:])

    reply = Wttr().get_wttr(city, nick)
    irc.msg(target, reply)


plugin.add_plugin('^(!wttr)( .*)?$', wttr)
plugin.add_help('!wttr',
                'Fancy weather forecast using wttr.it Example: !wttr Budapest')


class Wttr:
    def __init__(self):
        self.nick = ""
        self.wttr = ""

    def get_wttr(self, city, nick):
        self.nick = nick
        req = requests.get("http://wttr.in/" + city)
        self.wttr = req.text.split('\n')
        response = self.__format_response()
        return response
Example #9
0
import common
import plugin

WELCOME_FILE = 'welcome.yaml'
WELCOME_TIME = 12 * 3600

# store timestamps for welcomes
memory = {}


def welcome(irc, user, channel, _msg=None):

    try:
        welcomes = common.parse_config('plugins/' + WELCOME_FILE)
    except Exception:
        # fail gracefully, but uninformatively
        return

    for regexp, message in welcomes.items():
        regexp = re.compile(regexp, re.I)
        timestamp = memory.get(regexp, 0)
        if re.search(regexp, user) and timestamp < time.time() - WELCOME_TIME:
            line = '[%s] ' % user
            line += message
            irc.msg(channel, line)
            memory[regexp] = time.time()


plugin.add_plugin('', welcome, 'join')
Example #10
0
        "en": "https://www.a38.hu/en/restaurant"
    }

    def __init__(self, lang="en", **kwargs):
        self.requests = kwargs.get('requests', requests)
        self.url = A38.LANGUAGES.get(lang, A38.LANGUAGES["en"])

    def fetch_todays_menu(self):
        """
        :rtype: str
        """
        response = self.requests.get(self.url)
        tree = html.fromstring(response.content)

        menu = tree.xpath(
            '//div[@class="foodCard__foodlist"]/text()')  # type: list[str]

        if not menu:
            return 'No menu found @ A38'

        return 'Current A38 menu: %s' % self.format_menu(menu)

    def format_menu(self, menu):
        return ' | '.join(
            [dish.strip() for dish in menu if dish.strip() != ""])


plugin.add_plugin('^!a38', a38)
plugin.add_help('!a38',
                'Query A-38 menu. For other languages, please add [en|hu]')
Example #11
0
        'It is decidedly so',
        'Without a doubt',
        'Yes definitely',
        'You may rely on it',
        'As I see it, yes',
        'Most likely',
        'Outlook good',
        'Yes',
        'Signs point to yes',
        'Reply hazy try again',
        'Ask again later',
        'Better not tell you now',
        'Cannot predict now',
        'Concentrate and ask again',
        'Don\'t count on it',
        'My reply is no',
        'My sources say no',
        'Outlook not so good',
        'Very doubtful',
    ]

    rnd = random.randint(0, len(answers) - 1)
    irc.msg(target, nick + ': ' + answers[rnd])


plugin.add_plugin('^!8ball ', eightball)
plugin.add_help(
    '!8ball', 'The Magic 8-Ball is a toy used for fortune-telling or seeking'
    ' advice, developed in the 1950s. Example: !8ball Will I have'
    ' a great day?')
Example #12
0
import subprocess

import plugin


def fortune(irc, _user, target, _msg):
    try:
        output = subprocess.check_output('fortune').decode()
    except Exception as e:
        irc.msg(target, 'Error executing "fortune":' % e)
    lines = output.split('\n')
    # pop: Remove last empty element
    lines.pop()
    for line in lines:
        irc.msg(target, line)


plugin.add_plugin('^!fortune\Z', fortune)
plugin.add_help('!fortune', 'Provide a random fortune')
Example #13
0
import fetcher
import plugin

BASE_URL = 'https://html.duckduckgo.com/html/?q=site:imdb.com '
ERROR_FUN = 'That is the story of your life, isn\'t it?'


def search_imdb(irc, _user, target, line):
    url = BASE_URL + line.replace('!imdb ', '')
    page = fetcher.fetch_page(url)

    if page is None:
        answer = ERROR_FUN
    else:
        try:
            xpath_query = '//a[@class="result__a"]'
            tree = html.fromstring(page)
            elements = tree.xpath(xpath_query)
            answer = elements[0].get('href', ERROR_FUN)
            answer += ' -- ' + elements[0].text_content()
        except (IndexError, TypeError):
            answer = ERROR_FUN

    irc.msg(target, answer)


plugin.add_plugin('^!imdb', search_imdb)
plugin.add_help('!imdb',
                'Search for movie or series or actor/actress etc. in imdb.')
Example #14
0
def create_msg(data):
    date = data[0]
    new_cases = data[2]
    new_passed_away = data[17]
    new_healed = data[18]
    new_tests = data[15]
    active_cases = data[11]
    ventilator = data[20]
    vaccinated = data[32]
    new_vaccinated = data[33]
    second_vaccine = data[35]
    new_second_vaccine = data[36]

    msg = date + ' napi adatok'
    msg += ' | új esetek ' + new_cases
    msg += ' | elhunyt ' + new_passed_away
    msg += ' | gyógyult ' + new_healed
    msg += ' | tesztek ' + new_tests
    msg += ' | aktív esetek ' + active_cases
    msg += ' | lélegeztetőn ' + ventilator
    msg += ' | oltottak ' + vaccinated
    msg += ' | napi oltottak ' + new_vaccinated
    msg += ' | második oltás ' + second_vaccine
    msg += ' | második oltás napi ' + new_second_vaccine + ' ||'

    return msg


plugin.add_plugin('^!covid', covid)
plugin.add_help('!covid', 'Hungarian covid stats')
Example #15
0
from sys import version_info as vi

import plugin


def j_version(irc, _user, target, _msg):
    v1 = vi.major
    v2 = vi.minor
    v3 = vi.micro
    irc.msg(target, "I'm running on Python {}.{}.{}".format(v1, v2, v3))


plugin.add_plugin('^!ver\Z', j_version)
plugin.add_help('!ver', 'Show Python version')
Example #16
0
import pickle
import re

import plugin

FACT_FILE = 'facts.dat'


def oraculum_q(irc, _user, target, msg):
    if re.search('^\? .+', msg):
        cmd, topic = msg.split(' ', 1)
        try:
            with open(FACT_FILE, 'rb') as f:
                facts = pickle.load(f)
                fact = facts.get(topic, None)
                if fact:
                    line = '%s: %s' % (topic, fact)
                    irc.msg(target, line)
                else:
                    irc.msg(target, 'No such fact: %s' % topic)
        except Exception:
            # TODO: error handling
            return


# plugin.add_plugin('^![+-] ', oraculum)
plugin.add_plugin('^\? .+', oraculum_q)
Example #17
0
import wikipedia

import plugin


def wikipedia_lookup(irc, _user, target, msg):
    _cmd, title = msg.split(None, 1)
    wikipedia.set_lang('en')

    try:
        page = wikipedia.summary(title, sentences=1)
        page += " For more: " + wikipedia.page(title).url
    except wikipedia.DisambiguationError as exc:
        pages = ' | '.join(exc.options[:10])
        results = '"%s" may refer to: %s' % (title, pages)
        irc.msg(target, results)
        return
    except wikipedia.PageError:
        line = 'No such page: %s' % title
        irc.msg(target, line)
        return

    irc.msg(target, page)


plugin.add_plugin('^!wp ', wikipedia_lookup)
plugin.add_help('!wp', 'Query Wikipedia. Example: !wp ozric tentacles')
Example #18
0
import base64

import plugin


def b64(irc, _user, target, msg):
    cmd, text = msg.split(None, 1)

    # Lazy
    if cmd == '!b64d':
        result = base64.b64decode(text)
    else:
        result = base64.b64encode(text)
    irc.msg(target, 'Base64: %s ' % result)
    return


plugin.add_plugin('^!(base64|b64e?|b64d) ', b64)
plugin.add_help('!base64', 'Base64 encodes the argument. Example: !base64 foo')
plugin.add_help('!b64d', 'Base64 decodes the argument. Example: !b64d Zm9v')