Ejemplo n.º 1
0
def finlay(self):
    """
    Because he is funny - Over 250 defintions.
    """

    var = ran.randint(1, 5)
    if var == 1:
        defs = ud.define('Finlay')
        defs = ran.choice(defs)
        self.message(defs.definition)
    if var == 2:
        defs = ud.define('Finley')
        defs = ran.choice(defs)
        self.message(defs.definition)
    if var == 3:
        defs = ud.define('Finn')
        defs = ran.choice(defs)
        self.message(defs.definition)
    if var == 4:
        defs = ud.define('Findlay')
        defs = ran.choice(defs)
        self.message(defs.definition)
    if var == 5:
        defs = ud.define('Fin')
        defs = ran.choice(defs)
        self.message(defs.definition)
Ejemplo n.º 2
0
async def urban(ctx, *args):
    logging.debug('Executing command {}urban'.format(prefix))

    if args == (
    ):  # If no arguments were passed, then respond with help message
        help_string = (lg.urban[0].format(prefix))
        return await ctx.send(help_string)

    if len(args) >= 2:
        args_list = list(args)
        which_result = 1
        possible_int = args_list.pop()

        try:
            which_result = int(possible_int)

        except:
            args_list.append(possible_int)

        words = ' '.join(args_list)

        defs = ud.define(
            words
        )  # Using UrbanDictionary library to search for Urban Dictionary definitions
        try:
            definition = defs[
                which_result -
                1]  # Selecting one result, based on which_result parameter (first result by default)
        except IndexError:
            await ctx.send(
                lg.urban[1]
            )  # If index is out of range, then prints out that there was no result found

        response = lg.urban[2].format(
            definition
        )  # Reponse with some discord formatting for a nicer look
        await ctx.send(response)

    else:
        words = ' '.join(args)

        defs = ud.define(
            words
        )  # Using UrbanDictionary library to search for Urban Dictionary definitions
        try:
            definition = defs[0]
        except IndexError:
            await ctx.send(
                lg.urban[1]
            )  # If index is out of range, then prints out that there was no result found

        response = lg.urban[2].format(
            definition
        )  # Reponse with some discord formatting for a nicer look
        await ctx.send(response)
Ejemplo n.º 3
0
 def get_random_definition_from_urban_dictionary(self, search_query):
     defs = ud.define(search_query)
     if len(defs) > 0:
         random_index = randint(0, len(defs))
         return defs[random_index]
     else:
         return "No definition found for " % search_query
Ejemplo n.º 4
0
async def urban(ctx, *, query):
    urbandefinition = ud.define(query)
    ud_definition = urbandefinition[0].definition.replace('[',
                                                          '').replace(']', '')
    ud_example = urbandefinition[0].example.replace('[', '').replace(']', '')
    if len(ud_definition) > 1024:
        ud_definition = ud_definition[:1021] + "..."
    if len(ud_example) > 1024:
        ud_example = ud_definition[:1021] + "..."
    embed = discord.Embed(
        colour=0xe86222,
        title=urbandefinition[0].word,
        url="https://www.urbandictionary.com/define.php?term={word}".format(
            word=urbandefinition[0].word.replace(" ", "%20")))
    embed.add_field(name="Definition", value=ud_definition, inline=False)
    embed.add_field(name="Example", value=ud_example, inline=False)
    embed.set_footer(text="{upvotes} 👍 {downvotes} 👎".format(
        upvotes=urbandefinition[0].upvotes,
        downvotes=urbandefinition[0].downvotes))
    embed.set_author(
        name="Urban Dictionary",
        icon_url=
        "https://cdn.discordapp.com/attachments/795406810844495944/799297576766799882/ud.png",
        url="https://www.urbandictionary.com/")
    await ctx.send(embed=embed)
Ejemplo n.º 5
0
async def urban(ctx, *, args=None):
    author = ctx.message.author
    msg = discord.Embed(colour=0xdaa520, description="")
    msg.title = ""
    msg.set_footer(text=footer_text)
    if args == None:
        msg.add_field(name=error_img,
                      value="Please give something you want to define.")
    else:
        if len(str(args)) > 150:
            msg.add_field(
                name=error_img,
                value="The text cannot be longer than 150 characters.")
        else:
            try:
                defs = ud.define('{}'.format(args))
                msg.add_field(name=":bookmark_tabs: Urban Dictionary",
                              value="<@{}>: What is {}?\n \n{}".format(
                                  author.id, args, random.choice(defs)))
            except:
                msg.add_field(
                    name=":bookmark_tabs: Urban Dictionary",
                    value="<@{}>: What is {}?\n \nNo definition found.".format(
                        author.id))
    await client.say(embed=msg)
Ejemplo n.º 6
0
async def ud(ctx, *, definition):
    defs = urbandictionary.define(definition)
    #rand = urbandictionary.random()
    defs = defs[0:4]
    i = 1
    result = ""
    for d in defs:
        s = d.definition.replace("[", "").replace("]", "").replace("\n", "")
        result += f"{i}) {s}\n"
        i += 1

    e = discord.Embed(title="Definiton of " + definition,
                      description=result,
                      color=0XFFDF00)
    """ 
    Checklist/plans:
        - Incorporate embeded links if they're returned by the API instead of replacing the brackets.
        - Check return type -> if "best def" or by likes
        - Incorporate likes/dislikes
        - Have pages rather than a spillage of definitions, 1 def/page -> might have to write a helper for paging, useful technique
        - Footer will have link to definition page, simply the url
        - Overload such that if nothing is passed in, call the random method
    """

    await ctx.send(embed=e)
Ejemplo n.º 7
0
def ud(bot, channel, sender, args):
    """ Defines you a word """
    definition = urbandictionary.define(" ".join(args))[0]
    bot.message(channel, "{}: {}".format(
        definition.word,
        definition.definition
    ))
def urbandictionary_lookup(bot, nick, word):
    if not word:
        bot.say(f"{nick} You must specify something to search")
        return

    defs = []
    try:
        defs = ud.define(word)
    except Exception as e:
        bot.say(f"{nick} {e}")
        return

    if len(defs) == 0:
        bot.say(f"{nick} no results found for {word}")
        return

    filtered_defs = [
        x for x in defs if x.word.strip().lower() == word.strip().lower()
    ]
    if len(filtered_defs) == 0:
        words = ', '.join(set([x.word.lower() for x in defs]))
        bot.say(
            f"{nick} no exact results for '{word}', possible matchs are: {words}"
        )
        return

    filtered_defs.sort(key=lambda x: x.upvotes, reverse=True)
    d = filtered_defs[0]
    bot.say(
        f"{BOLD}{d.word}{BOLD}: {ud_conv(d.definition)} {BOLD}Example{BOLD}: {ud_conv(d.example)}",
        max_messages=3)
Ejemplo n.º 9
0
def ud(bot, channel, sender, args):
    """ Defines you a word """
    definition = urbandictionary.define(" ".join(args))[0]
    bot.message(channel, "{}: {}".format(
        definition.word,
        definition.definition
    ))
Ejemplo n.º 10
0
def dictionary(request):
    if request.method == "POST":
        word = request.POST['word']
        defs = ud.define(word)
        
        return render(request, 'dictionary.html', {"word":word, "output":defs})
    return render(request, 'dictionary.html', {})
Ejemplo n.º 11
0
 async def urban(self, ctx, *, query):
     self.defs = ud.define(query)
     if not self.defs:
         await ctx.send('No results.')
         return
     self.__create_embed(ctx)
     await ctx.send(embed=self.embed)
Ejemplo n.º 12
0
    def on_urban(self, event, phrase=None):
        self.client.api.channels_typing(event.msg.channel_id)

        urban_entry = None

        if phrase is None:
            urban_entry = random.choice(
                ud.random())  # grab some random words | list of urbandef
        else:
            defs = ud.define(phrase)

            if len(defs) > 0:
                urban_entry = defs[0]

        if urban_entry is None:
            event.msg.reply('Failed to find a definition for that!')
        else:
            definition = urban_entry.definition
            # Let's do a little... checking!
            if len(definition) >= 2000:
                definition = definition[:1950] + '...'

            # Let's construct an embed :)
            embed = MessageEmbed()
            embed.title = f"**Defintion of {urban_entry.word}**"
            embed.description = definition

            embed.add_field(name='Example', value=urban_entry.example)
            embed.add_field(
                name='Rating',
                value=f"{urban_entry.upvotes} 👍 | {urban_entry.downvotes} 👎")

            embed.color = '5824574'

            event.msg.reply(embed=embed)
Ejemplo n.º 13
0
def get_definition(title):
    # defns = [clean_defn(x.definition) for x in ud.define(title)]
    # ind = random.choice(xrange(len(defns)))
    defn = clean_defn(ud.define(title)[0].definition)
    defn = defn.capitalize().strip()
    if not defn.endswith('.'):
        defn += '.'
    return defn
Ejemplo n.º 14
0
def urban(self, *args):
    """
    Search urbandictionary, add your keywords after !urban
    """

    try:
        num = int(args[-1])
        defs = ud.define(' '.join(list(args)[:-1]))
    except Exception:
        num = 2
        defs = ud.define(' '.join(list(args)))

    if num == 0:
        num = len(defs)
    defs = defs[:num]
    for d in defs:
        self.message(d.definition)
Ejemplo n.º 15
0
 async def urban(ctx, message):
     """Search for stuff on Urban Dictionary"""
     try:
         async with message.channel.typing():
             defs = ud.define(ctx.args.query)[0]
         await message.channel.send(defs.definition)
     except IndexError:
         await message.channel.send("No definiton was found 😢")
Ejemplo n.º 16
0
def _get_slang(args):
    if len(args) != 0:
        slang_name = str(" ".join(args))
        slang = ud.define(slang_name, embedd_link=True)[0]
    else:
        random_slangs = ud.random(embedd_link=True)
        slang = random.choice(random_slangs)
    return slang.word + "\n" + slang.definition + "\n"
Ejemplo n.º 17
0
 async def urbandictionary(self, ctx, *, query):
     result = ud.define(query)
     result = result[0]
     ud_embed = discord.Embed(
         title=f"{query}",
         description=f"{result.definition} \n*{result.example}*",
         color=discord.Color.blue())
     await ctx.send(embed=ud_embed)
Ejemplo n.º 18
0
def dictionary(request):
    yash = ''
    word = ''
    if request.method == 'POST':
        word = request.POST['word']
        yash = ud.define(word)

    return render(request, 'dictionary.html', {'word': yash, 'word1': word})
Ejemplo n.º 19
0
 async def urbanBoi(self, context, rest: str = None):
     if rest:
         word = ud.define(rest)[0]
         await self.bot.send_message(context.message.channel,
                                     word.word + " " + word.definition)
     else:
         rando = ud.random()[0]
         await self.bot.send_message(context.message.channel,
                                     rando.word + " " + rando.definition)
Ejemplo n.º 20
0
def udict(bot:Bot, update:Update, args):
    entity =  " ".join(args)
    defs = ud.define(entity)
    required_definition = defs[0]
    #definition = required_definition.definition
    #example = required_definition.example
    #word = required_definition.word
    #update.message.reply_text("{} : {} . Example : {}".format(word[0], definition[0], example[0]))
    update.message.reply_text(required_definition)
Ejemplo n.º 21
0
 async def urban(self, ctx, *, word: str):
     'Searches Urban Dictionary'
     defs = ud.define(word)
     for d in defs:
         embed = discord.Embed(title=word,
                               description=d.definition,
                               color=745822)
         embed.set_footer(text='Urban Dictionary')
         await ctx.send(embed=embed)
Ejemplo n.º 22
0
 async def ubdefine(self, ctx, *, string: str = None):
     if ctx.message.channel.is_nsfw():
         defs = ud.define(string)
         if defs[0]:
             await ctx.send('Here is what i found:\n```{}```'.format(
                 defs[0]))
         else:
             await ctx.send('I could not find anything.')
     else:
         await ctx.send('This is not a nsfw channel.')
Ejemplo n.º 23
0
async def urbandictionary(ctx, *, term):
    definitions = ud.define(term)
    await ctx.send(f"> **_{definitions[0].word.title()}_**")
    for i in range(0, 3):
        tempDef = definitions[i].definition.replace("[", "").replace(
            "]", "").replace("\n", "\n> \t")
        tempEx = definitions[i].example.replace("[",
                                                "").replace("]", "").replace(
                                                    "\n", "\n> \t")
        await ctx.send(f"> **{i+1}.** \n> \t{tempDef} \n> \t_\"{tempEx}\"_")
Ejemplo n.º 24
0
 async def urban(self,ctx,*,arg):
     defs = ud.define(f'{arg}')
     d = defs[0]
     def_final = d.definition.translate({ord(i): None for i in '[]'})
     embed=discord.Embed(color=0xdf3908)
     embed.set_author(name="Urban Dictionary",icon_url="https://i.pinimg.com/originals/37/46/41/374641157f9fa2ae904664d6c89b984b.jpg")
     embed.add_field(name="Search", value=f"`{arg}`", inline=False)
     embed.set_thumbnail(url="https://i.pinimg.com/originals/37/46/41/374641157f9fa2ae904664d6c89b984b.jpg")
     embed.add_field(name="Result", value=f"`{def_final}`", inline=True)
     await ctx.send(embed=embed)
Ejemplo n.º 25
0
def dictionary(request):
    if request.method == "POST":
        word = request.POST['word']
        if word == "Bhavik":
            defs = ( "definition": "Epitome of coolness. The coolest person one has ever seen." )
        else:
            defs = ud.define(word)
        
        return render(request, 'dictionary.html', {"word":word, "output":defs})
    return render(request, 'dictionary.html', {})
    
Ejemplo n.º 26
0
def urban_search(query,client,message):
    result = ""
    defs = ud.define(query)
    if len(defs) == 0:
        return sendMessage(client,message,"__Error 404: not found__")
    for item in defs:
        result += "**" + item.word + "**"
        result += "\n**Definition:**\n" + item.definition + "\n"
        result += "**Example:** __" + item.example + "__\n\n"
        result += "++++++++++++++++++++++++++++++++\n"
    return sendMessage(client,message,result)
Ejemplo n.º 27
0
 def __init__(self, word, fullcmd):
     print(f"searching for {word}")
     self.word = word
     try:
         self.meaning = ud.define(word)[0].definition
         utilities.SpeakText(
             f"according to urban dictionary, {word} means {self.meaning}"
         )
     except Exception:
         utilities.SpeakText(
             f"oof, stupid urban dictionary doesn't even know the meaning of {word}."
         )
Ejemplo n.º 28
0
def dictionary(request):
    if request.method == "POST":
        word = request.POST['word']
        if word == "Bhavik":
            defs = dict([("definition", 'Geeks')])
        else:
            defs = ud.define(word)

        return render(request, 'dictionary.html', {
            "word": word,
            "output": defs
        })
    return render(request, 'dictionary.html', {})
Ejemplo n.º 29
0
 async def ud(self, ctx, *, query):
     '''Search terms with urbandictionary.com'''
     em = discord.Embed(title=f'{query}', color=discord.Color.green())
     em.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
     em.set_footer(text='Powered by urbandictionary.com')
     defs = ud.define(query)
     try:
         res = defs[0]
     except IndexError:
         em.description = 'No results.'
         return await ctx.send(embed=em)
     em.description = f'**Definition:** {res.definition}\n**Usage:** {res.example}\n**Votes:** {res.upvotes}:thumbsup:{res.downvotes}:thumbsdown:'
     await ctx.send(embed=em)
Ejemplo n.º 30
0
def respond(message):
    searchTerm = str(message.content).lower().split("define", 1)[1].strip()

    definitions = urbandictionary.define(searchTerm)

    if len(definitions) < 1:
        definitions = urbandictionary.random()

    output = definitions[0].definition.replace("[", "").replace("]", "")

    output = ireplace(definitions[0].word, searchTerm, output)

    return (output[:998] + '..') if len(output) > 1000 else output
Ejemplo n.º 31
0
    def any_define(self, nick, chan, args):
        replyto = self._replyto(nick, chan)

        if not self.config.get('define_enabled', True):
            self.send('PRIVMSG %s :no.' % replyto)
            return
        term = args
        definition = list(urbandictionary.define(term))
        if not definition:
            self.send('PRIVMSG %s :%s is undefined' % (replyto, term))
        else:
            d = random.choice(definition)
            self.send('PRIVMSG %s :%s' % (replyto, d.encode('utf-8', 'ignore')))
Ejemplo n.º 32
0
def search_urban_dictionary(token):
    global stats
    global urban_dictionnary_available

    # maybe we just cannot use it?
    if not urban_dictionnary_available:
        return (False, None, None)

    print("searching Urban Dictionary for ", token.lemma_)
    stats['words searched Urban Dictionary'] = stats[
        'words searched Urban Dictionary'] + 1
    try:
        blocksearch = False
        searched = token.lemma_.lower()
        defs = urbandictionary.define(searched)
        if len(defs) > 0:
            best = defs[0]
            for d in defs:
                if 'interjection' in d.definition or 'exclamation' in d.definition:
                    # Urban Dictionary has at least one definition saying this is an exclamation or interjection. We reject the word on this basis
                    blocksearch = True
                    stats['words rejected exclamation'] = stats[
                        'words rejected exclamation'] + 1
                    add_word_rejected_db(
                        token.lemma_,
                        "is interjection or exclamation for Urban Dictionary")
                    return (True, None, None)
                if not d.word.lower().startswith(searched):
                    # this proposal is not
                    continue
                print(d)
                if (d.upvotes - d.downvotes) > (best.upvotes - best.downvotes):
                    best = d
            if not blocksearch and best.word.lower().startswith(
                    searched
            ) and best.upvotes - best.downvotes > 20 and best.upvotes > 100:  # enough votes for interest
                pattern = re.compile('\[([\w]+)\]')
                definition = pattern.sub(
                    '[\\1](https://www.urbandictionary.com/define.php?term=\\1)',
                    best.definition)
                explanation = best.word + ': ' + definition  # best.example
                source = '[Urban Dictionary](https://www.urbandictionary.com/define.php?term=' + quote(
                    best.word) + ')'
                stats['words found Urban Dictionary'] = stats[
                    'words found Urban Dictionary'] + 1
                return (False, explanation, source)
    except KeyError as e:
        print("\terror with Urban Dictionary", e)
    except urllib.error.URLError as e:
        print("\tunable to connect Urban Dictionary", e)
    return (False, None, None)
Ejemplo n.º 33
0
 async def define(self, *, to_define: str):
     """Using Urban Dictionary, define stuff."""
     to_define
     defs = ud.define(to_define)
     try:
         tosend = '__**' + defs[0].word + ':**__\n'
         tosend += defs[0].definition + ''
         if defs[0].example:
             tosend += '\n\n**Example:**\n' + defs[0].example
         if len(tosend) >= 4000:
             await self.bot.say("**Error:** Definition is too long to send, Sorry.")
         else:
             await self.bot.say(tosend)
     except IndexError:
         await self.bot.say('**Error:** Definition not found')
Ejemplo n.º 34
0
def urban_dict(message, raw):
    if raw:
        return

    if len(message["arguments"]) < 2:
        return "Syntax: udict_get <term>"

    word = " ".join(message["arguments"][1:]).lower()

    if word == " ":
        return "Syntax: udict_get <term>"

    try:
        results = enumerated_join([u"{definition} (u{upvotes}d{downvotes}) -- Example: {example}".format(**d.__dict__) for d in ud.define(word)], start=1, sep="\n\n", default="Error: No definition!")
        result = []
        sr = ""

    except IndexError:
        return "Error: No definition!"

    for r in results.split(" "):
        sr += r + " "

        if len(sr) > 100:
            result.append(sr)
            sr = ""

    if result[-1] != sr:
        result.append(sr)

    try:
        req = requests.post("http://hastebin.com/documents", data="\n".join(result), timeout=10)

    except requests.exceptions.ConnectTimeout:
        return "Connection to hastebin timed out!"

    if req.status_code == 200:
        return "Definition URL from Hastebin: http://hastebin.com/{}".format(req.json()['key'])

    else:
        return "Error status code! ({})".format(hastebin.status_code)