コード例 #1
0
ファイル: howdoi.py プロジェクト: sork01/Jante_plugins
class hdiPlugin(parsingplugintemplate):
    def __init__(self, bot):
        super(hdiPlugin, self).__init__(bot,
                                        command="howdoi",
                                        description="How to do things")

        self._config = bot.getConfig()
        self.parser = JanteParser(description='Get told how to do things',
                                  prog='howdoi',
                                  add_help=False)
        self.parser.add_argument('-h',
                                 '--help',
                                 action='store_true',
                                 required=False,
                                 help="Shows this helpful message.")
        self.parser.add_argument("search_terms",
                                 nargs="*",
                                 metavar="search terms",
                                 help="Words that will be searched.")

    def paste(self, text, message):
        return self._bot.getService("paste").paste(text, message)

    def search(self, word):

        parser = howdoi.get_parser()
        args = vars(parser.parse_args(word.split(' ')))

        output = howdoi.howdoi(args)

        return output if output.strip(
        ) != "" else "Did not find anything containing that"

    def parse(self, message):
        try:
            args = self.parser.parse_args(message.getText().split(" "))
        except ArgumentParserError as error:
            return ArgumentParserError("\n{}".format(error))

        search_terms = " ".join(args.search_terms)
        if args.help:
            return self.parser.format_help()

        return self.paste(self.search(search_terms), message)
コード例 #2
0
ファイル: kana.py プロジェクト: sork01/Jante_plugins
class KanaPlugin(parsingplugintemplate):
    def __init__(self, bot):
        super(KanaPlugin,
              self).__init__(bot,
                             command="kana",
                             description="Translates English to japanese kana")

        self.parser = JanteParser(
            description='Translates English to japanese kana',
            prog='kana',
            add_help=False)
        self.parser.add_argument('-h',
                                 '--help',
                                 action='store_true',
                                 required=False,
                                 help="Shows this helpful message.")
        self.parser.add_argument("words", nargs="*", help="The search words")

    def kana(self, searchword):
        query = urllib.parse.quote(searchword)
        HEADER = {
            'User-Agent':
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"
        }
        url = "https://www.sljfaq.org/cgi/e2k.cgi?word=" + query
        req = urllib.request.Request(url, headers=HEADER)
        response = urllib.request.urlopen(req)
        html = response.read()
        soup = BeautifulSoup(html, 'html.parser')
        kana = soup.find("td", class_="katakana-string").text
        return kana.strip()

    def parse(self, message):

        try:
            args = self.parser.parse_args(message.getText().split(" "))
        except ArgumentParserError as error:
            return ArgumentParserError("\n{}".format(error))
        ans = " ".join(args.words)
        if args.help:
            return self.parser.format_help()
        else:
            return self.kana(ans)
コード例 #3
0
ファイル: wp.py プロジェクト: sork01/Jante_plugins
class WpPlugin(parsingplugintemplate):
    def __init__(self, bot):
        super(WpPlugin, self).__init__(bot,
                                       command="wp",
                                       description="Get things from wikipedia")

        self._config = bot.getConfig()
        self.parser = JanteParser(description='Get things from wikipedia',
                                  prog='wp',
                                  add_help=False)
        self.parser.add_argument('-h',
                                 '--help',
                                 action='store_true',
                                 required=False,
                                 help="Shows this helpful message.")
        self.parser.add_argument("search_terms",
                                 nargs="*",
                                 metavar="search terms",
                                 help="Words that will be searched.")
        self.parser.add_argument('-e',
                                 '--english',
                                 action='store_true',
                                 required=False,
                                 help="English wikipedia.")

    def paste(self, text, message):
        return self._bot.getService("paste").paste(text, message)

    def search(self, word, lang):
        wk.set_lang(lang)
        message = ""
        try:
            page = wk.page(word)
        except wk.exceptions.DisambiguationError as e:
            return "Did not find anything with that name."
        except wk.exceptions.PageError as e:
            e
            return "Did not find anything with that name."
        message += wk.summary(word)
        return message if message.strip(
        ) != "" else "Did not find anything with that name."

    def parse(self, message):
        try:
            args = self.parser.parse_args(message.getText().split(" "))
        except ArgumentParserError as error:
            return ArgumentParserError("\n{}".format(error))

        search_terms = " ".join(args.search_terms)
        if args.help:
            return self.parser.format_help()
        if args.english:
            return self.paste(self.search(search_terms, "en"), message)

        return self.paste(self.search(search_terms, "sv"), message)
コード例 #4
0
ファイル: arraks.py プロジェクト: sork01/Jante_plugins
class ArraksPlugin(parsingplugintemplate):
    def __init__(self, bot):
        super(ArraksPlugin,
              self).__init__(bot,
                             command="arraks",
                             description="gets anagrams from arraks.fi")
        self.parser = JanteParser(description='Gets anagrams from arraks.fi',
                                  prog='arraks',
                                  add_help=False)
        self.parser.add_argument('-h',
                                 '--help',
                                 action='store_true',
                                 required=False,
                                 help="Shows this helpful message.")
        self.parser.add_argument('-a',
                                 '--all',
                                 action='store_true',
                                 required=False,
                                 help="Gives all found anagrams.")
        self.parser.add_argument(
            '-l',
            '--language',
            type=str,
            default="sw",
            required=False,
            help=
            "Choose language to get the anagram in, languages being en,fi,no,da,fr,ge,du,la and sw"
        )
        self.parser.add_argument(
            '-n',
            '--mwords',
            type=int,
            default=0,
            required=False,
            help="Max number of words in anagram, from 1 to 8")
        self.parser.add_argument("words", nargs="*", help="The search words")

    def arraks(self, word, N, lang, all=False):
        if N == 0:
            if len(word.split(" ")) < 2:
                N = 2
            else:
                N = len(word.split(" "))
        br = mechanize.Browser()
        br.set_handle_robots(False)
        response = br.open("https://www.arrak.fi/sv/ag")
        response.encoding = "utf-8"
        br.form = list(br.forms())[0]
        #word = word.encode('utf-8')
        br["sourcetext"] = word.encode('windows-1252')
        br["maxword"] = [str(N)]
        languages = [
            "Swedish", "English", "Finnish", "Norwegian", "Danish", "French",
            "German", "Dutch", "Latin"
        ]
        for language in languages:
            if lang.lower() == language[:2].lower():
                chlang = language
                break
            else:
                chlang = "Swedish"
        br["lang"] = [chlang]
        resp = br.submit().read().decode('windows-1252')
        resp1 = str(resp)[2:-1]
        resp1 = resp1.replace("\n", "    ")
        print(resp1)
        res = re.findall(r'"no">([^<]+)', resp1)
        res = (res[0].replace("\\n", "     "))
        res = (res[:-4])
        res = re.split("     |    |   ", res)
        res = [x.strip() for x in res if x.strip()]
        res = list(filter(None, res))
        result = []

        for anagram in res:
            if sorted(re.split(r'\s+', word.lower())) != sorted(
                    re.split(r'\s+', anagram.lower())):
                result.append(anagram)

        message = ""
        if len(result) == 0:
            message = "No anagram found"
        else:
            if all:
                for answer in result:
                    message += (answer + ", ")
                message = message[:-2]
            else:
                message = result[random.randint(0, len(result) - 1)]
        return message

    def parse(self, message):

        try:
            args = self.parser.parse_args(message.getText().split(" "))
        except ArgumentParserError as error:
            return ArgumentParserError("\n{}".format(error))
        ans = " ".join(args.words)
        if args.help:
            return self.parser.format_help()
        if args.all:
            return self.arraks(ans, args.mwords, args.language, True)
        else:
            return self.arraks(ans, args.mwords, args.language)
コード例 #5
0
class SlPlugin(parsingplugintemplate):
    """
    Plugin for echoing things.
    Works similar to echo in bash.
    """
    def __init__(self, bot):
        super(SlPlugin, self).__init__(
            bot,
            command="sl",
            description=
            "Shows sl traveling directions, there are no useful arguments yet."
        )

        self.parser = JanteParser(
            description=
            'Shows sl traveling directions\n No useful arguments yet.',
            prog='sl',
            add_help=False)
        self.parser.add_argument('-h',
                                 '--help',
                                 action='store_true',
                                 required=False,
                                 help="Shows this helpful message.")
        self.parser.add_argument('-a',
                                 '--arrival',
                                 type=str,
                                 default="",
                                 required=False,
                                 help="Set arrival time in format HH:MM")
        self.parser.add_argument('-s',
                                 '--start',
                                 type=str,
                                 default="",
                                 required=False,
                                 help="Set starting time in format HH:MM")
        self.parser.add_argument(
            '-d',
            '--date',
            type=str,
            default="",
            required=False,
            help="Set date for arrival or departure in format YY-MM-DD")
        self.parser.add_argument("words", nargs="*", help="The search words")

    def getdirections(self, json):
        startnames = []
        destnames = []
        starttimes = []
        desttimes = []
        messageslist = []
        transportlist = []
        linelist = []
        if 'Trip' not in json:
            return "No trip found"
        trip = json['Trip']
        leglist = trip[0]['LegList']
        leg = leglist['Leg']
        for i in range(len(leg)):
            if leg[i]['type'] == 'WALK':
                continue
            origin = leg[i]['Origin']
            startnames.append(origin['name'])
            starttimes.append(origin['time'][:-3])
            destination = leg[i]['Destination']
            destnames.append(destination['name'])
            desttimes.append(destination['time'][:-3])
            if 'Messages' in leg[i]:
                messages = leg[i]['Messages']
                message = messages['Message']
                messageslist.append(message[0]['text'])
            if 'Product' in leg[i]:
                status = leg[i]['Product']
                transport = status['catOutL'].lower()
                transportlist.append(transport)
                linelist.append(status['line'])

        res = "Ta "
        for i in range(len(startnames)):
            res += (str(transportlist[i]) + "linje " + str(linelist[i]) +
                    " från " + str(startnames[i]) + " som går kl " +
                    str(starttimes[i]) + " som ankommer till " + destnames[i] +
                    " kl " + desttimes[i] + "\n")
            if i < len(startnames) - 1:
                res += "därefter "
        FMT = "%H:%M"
        tdelta = datetime.strptime(desttimes[len(desttimes) - 1],
                                   FMT) - datetime.strptime(
                                       starttimes[0], FMT)
        res += ("\nDen totala restiden är " + str(tdelta)[:-6] +
                " timmar och " + str(tdelta)[2:-3] + " minuter")
        return res

    def getids(self,
               startinput,
               destinationinput,
               time="",
               arrival=0,
               date=""):

        if startinput == destinationinput:
            return "Can't have the same start and destination"
        urlstart = "https://api.sl.se/api2/typeahead.json?key=4bae1902a34444108f283cc47fe5ccd3&searchstring=" + startinput
        urldest = "https://api.sl.se/api2/typeahead.json?key=4bae1902a34444108f283cc47fe5ccd3&searchstring=" + destinationinput

        f = requests.get(urlstart)
        f2 = requests.get(urldest)

        startlist = json.loads(f.text)
        if len(startlist['ResponseData']) == 0:
            return "No startlocation found"
        start = (startlist['ResponseData'][0])
        startid = (start['SiteId'])
        destlist = json.loads(f2.text)
        if len(destlist['ResponseData']) == 0:
            return "No destination found"
        dest = (destlist['ResponseData'][0])
        destid = (dest['SiteId'])
        trip = "https://api.sl.se/api2/TravelplannerV3_1/trip.json?key=d6dcb0574b8b4487a47e38a7079f3866&originExtId=" + startid + "&destExtId=" + destid + "&time=" + str(
            time) + "&searchForArrival=" + str(arrival) + "&date=" + date
        print(trip)
        f3 = requests.get(trip)

        tripjson = json.loads(f3.text)
        #res += "Valda stationer är " + start['Name'] + " och " + dest['Name']
        return self.getdirections(tripjson)

    def parse(self, message):
        try:
            args = self.parser.parse_args(message.getText().split(" "))
        except ArgumentParserError as error:
            return ArgumentParserError("\n{}".format(error))
        ans = " ".join(args.words)
        print(args.arrival)
        print(args.start)
        print(args.words)
        if args.help:
            return self.parser.format_help()
        if args.arrival:
            if args.date:
                return self.getids(args.words[0], args.words[1], args.arrival,
                                   1, args.date)
            return self.getids(args.words[0], args.words[1], args.arrival, 1)
        if args.start:
            if args.date:
                return self.getids(args.words[0], args.words[1], args.start, 0,
                                   args.date)
            return self.getids(args.words[0], args.words[1], args.start, 0)
        if args.date:
            return self.getids(args.words[0], args.words[1], args.start, 0,
                               args.date)
        else:
            return self.getids(args.words[0], args.words[1])
コード例 #6
0
ファイル: plex.py プロジェクト: sork01/Jante_plugins
class PlexPlugin(parsingplugintemplate):
    def __init__(self, bot):
        super(PlexPlugin, self).__init__(
            bot,
            command="plex",
            description="Search things on Robins Plex-server.")

        self._config = bot.getConfig()
        self.parser = JanteParser(description='Getting movies from plex',
                                  prog='plex',
                                  add_help=False)
        self.parser.add_argument('-h',
                                 '--help',
                                 action='store_true',
                                 required=False,
                                 help="Shows this helpful message.")
        self.parser.add_argument("search_terms",
                                 nargs="*",
                                 metavar="search terms",
                                 help="Words that will be searched.")
        self.parser.add_argument('-p',
                                 '--plot',
                                 action='store_true',
                                 required=False,
                                 help="Shows movie plot.")
        self.parser.add_argument('-t',
                                 '--tagline',
                                 action='store_true',
                                 required=False,
                                 help="Shows movie tagline.")
        self.parser.add_argument('-d',
                                 '--duration',
                                 action='store_true',
                                 required=False,
                                 help="Shows movie duration in minutes.")

    def paste(self, text, message):
        return self._bot.getService("paste").paste(text, message)

    def search(self, word, plot=False, tagline=False, duration=False):
        server_url = self._config["plex"]["serverUrl"]

        api_key = self._config["plex"]["apiKey"]

        xml = requests.get(f"{server_url}{api_key}").text
        root = ET.fromstring(xml)
        movies = {}
        entry = {}
        message = ""
        self.log(word)
        for video_tag in root.findall('Video'):
            if word.lower() in video_tag.get('title').lower():
                entry = {
                    (video_tag.get('title')): {
                        'name':
                        str((video_tag.get('title'))),
                        'year': (" (" + str(video_tag.get('year')) + ")"),
                        'plot':
                        str((video_tag.get('summary'))),
                        'tagline':
                        str((video_tag.get('tagline'))),
                        'duration':
                        str(round(int(video_tag.get('duration')) / 1000 / 60))
                        + " minutes"
                    }
                }
                movies.update(entry)
        for movie in movies:
            message += movies.get(movie).get('name') + movies.get(movie).get(
                'year')
            if plot == True:
                message += " Plot: " + movies.get(movie).get('plot')
            if tagline == True:
                message += " Tagline: " + movies.get(movie).get('tagline')
            if duration == True:
                message += " Duration: " + movies.get(movie).get('duration')
            message += "\n"
        return message if message.strip(
        ) != "" else "Did not find anything with that name."

    def parse(self, message):
        try:
            args = self.parser.parse_args(message.getText().split(" "))
        except ArgumentParserError as error:
            return ArgumentParserError("\n{}".format(error))

        search_terms = " ".join(args.search_terms)
        if args.help:
            return self.parser.format_help()
        if args.plot:
            return self.paste(self.search(search_terms, True), message)
        if args.tagline:
            return self.paste(self.search(search_terms, False, True), message)
        if args.duration:
            return self.paste(self.search(search_terms, False, False, True),
                              message)

        return self.paste(self.search(search_terms), message)
コード例 #7
0
class EchoPlugin(ParsingPluginTemplate):
    """
    Plugin for echoing things.
    Works similar to echo in bash.
    """
    def __init__(self, bot):
        super(EchoPlugin,
              self).__init__(bot,
                             command="echo",
                             description="Echo text back to the sender")

        self.parser = JanteParser(description='Echos things',
                                  prog='echo',
                                  add_help=False)
        self.parser.add_argument(
            '-t',
            '--title',
            action='store_true',
            required=False,
            help="The first characters of each word will be made uppercase.")
        self.parser.add_argument('-l',
                                 '--lower',
                                 action='store_true',
                                 required=False,
                                 help="Changes all letters to lowercase.")
        self.parser.add_argument(
            '-c',
            '--capitalize',
            action="store_true",
            help="Converts the first character of a string to uppercase.")
        self.parser.add_argument(
            '--url-encode',
            action="store_true",
            help="Encodes the string according to URL-safe conventions")
        self.parser.add_argument('-h',
                                 '--help',
                                 action='store_true',
                                 required=False,
                                 help="Shows this helpful message.")
        self.parser.add_argument('-u',
                                 '--all-caps',
                                 '--upper',
                                 action='store_true',
                                 required=False,
                                 help="Return the string in all caps.")
        self.parser.add_argument("words",
                                 nargs="*",
                                 help="Words that will be echoed.")

    def parse(self, message):
        try:
            args = self.parser.parse_args(message.get_text().split(" "))
        except ArgumentParserError as error:
            return ArgumentParserError("\n{}".format(error))
        ans = " ".join(args.words)
        if args.help:
            return self.parser.format_help()
        if args.lower:
            ans = ans.lower()
        if args.title:
            ans = ans.title()
        if args.capitalize:
            ans = ans.capitalize()
        if args.all_caps:
            ans = ans.upper()
        if args.url_encode:
            ans = urlencode({"": ans})[1:]
        return ans
コード例 #8
0
ファイル: google.py プロジェクト: sork01/Jante_plugins
class google(parsingplugintemplate):
    def __init__(self, bot):
        super(google,
              self).__init__(bot,
                             command="google",
                             description="Generates Google search queries.")

        self.parser = JanteParser(description='Searches Google',
                                  prog='google',
                                  add_help=False)
        self.parser.add_argument('-n',
                                 '--results',
                                 type=int,
                                 default=1,
                                 required=False,
                                 help="Amount of results from 1 to 100")
        self.parser.add_argument('-h',
                                 '--help',
                                 action='store_true',
                                 required=False,
                                 help="Shows this helpful message.")
        self.parser.add_argument('-l',
                                 '--lucky',
                                 action='store_true',
                                 required=False,
                                 help="Displays first result.")
        self.parser.add_argument('-i',
                                 '--image',
                                 action='store_true',
                                 required=False,
                                 help="Google Image Search.")
        self.parser.add_argument('-r',
                                 '--random',
                                 action='store_true',
                                 required=False,
                                 help="Gives a random Google Search.")
        self.parser.add_argument("words", nargs="*", help="The search words")

    def gislink(self, searchword, N, random=False):
        HEADER = {
            'User-Agent':
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36"
        }

        split_query = searchword.split()
        split_query = '+'.join(split_query)
        url = "https://www.google.co.in/search?q=" + split_query + "&tbm=isch"
        soup = BeautifulSoup(
            requests.get(url, headers=HEADER).text, 'html.parser')
        imageList = re.findall(r".+(https:.+.jpg)", soup.text[-100000:])
        if random:
            message = "Searchword: " + searchword + "\n"
        else:
            message = ""

        if len(imageList) == 0:
            return "No match for searchword " + searchword
        else:
            message += imageList[0] + '\n'
        message = message[:-1]
        return message

    def parse(self, message):
        try:
            args = self.parser.parse_args(message.getText().split(" "))
        except ArgumentParserError as error:
            return ArgumentParserError("\n{}".format(error))
        ans = " ".join(args.words)
        if args.help:
            return self.parser.format_help()
        if args.results < 1 or args.results > 100:
            return (str(args.results) + " is not a valid result")
        if args.lucky:
            if args.image:
                return self.gislink(ans, args.results)
            elif args.random:
                words = self._bot.getService("ngramkeeper").getDictionary()
                longwords = list(filter(lambda word: len(word) > 5, words))
                ans = random.choice(longwords)
                querystring = urllib.parse.urlencode({'q': ans, 'btnI': '1'})
                return 'https://www.google.com/search?{}'.format(querystring)
            else:
                querystring = urllib.parse.urlencode({'q': ans, 'btnI': '1'})
                return 'https://www.google.com/search?{}'.format(querystring)
        if args.random:
            if args.image:
                words = self._bot.getService("ngramkeeper").getDictionary()
                longwords = list(filter(lambda word: len(word) > 5, words))
                ans = random.choice(longwords)
                return self.gislink(ans, args.results, True)
            else:
                words = self._bot.getService("ngramkeeper").getDictionary()
                longwords = list(filter(lambda word: len(word) > 5, words))
                ans = random.choice(longwords)
                querystring = urllib.parse.urlencode({'q': ans})
                return 'https://www.google.com/search?{}'.format(querystring)
        if args.image:
            return self.gislink(ans, args.results)
        else:
            querystring = urllib.parse.urlencode({'q': ans})
            return 'https://www.google.com/search?{}'.format(querystring)
コード例 #9
0
class DictPlugin2(ParsingPluginTemplate):
    class DictManager():
        """
        self._datadict["__global__"] is data that is used by everyone
        self._datadict["u_<username>"] is user specific data and can only be accessed by that user.
        """
        def __init__(self, config, filename):
            self._config = config
            self._filename = filename
                
            self._global_username = "******"
            self._user_prefix = "u_"

            try:
                file_object  = open(self._filename, "r").read()

                if not len(file_object) == 0:
                    self._datadict = defaultdict(dict, json.loads(file_object)) 
                else    :
                    self._datadict = defaultdict(dict)
            except:
                self._datadict = defaultdict(dict) 

            self._mutex = threading.Lock()
        
        def _location_key(self, user, global_):
       
            if global_:
                return self._global_username
            else:
                return "{}{}".format(self._user_prefix)
        
        def exists(self, key, user="", global_=True):
            return key in self._datadict[self._location_key(user,  global_)]

        def save(self):
            with self._mutex:
                file_object = open(self._filename, 'w+')
                file_object.write(json.dumps(self._datadict))
                file_object.close()

        def keys(user="", global_=True):
            return self._datadict[self._location_key(user, global_)].keys()

        def items(user="", global_=True):
            
            items_ = self._datadict[self._location_key(user, global_)].items()

            return sorted(items_, key=lambda x: x[0])
            
        def remove(self, key, user="", global_=True):

            if not key in self._datadict[self._location_key(user, global_)]:
                return False
            
            del self._datadict[self._location_key(user, global_)][key]
            return True
       
        def get_dict(self):
            return self._datadict
        
        def get(self, key, user="", global_=True):
            return self._datadict[self._location_key(user, global_)][key]

        def size(self, user="", global_=True):
            return len(self.keys(user=user,global_=global_))
        
        def keys(self, user="", global_=True):
            return self._datadict[self._location_key(user, global_)].keys()

        def insert(self, key, value, force, global_=True, user=""):
            """
            Returns true if value was inserted, false if it was already present and force == False
            """
            current_time = time.time()
           
            location = self._location_key(user, global_)
            if key in self._datadict[location]:
                if force:
                    user_insert = self._datadict[location][key]["user_insert"]
                    time_insert = self._datadict[location][key]["time_insert"]
                else:
                    return False
            else:
                user_insert = user
                time_insert = current_time

            with self._mutex:
                self._datadict[location][key] = {
                            "value": value,
                            "user_insert": user_insert,
                            "time_insert": time_insert,
                            "user_update": user,
                            "time_update": current_time 
                    }
            return True
        
    def __init__(self, bot):
        self._config = configparser.ConfigParser()
        self._config.read("plugins/dict2/settings.ini")
        
        super(DictPlugin2, self).__init__(bot, command=self._config.get('dict','command', fallback="dict"), description="Keys and values!")


        filename = "{datapath}{filename}".format(datapath=self._bot.get_base_data_path(), filename=self._config.get("dict",'savefilename', fallback="dict2plugindata.json"))
        
        self._dict_manager = DictPlugin2.DictManager(self._config, filename)

        self._options = defaultdict(list) 
        
        self.parser = JanteParser(description='Keeps a dictionary of things.', prog='dict', add_help=False)
        self.parser.add_argument('-h', '--help', action='store_true', required=False, help="Shows this helpful message.")
        self.parser.add_argument('-k', '--key', help="The key to save the value with. Must be used with -v.")
        self.parser.add_argument('-v', '--value', help="The value to be stored. Must be used with -k.")
        self.parser.add_argument('-r', '--remove', '--delete', help="Remove a key-value pair.")
        self.parser.add_argument('--list', action='store_true', help="List all key-value pairs.")
        self.parser.add_argument('--raw', action='store_true', help="Output data as raw as possible.")
        self.parser.add_argument('--size', action='store_true', help="Show the number of keys that are saved.")
        self.parser.add_argument('--keys', action="store_true", help="Return a list of all keys.")
        self.parser.add_argument('-p', '--pick', type=int, help="Pick option <index> from options recommended to you earlier.")
        self.parser.add_argument('--force', '-f', action='store_true', help="Force an overwrite if the key already exists.")
        self.parser.add_argument('--local', '-l', action='store_false', dest="global_", default=True, help="Store or retrieve values stored by the user.")
        self.parser.add_argument('--global', dest="global_", action="store_true", default=True, help="Store or retrieve globally stored values")
        self.parser.add_argument('--info', action="store_true", help="Show more info about when supplying a key.")
        self.parser.add_argument("ARGS", nargs="*", help="Positional arguments to dict.")

    def save(self):
        self._dict_manager.save()

    def paste(self, text, message):
        return self._bot.get_service("paste").paste(text, message)
    
    def add_new_pair(self, key, value, force=False, user=0, global_=True):
        if len(key) < int(self._config.get('dict','min_key_length',fallback=3)):
            return ValueError("Key length was shorter than the minimum key length {}.".format(self._config.get('dict','min_key_length',fallback=3)))
        if "\n" in key:
            return ValueError("Can't have a newline in the key.")

        if self._dict_manager.insert(key, value, force=force, user=user, global_=global_):
            self.save()
            return "Inserted keypair \"{key}: {value}\".".format(key=key,value=value)
        else:
            return ValueError('Key "{}" is already present in the dict. Use --force to overwrite it.'.format(key))
   
    def get(self, key, extra_info=False, user="", global_=True):
        if not self._dict_manager.exists(key, user=user, global_=global_):
            if self._dict_manager.size(user=user, global_=global_) == 0:
                return RuntimeError("No keys currently exist")
            
            options = similar.possibilities(key, list(self._dict_manager.keys(user=user, global_=global_)), use_random=True, subsets=True) 
            
            if global_:
                location = None
            else:
                location = user
            self._options[location] = options 
            
            if len(options) == 1:
                return KeyError('\n"{}" is the only key similar to what you looked after. Here is its contents:\n{}'.format(options[0], self.get(options[0], extra_info=extra_info, user=user, global_=global_))) 
  
            tmp = []
            for i in range(1, len(options) + 1):
                tmp.append('{}: "{}"'.format(i, options[i - 1]))

            return KeyError('\nCould not find key "{}". Could you have meant:\n{}?'.format(key, '; '.join(tmp)))
        
        data = self._dict_manager.get(key, user=user, global_=global_)

        if not extra_info:
            return data["value"]
        return "Key: {key}\nValue: {value}\nKey created by {insert_person} on {inserted}\nLatest update by {update_person} on {update}".format(key=key, value=data["value"], inserted=datetime.datetime.fromtimestamp(data["time_insert"]).strftime('%c'), insert_person=data["user_insert"], update=datetime.datetime.fromtimestamp(data["time_update"]).strftime('%c'), update_person=data["user_update"]) 


    def parse(self, message):
        try:
            args = self.parser.parse_args(shlex.split(message.get_text()))
        
        except ArgumentParserError as error:
            return ArgumentParserError("\n{}".format(error))
        
        user = message.get_alias()

        if args.help:
            return self.parser.format_help()
        
        if args.list:
            ans = ""
            for key, value in self._dict_manager.items():
                ans += "{}\n\t{}\n".format(key, value)
            if ans == "":
                return "No pairs are stored."
            return self.paste(ans, message)
        
        if args.pick:
            if args.global_:
                location = None
            else:
                location = user

            if len(self._options[location]) == 0:
                return RuntimeError('There are no options to pick at this moment.')
            if args.pick > len(self._options[location]) or args.pick < 1:
                return RuntimeError('You can only pick numbers between 1 and {}.'.format(len(self._options)))
            return self.paste(self.get(self._options[location][args.pick - 1], user=user, global_=args.global_, extra_info=args.info), message)
        
        if args.remove:
            key = args.remove.strip()
            if self._dict_manager.remove(key, user=user, global_=args.global_):
                
                self.save()
                return 'Value associated with key "{}" was removed.'.format(key)
            else:
                return 'Could not remove the key. Are you sure it is present?'

        if args.keys:
            return self.paste("\n".join(sorted(self._dict_manager.keys(user=user, global_=args.global_))), message)

        if args.size:
            size = self._dict_manager.size(user=user, global_=args.global_)
            if args.raw:
                return str(size)
            return 'There are {} keys at the moment.'.format(size)

        if (args.value or args.key):
            if not (args.value and args.key):
                return ValueError("Must supply both key and value")
            return self.add_new_pair(args.key, args.value, args.force, message)


        m = re.match(r"(.*[^\s]+)\s*:=\s*(.+)", " ".join(args.ARGS))
        if m:
            return self.add_new_pair(m.group(1), m.group(2), force=args.force, user=user, global_=args.global_)

        key = " ".join(args.ARGS)

        return self.paste(self.get(key, extra_info=args.info, user=user, global_=args.global_), message)
