Add 'UrbanDictionary/' from commit '4a9829583291a692fc8e33adeb666fd8d2fff793'

git-subtree-dir: UrbanDictionary
git-subtree-mainline: cd5e994b940625ceea7f5e2a510452f7b7df2a35
git-subtree-split: 4a9829583291a692fc8e33adeb666fd8d2fff793
This commit is contained in:
oddluck 2019-07-14 18:44:27 -04:00
commit d66a75ecdf
10 changed files with 363 additions and 0 deletions

27
UrbanDictionary/.gitignore vendored Normal file
View File

@ -0,0 +1,27 @@
*.py[co]
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
#Translations
*.mo
#Mr Developer
.mr.developer.cfg

View File

@ -0,0 +1,23 @@
language: python
python:
- "2.7"
- "3.4"
- pypy
# command to install dependencies,
install:
- pip install -vr requirements.txt||true
# command to run tests, e.g. python setup.py test
script:
- echo $TRAVIS_PYTHON_VERSION
- cd .. && supybot-test UrbanDictionary
notifications:
email: false
irc:
channels:
- "irc.efnet.net#supybot"
template:
- "Build #%{build_number}: %{repository} %{branch} (%{commit}) %{author} - %{message}"
- "Build details: \x03 %{build_url}"
matrix:
fast_finish: true

View File

@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2014 spline
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

45
UrbanDictionary/README.md Normal file
View File