コード例 #10
0
ファイル: anidb.py プロジェクト: sork01/Jante_plugins
class AnidbPlugin(parsingplugintemplate):
    def __init__(self, bot):
        super(AnidbPlugin, self).__init__(bot,
                                          command="anidb",
                                          description="Searches anidb")
        self.parser = JanteParser(description='Searches anidb',
                                  prog='anidb',
                                  add_help=False)
        self.parser.add_argument('-h',
                                 '--help',
                                 action='store_true',
                                 required=False,
                                 help="Shows this helpful message.")
        self.parser.add_argument("words", nargs="*", help="The search words")

    def anidb(self, searchword):
        headers = {}
        headers[
            'User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
        query = urllib.parse.quote(searchword)
        url = "https://anidb.net/search/fulltext/?adb.search=" + query + "&do.search=1&entity.animetb=1&field.titles=1"
        req = urllib.request.Request(url, headers=headers)
        response = urllib.request.urlopen(req)
        html = response.read()
        soup = BeautifulSoup(html, 'html.parser')
        score = soup.find_all('td', {'class': 'score'})
        name = soup.find_all('td', {'class': 'relid'})
        link = re.findall(r'href="([^"]+)',
                          str(soup.find_all('td', {'class': 'relid'})))
        distance = 100
        count = 0
        index = 0
        for series in name:
            tmpdistance = self.levenshteinDistanceDP(series.text.lower(),
                                                     searchword.lower())
            if tmpdistance < distance:
                distance = tmpdistance
                index = count
            count += 1
        if len(link) == 0:
            message = ("No anime found (" + searchword + ")")
        else:
            descNImg = self.aniDescImg(link[index])
            if descNImg[0] == "Adult":
                message = "Adult content you f*****g hentai!"
            else:
                message = (name[index].text + ": Score: " + score[index].text +
                           "\n\n" + descNImg[0] + "\n\n" + descNImg[1])
        return message

    def aniDescImg(self, url):
        headers = {}
        headers[
            'User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
        url = ("https://anidb.net" + url)
        req = urllib.request.Request(url, headers=headers)
        response = urllib.request.urlopen(req)
        html = response.read()
        soup = BeautifulSoup(html, 'html.parser')
        adult = soup.find('h1', {'class': 'anime'}).text
        if adult == "Adult Content Warning":
            desc = "Adult"
            img = None
        else:
            desc = soup.find_all('div',
                                 {'class': 'g_bubble g_section desc resized'})
            if len(desc) == 0:
                desc = ""
                image = soup.find('img', alt=True)
                img = image["src"]
            else:
                desc = desc[0].text
                image = soup.find('img', alt=True)
                img = image["src"]

        return [desc, img]

    def levenshteinDistanceDP(self, token1, token2):
        distances = numpy.zeros((len(token1) + 1, len(token2) + 1))

        for t1 in range(len(token1) + 1):
            distances[t1][0] = t1

        for t2 in range(len(token2) + 1):
            distances[0][t2] = t2

        a = 0
        b = 0
        c = 0

        for t1 in range(1, len(token1) + 1):
            for t2 in range(1, len(token2) + 1):
                if (token1[t1 - 1] == token2[t2 - 1]):
                    distances[t1][t2] = distances[t1 - 1][t2 - 1]
                else:
                    a = distances[t1][t2 - 1]
                    b = distances[t1 - 1][t2]
                    c = distances[t1 - 1][t2 - 1]

                    if (a <= b and a <= c):
                        distances[t1][t2] = a + 1
                    elif (b <= a and b <= c):
                        distances[t1][t2] = b + 1
                    else:
                        distances[t1][t2] = c + 1
        return distances[len(token1)][len(token2)]

    def parse(self, message):

        try:
            args = self.parser.parse_args(message.getText().split(" "))
        except ArgumentParserError as error:
            return ArgumentParserError("\n{}".format(error))
        ans = " ".join(args.words)
        if args.help:
            return self.parser.format_help()
        else:
            return self.anidb(ans)
コード例 #11
0
class YoutubePlugin(parsingplugintemplate):
    def __init__(self, bot):
        super(YoutubePlugin, self).__init__(bot,
                                         command="youtube", description="Searches youtube")

        self.parser = JanteParser(description='Searches youtube', prog='youtube', add_help=False)
        self.parser.add_argument('-n', '--results', type=int, default=1, required=False,
                                 help="Amount of results from 1 to 20")
        self.parser.add_argument('-h', '--help', action='store_true', required=False,
                                 help="Shows this helpful message.")
        self.parser.add_argument('-r', '--random', action='store_true', required=False,
                                 help="Gives a random youtube link.")
        self.parser.add_argument('-s', '--streaming', action='store_true', required=False,
                                 help="Check if anyone is streaming.")
        self.parser.add_argument("words", nargs="*",
                                 help="The search words")


        
    def ytstreaming(self):
        url = ["https://www.youtube.com/channel/UCRU8PSSNf8n_68UZ1iXyr3A", "https://www.youtube.com/user/lurlurlur", "https://www.youtube.com/user/FxH1337", "https://www.youtube.com/channel/UCM9th0j-83uvnP8yfVkqEYw"] 
        message = ""
        for channel in url:
            req = urllib.request.Request(channel)
            req.add_header("Accept-Language", "en-US,en;q=0.5")
            response = urllib.request.urlopen(req)
            html = response.read()
            live = re.findall("(text\":\"LIVE)", str(html))
            if len(live) == 0:
                message += ""
                #print(channel + " is empty")
            else:
                if "68UZ1iXyr3A" in channel or "83uvnP8yfVkqEYw" in channel:
                    name = "Sork: "
                elif "FxH1337" in channel:
                    name = "Felix: "
                else:
                    name = "Lur: "
                link = re.findall("watch\?v=([A-Za-z0-9-_]*)", str(html))
                title = self.yt("https://www.youtube.com/watch?v=" + link[0])
                message += name + title + " https://www.youtube.com/watch?v=" + link[0] + "\n"
        if message == "":
            return "No one is streaming atm"
        else:
            return message

    def yt(self, yturl):
        url = yturl
        response = urllib.request.urlopen(url)
        html = response.read().decode('utf-8')
        soup = BeautifulSoup(html, 'html.parser')
        title = soup.find("meta",  {"name":"title"})
        title = title["content"]
        message = ""
        if len(title) == 0:
            message += ("There is no such video")
        else:
            message += str(title)

        return message

    def ytlink(self, searchword, N, random = False):
        query = urllib.parse.quote(searchword)
        url = "https://www.youtube.com/results?search_query=" + query
        response = urllib.request.urlopen(url)
        html = response.read()
        soup = BeautifulSoup(html, 'html.parser')
        ytlist = []
        i = 1
        video = re.findall(r'videoIds":\["([^"]+)', soup.text)
        #title = re.findall(r'title":{"runs":\[{"text":"([^"]+)', soup.text)
            #ytlist.append(str(youtuber) + ": " + vid['title'] + ' https://www.youtube.com' + vid['href'])
        ytlist.append(self.yt('https://www.youtube.com/watch?v=' + video[0]) + ' https://www.youtube.com/watch?v=' + video[0])
            #i = i + 1
        ytlist = ytlist[0:N]
        if random:
            message = "Searchword: " + searchword + "\n"
        else:
            message = ""
        for link in ytlist:
            message += link + '\n'
        message = message[:-1]
        if message == "":
            return "No match for searchword " + searchword
        else:
            return message

    def parse(self, message):

        try:
            args = self.parser.parse_args(message.getText().split(" "))
        except ArgumentParserError as error:
            return ArgumentParserError("\n{}".format(error))
        ans = " ".join(args.words)
        if args.help:
            return self.parser.format_help()
        if args.streaming:
            return self.ytstreaming()
        if args.results < 1 or args.results > 20:
            return (str(args.results) + " is not a valid result")
        if args.random:
            words = self._bot.getService("ngramkeeper").getDictionary()
            longwords = list(filter(lambda word: len(word) > 5, words))
            ans = random.choice(longwords)
            return self.ytlink(ans, args.results, True)
        else:
            return self.ytlink(ans, args.results)