@ -0,0 +1,45 @@
[![Build Status](https://travis-ci.org/reticulatingspline/UrbanDictionary.svg?branch=master)](https://travis-ci.org/reticulatingspline/UrbanDictionary)
# Limnoria plugin for UrbanDictionary
## Introduction
Limnoria plugin for querying [UrbanDictionary](http://www.urbandictionary.com)
## Install
You will need a working Limnoria bot on Python 2.7 for this to work.
Go into your Limnoria plugin dir, usually ~/supybot/plugins and run:
```
git clone https://github.com/reticulatingspline/UrbanDictionary
```
To install additional requirements, run:
```
pip install -r requirements.txt
```
Next, load the plugin:
```
/msg bot load UrbanDictionary
```
## Example Usage
```
<spline> @ud spline
<myybot> spline :: The object which Maxis likes to reticulate. [ex:] 1: "What are you reticulating, dude?"2: "My favorite dish-- Splines!" [/ex]
```
## About
All of my plugins are free and open source. When I first started out, one of the main reasons I was
able to learn was due to other code out there. If you find a bug or would like an improvement, feel
free to give me a message on IRC or fork and submit a pull request. Many hours do go into each plugin,
so, if you're feeling generous, I do accept donations via Amazon or browse my [wish list](http://amzn.com/w/380JKXY7P5IKE).
I'm always looking for work, so if you are in need of a custom feature, plugin or something bigger, contact me via GitHub or IRC.

View File

@ -0,0 +1,43 @@
###
# Copyright (c) 2012-2013, spline
# All rights reserved.
#
#
###
"""
Add a description of the plugin (to be presented to the user inside the wizard)
here. This should describe *what* the plugin does.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
__version__ = ""
# XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.authors.unknown
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
# This is a url where the most recent plugin package can be downloaded.
__url__ = ''
from . import config
from . import plugin
from imp import reload
reload(plugin) # In case we're being reloaded.
# Add more reloads here if you add third-party modules and want them to be
# reloaded when this plugin is reloaded. Don't forget to import them as well!
if world.testing:
from . import test
Class = plugin.Class
configure = config.configure
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:

27
UrbanDictionary/config.py Normal file
View File

@ -0,0 +1,27 @@
###
# Copyright (c) 2012-2013, spline
# All rights reserved.
#
#
###
import supybot.conf as conf
import supybot.registry as registry
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('UrbanDictionary')
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified himself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('UrbanDictionary', True)
UrbanDictionary = conf.registerPlugin('UrbanDictionary')
conf.registerChannelValue(UrbanDictionary, 'maxNumberOfDefinitions', registry.Integer(10, """Number of definition and examples in output. Max 10."""))
conf.registerChannelValue(UrbanDictionary, 'disableANSI', registry.Boolean(False, """Do not display any ANSI formatting codes in output."""))
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=250:

View File

@ -0,0 +1 @@
# Stub so local is a module, used for third-party modules

158
UrbanDictionary/plugin.py Normal file
View File

@ -0,0 +1,158 @@
# -*- coding: utf-8 -*-
###
# Copyright (c) 2012-2013, spline
# All rights reserved.
#
#
###
from __future__ import unicode_literals
# my libs
import json
import re
# supybot libs
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('UrbanDictionary')
@internationalizeDocstring
class UrbanDictionary(callbacks.Plugin):
"""Add the help for "@plugin help UrbanDictionary" here
This should describe *how* to use this plugin."""
threaded = True
######################
# INTERNAL FUNCTIONS #
######################
def _red(self, string):
"""return a red string."""
return ircutils.mircColor(string, 'red')
def _bu(self, string):
"""bold and underline string."""
return ircutils.bold(ircutils.underline(string))
def cleanjson(self, s):
"""clean up json and return."""
s = s.replace('\n', '')
s = s.replace('\r', '')
s = s.replace('\t', '')
s = s.strip()
# return
return s
####################
# PUBLIC FUNCTIONS #
####################
def urbandictionary(self, irc, msg, args, optlist, optterm):
"""[--disableexamples | --showvotes | --num # | --showtags] <term>
Fetches definition for <term> on UrbanDictionary.com
Use --disableexamples to not display examples.
Use --showvotes to show votes [default: off]
Use --num # to limit the number of definitions. [default:10]
Use --showtags to display tags (if available)
"""
# default args for output. can manip via --getopts.
args = {'showExamples': True,
'numberOfDefinitions':self.registryValue('maxNumberOfDefinitions'),
'showVotes': False,
'showTags':False
}
# optlist to change args.
if optlist:
for (key, value) in optlist:
if key == 'disableexamples':
args['showExamples'] = False
if key == 'showvotes':
args['showVotes'] = True
if key == 'showtags':
args['showTags'] = True
if key == 'num': # if number is >, default to config var.
if 0 <= value <= self.registryValue('maxNumberOfDefinitions'):
args['numberOfDefinitions'] = value
# build and fetch url.
url = 'http://api.urbandictionary.com/v0/define?term=%s' % utils.web.urlquote(optterm)
try:
html = utils.web.getUrl(url)
except utils.web.Error as e:
self.log.error("ERROR opening {0} message: {1}".format(url, e))
irc.reply("ERROR: could not open {0} message: {1}".format(url, e))
return
# try parsing json.
#irc.reply("{0}".format(self._repairjson(html.decode('utf-8'))))
try:
#jsondata = self._repairjson(html.decode('utf-8')) # decode utf-8. fix \r\n that ud puts in below.
jsondata = html.decode('utf-8')
jsondata = json.loads(jsondata) # odds chars in UD.
except Exception as e:
self.log.error("Error parsing JSON from UD: {0}".format(e))
irc.reply("ERROR: Failed to parse json data. Check logs for error")
return
# process json.
results = jsondata.get('result_type') # exact, no_results, fulltext .
if not results:
# assume exact i guess...
results = 'exact'
definitions = jsondata.get('list')
# prep output now depending on results.
if results == "exact": # we did not find anything.
outdefs = []
for i in definitions[0:args['numberOfDefinitions']]: # iterate through each def.
# clean these up.
definition = self.cleanjson(''.join(i['definition'])) #.encode('utf-8')
example = self.cleanjson(''.join(i['example']))
# now add
outputstring = "{0}".format(definition) # default string.
if args['showExamples']: # show examples?
outputstring += " {0} {1} {2}".format(self._bu("[ex:]"), example, self._bu("[/ex]"))
if args['showVotes']: # show votes?
outputstring += " (+{0}/-{1})".format(i['thumbs_up'], i['thumbs_down'])
outdefs.append(outputstring) # add to our list.
output = " | ".join([item for item in outdefs]) # create string with everything.
elif results == "fulltext": # not direct. yields related terms.
output = " | ".join(sorted(set([item['word'] for item in definitions]))) # sorted, unique words.
# output time.
if results == "no_results" or len(definitions) == 0: # NOTHING FOUND.
irc.reply("ERROR: '{0}' not defined on UrbanDictionary.".format(optterm))
return
else: # we have definitions, so we're gonna output.
# check if we should add tags.
if args['showTags']: # display tags.
tags = jsondata.get('tags')
if tags: # we have tags. add it to optterm.
tags = " | ".join([i for i in tags])
else:
tags = False
else:
tags = False
# now lets output.
if self.registryValue('disableANSI'): # disable formatting.
if tags:
irc.reply("{0} :: {1} :: {2}".format(optterm, tags, ircutils.stripFormatting(output)))
else:
irc.reply("{0} :: {1}".format(optterm, ircutils.stripFormatting(output)))
else: # colors.
if tags:
irc.reply("{0} :: {1} :: {2}".format(self._red(optterm), tags, output))
else:
irc.reply("{0} :: {1}".format(self._red(optterm), output))
urbandictionary = wrap(urbandictionary, [getopts({'showtags':'',
'showvotes':'',
'num':('int'),
'disableexamples':''}), ('text')])
Class = UrbanDictionary
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=250:

View File

@ -0,0 +1 @@
git+https://github.com/ProgVal/Limnoria.git

18
UrbanDictionary/test.py Normal file
View File

@ -0,0 +1,18 @@
###
# Copyright (c) 2012-2014, spline
# All rights reserved.
#
#
###
from supybot.test import *
class UrbanDictionaryTestCase(PluginTestCase):
plugins = ('UrbanDictionary',)
def testUrbanDictionary(self):
conf.supybot.plugins.UrbanDictionary.disableANSI.setValue('True')
self.assertRegexp('urbandictionary hello', 'hello ::')
self.assertRegexp('urbandictionary spline', 'spline ::')
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: