Example #1
0
def cmd_lookup(message):
    """
    **!lookup**

    Usage:
      !lookup <term>

    Example:
      !lookup ironically

    Looks up the term on Merriam-Webster's online dictionary.
    And by Merriam-Webster, we do mean Urban Dictionary.
    """
    word = message.content[len("!lookup "):].strip()
    if not word:
        return

    response = ""
    entry = urbandict.define(word)[0]

    if "There aren't any definitions for " in entry["def"]:
        return

    response = "**" + entry["word"].strip() + "**\n"
    response += entry["def"].strip() + "\n"
    if entry["example"].strip() != "":
        response += "*" + entry["example"].strip() + "*"

    # TODO: Need to make sure we're not sending unicode that the API can't handle here
    if response:
        try:
            client.send_message(message.channel, response.encode('utf-8'))
        except:
            print "Unicode error in !lookup()"
    return
Example #2
0
    def check(self,message): # Scans message for commands
        msg = message.content

        if msg.startswith("!def "):
            print("Urbandictionary module called!")
            query = msg.replace("!def ","")

            # The following part is important to allow specification of the
            # number of fetched definitions
            query = query.split()
            try:
                if len(query)>1:
                    number = int(query[len(query)-1])
                    if number > 5:
                        number = 5
                    del query[len(query)-1]
                else:
                    number = 1
            except:
                print ("Could not convert to int")
                number = 1
            query = " ".join(query)

            result = urbandict.define(query)
            if number>len(result): # Limit results by availability
                number=len(result)

            for i in range(number):
                title = " ".join(result[i]['word'].replace("\n","").split())
                definition = " ".join(result[i]['def'].replace("\n","").split())
                example = " ".join(result[i]['example'].replace("\n","").split())

                self.dclient.send_message(message.channel,"**"+title+"**")
                self.dclient.send_message(message.channel, definition)
                self.dclient.send_message(message.channel,"*"+example+"*")
Example #3
0
 def define(*args):
     definition = urbandict.define(' '.join(args[0]))[0]
     return "### {} \n **Definition**: {} \n **Example**: _{}_".format(
             definition['word'],
             definition['def'],
             definition['example']
     )
Example #4
0
def urbandefine():
	word = userword.get()
	data = urbandict.define(word)
	word = data[index]['word']
	definition =  data[index]['def']
	example = data[index]['example']	
	labelText.set(definition) 
	widgetLabelResult.pack()
Example #5
0
def urban_response(message, term):
    if is_approved(message, "any"):
        terms = urbandict.define(term)
        for x in terms:
            if x['example'] == '' and len(terms) == 1:
                message.send("No definitions found for %s" % term)
                break
            temp = "Definition: %s Examples: %s" % (x['def'], x['example'])
            message.upload_snippet(temp, x['word'].strip("\n "))
Example #6
0
    def test_define_word(self, urlopen_mock, urlquote_mock):
        test_data = open('fixtures/test_data.html')
        urlopen_mock.return_value = test_data
        urlquote_mock.return_value = "xterm"

        ret = urbandict.define("xterm")
        urlopen_mock.assert_called_once()
        urlquote_mock.assert_called_once_with("xterm")
        self.assertTrue(isinstance(ret, list))
        self.assertEqual(len(ret), 1)
        self.assertEqual(ret[0]['word'].strip(), 'xterm')
        self.assertTrue('def' in ret[0] and 'example' in ret[0])
Example #7
0
    def test_define_random(self, urlopen_mock, urlquote_mock):
        test_data = open('fixtures/test_data.html')
        urlopen_mock.return_value = test_data
        urlquote_mock.return_value = "xterm"

        ret = urbandict.define(urbandict.TermTypeRandom())
        # as we don't pass any specific data, there's nothing
        # to quote
        urlquote_mock.assert_not_called()
        urlopen_mock.assert_called_once()
        self.assertTrue(isinstance(ret, list))
        self.assertEqual(len(ret), 1)
Example #8
0
def lookup_urbandictionary(word):
    """Look up word definition on urbandictionary.com.

    Returns None if no definition found.
    """
    res = ud.define(word)
    assert res  # res is never empty, even when no definition is found

    if urbandictionary_has_definition(res[0]):
        return res[0]['def']

    return None
Example #9
0
        def ud(term, count):
            lent = []
            jatx = []
            dict1 = urbandict.define(term)
            if count > len(dict1):
                return("Less results pl0x kk")
            else:
                for x in range(0, count, 1):
                    for i in dict1[x].keys():
                        if not(i.startswith("word")):
                            jatx.append("\x02"+i.upper()+"\x02 : "+dict1[x][i])

            return jatx
Example #10
0
async def urban(bot, msg, reg):
    x = reg.group('word')
    try:
        res = urbandict.define(x)
        res = res[0]
        em = Embed(title=x.title(),
                   description=strutils.escape_markdown(res['def']),
                   colour=miscutils.colours['orange'])
        if res['example']:
            em.add_field(name='Example', value=res['example'])
        await msgutils.send_embed(bot, msg, em)
    except Exception:
        await msg.channel.send(
            'Could not find `{}` in the urban dictionary. Make sure the phrase is spelled correctly.'
            .format(x))
Example #11
0
async def ud(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        await e.edit("Processing...")
        str = e.pattern_match.group(1)
        mean = urbandict.define(str)
        if len(mean) >= 0:
            await e.edit("Text: **" + str + "**\n\nMeaning: **" +
                         mean[0]["def"] + "**\n\n" + "Example: \n__" +
                         mean[0]["example"] + "__")
            if LOGGER:
                await e.client.send_message(
                    LOGGER_GROUP,
                    "ud query " + str + " executed successfully.")
        else:
            await e.edit("No result found for **" + str + "**")
Example #12
0
async def _(event):
    if event.fwd_from:
        return
    await event.edit("processing...")
    str = event.pattern_match.group(1)
    try:
        mean = urbandict.define(str)
        if len(mean) > 0:
            await event.edit("Text: **" + str + "**\n\nMeaning: **" +
                             mean[0]["def"] + "**\n\n" + "Example: \n__" +
                             mean[0]["example"] + "__")
        else:
            await event.edit("No result found for **" + str + "**")
    except:
        await event.edit("No result found for **" + str + "**")
Example #13
0
async def _(event):
    if event.fwd_from:
        return
    await event.edit("processing...")
    str = event.pattern_match.group(1)
    try:
        mean = urbandict.define(str)
        if len(mean) > 0:
            await event.edit('Text: **' + str + '**\n\nMeaning: **' +
                             mean[0]['def'] + '**\n\n' + 'Example: \n__' +
                             mean[0]['example'] + '__')
        else:
            await event.edit("No result found for **" + str + "**")
    except:
        await event.edit("No result found for **" + str + "**")
Example #14
0
async def urban_dict(ud_e):
    """ For .ud command, fetch content from Urban Dictionary. """
    await ud_e.edit("Processing...")
    query = ud_e.pattern_match.group(1)
    try:
        define(query)
    except HTTPError:
        return await ud_e.edit(f"Sorry, couldn't find any results for: {query}"
                               )
    mean = define(query)
    deflen = sum(len(i) for i in mean[0]["def"])
    exalen = sum(len(i) for i in mean[0]["example"])
    meanlen = deflen + exalen
    if int(meanlen) >= 0:
        if int(meanlen) >= 4096:
            await ud_e.edit("`Output too large, sending as file.`")
            file = open("output.txt", "w+")
            file.write("Text: " + query + "\n\nMeaning: " + mean[0]["def"] +
                       "\n\n" + "Example: \n" + mean[0]["example"])
            file.close()
            await ud_e.client.send_file(
                ud_e.chat_id,
                "output.txt",
                caption="`Output was too large, sent it as a file.`")
            if os.path.exists("output.txt"):
                os.remove("output.txt")
            return await ud_e.delete()
        await ud_e.edit("Text: **" + query + "**\n\nMeaning: **" +
                        mean[0]["def"] + "**\n\n" + "Example: \n__" +
                        mean[0]["example"] + "__")
        if BOTLOG:
            await ud_e.client.send_message(
                BOTLOG_CHATID,
                "ud query `" + query + "` executed successfully.")
    else:
        await ud_e.edit("No result found for **" + query + "**")
Example #15
0
async def urban_dictionary(client, message):
    if len(message.text.split()) == 1:
        message.edit("Usage: `ud example`")
        return
    text = message.text.split(None, 1)[1]
    mean = urbandict.define(text)
    if len(mean) >= 0:
        teks = "**Result of {}**\n\n**{}**\n**Meaning:**\n`{}`\n\n**Example:**\n`{}`".format(
            text, mean[0]["word"].replace("unknown", ""), mean[0]["def"],
            mean[0]["example"])
        await client.edit_message_text(message.chat.id, message.message_id,
                                       teks)
    else:
        await client.edit_message_text(message.chat.id, message.message_id,
                                       "Result not found!")
Example #16
0
async def urban_dict(ud_e):
    await ud_e.edit("Processing...")
    query = ud_e.pattern_match.group(1)
    try:
        define(query)
    except HTTPError:
        return await ud_e.edit(
            f"Maaf, tidak dapat menemukan hasil apa pun untuk: {query}")
    mean = define(query)
    deflen = sum(len(i) for i in mean[0]["def"])
    exalen = sum(len(i) for i in mean[0]["example"])
    meanlen = deflen + exalen
    if int(meanlen) >= 0:
        if int(meanlen) >= 4096:
            await ud_e.edit("`Output too large, sending as file.`")
            file = open("output.txt", "w+")
            file.write("Text: " + query + "\n\nMeaning: " + mean[0]["def"] +
                       "\n\n" + "Example: \n" + mean[0]["example"])
            file.close()
            await ud_e.client.send_file(
                ud_e.chat_id,
                "output.txt",
                caption="`Output was too large, sent it as a file.`",
            )
            if os.path.exists("output.txt"):
                os.remove("output.txt")
            return await ud_e.delete()
        await ud_e.edit("Text: **" + query + "**\n\nMeaning: **" +
                        mean[0]["def"] + "**\n\n" + "Example: \n__" +
                        mean[0]["example"] + "__")
        if BOTLOG:
            await ud_e.client.send_message(
                BOTLOG_CHATID,
                "ud query `" + query + "` executed successfully.")
    else:
        await ud_e.edit("Tidak ada hasil untuk **" + query + "**")
async def _(event):
    if event.fwd_from:
        return
    str = event.pattern_match.group(1)
    await event.edit(f"Searching UrbanDictionary for ```{str}```..")
    try:
        mean = urbandict.define(str)
        if len(mean) > 0:
            await event.edit('Text: **' + str + '**\n\nMeaning: **' +
                             mean[0]['def'] + '**\n\n' + 'Example: \n__' +
                             mean[0]['example'] + '__')
        else:
            await event.edit("No result found for **" + str + "**")
    except:
        await event.edit("No result found for **" + str + "**")
Example #18
0
async def urban_dict(ud_e):
    await ud_e.edit("Hazırlanır...")
    query = ud_e.pattern_match.group(1)
    try:
        define(query)
    except HTTPError:
        await ud_e.edit(f"Bağışlayın, {query} axtardım və heç bir məlumat tapmadım.")
        return
    mean = define(query)
    deflen = sum(len(i) for i in mean[0]["def"])
    exalen = sum(len(i) for i in mean[0]["example"])
    meanlen = deflen + exalen
    if int(meanlen) >= 0:
        if int(meanlen) >= 4096:
            await ud_e.edit("`Problem çox uzun olduğu üçün fayl kimi göndərirəm...`")
            file = open("urbandictionary.txt", "w+")
            file.write("Sual: " + query + "\n\nCavabı: " + mean[0]["def"] +
                       "\n\n" + "Nümunə: \n" + mean[0]["example"])
            file.close()
            await ud_e.client.send_file(
                ud_e.chat_id,
                "urbandictionary.txt",
                caption="`Problem çox uzun olduöu üçün fayl kimi göndərirəm...`")
            if os.path.exists("urbandictionary.txt"):
                os.remove("urbandictionary.txt")
            await ud_e.delete()
            return
        await ud_e.edit("Sual: **" + query + "**\n\nCavabı: **" +
                        mean[0]["def"] + "**\n\n" + "Nümunə: \n__" +
                        mean[0]["example"] + "__")
        if BOTLOG:
            await ud_e.client.send_message(
                BOTLOG_CHATID,
                query + "`UrbanDictionary sorğusu uğurla yerinə yetirildi!`")
    else:
        await ud_e.edit(query + "**üçün heç bir məlumat tapılmadı**")
Example #19
0
async def _(event):
    if event.fwd_from:
        return
    await event.edit("processing...")
    str = event.pattern_match.group(1)
    try:
        mean = urbandict.define(str)
        if len(mean) > 0:
            await event.edit('**Text: ' + str + '**\n\n**Meaning:** `' +
                             mean[0]['def'] + '`\n\n' + '**Example:** \n`' +
                             mean[0]['example'] + '`')
        else:
            await event.edit("**No result found for** `" + str + "`")
    except:
        await event.edit("**No result found for** `" + str + "`")
Example #20
0
def urban(msg):
    if msg.get('text'):
        if msg['text'].startswith('/u') or msg['text'].startswith('!u'):
            str = msg['text'][3:]
            if str == '':
                bot.sendMessage(msg['chat']['id'], '*Use:* `/u or !u <search query>`',
                                parse_mode='Markdown',
                                reply_to_message_id=msg['message_id'])
            else:
                sents = bot.sendMessage(msg['chat']['id'], '*Performing dictionary query..... 🔁*', 'Markdown', reply_to_message_id=msg['message_id'])[
                'message_id']
                mean = urbandict.define(str)
                try:
                    return bot.editMessageText((msg['chat']['id'], sents), 'Text: **'+str+'**\n\nMeaning: **'+mean[0]['def']+'**\n\n'+'Example: \n__'+mean[0]['example']+'__', 'Markdown', disable_web_page_preview=True)
                except Exception as error:
                    return bot.editMessageText((msg['chat']['id'], sents), "Can't find *{str}* in the dictionary", parse_mode="Markdown", disable_web_page_preview=True)
Example #21
0
    async def urbancmd(self, message):
        """Define word meaning. Usage:
            .urban <word(s)>"""

        args = utils.get_args_raw(message)

        if not args:
            return await utils.answer(message, _("<b>Provide a word(s) to define.</b>"))

        try:
            definition = define(args)
        except HTTPError:
            return await utils.answer(message, _("<b>Couldn't find definition for that.</b>"))

        await utils.answer(message, _("<b>Text</b>: <code>{}</code>\n<b>Meaning</b>: <code>{}\n<b>Example</b>: "
                                      + "<code>{}</code>").format(args, definition[0]['def'], definition[0]['example']))
Example #22
0
 def run(self):
     while 1: 
         msg=self.queue_in.get() # get() is blocking
         chat_id=msg.get_chat_id()
         if msg.get_text().lower()[:len("/ud")]=="/ud" and len(msg.get_text().split(" "))>=2:
             term=msg.get_text().split(" ",1)[1]
             term_ud=ud.define(term)
             def_ud=term_ud[0]["def"]
             def_ex=""
             if def_ud.find("There aren't any definitions")==-1:  #there is a def
                 reply=def_ud.strip("\n\r ")
                 if self.output_example:
                     reply+="\nExample: %s"%def_ex
             else: 
                 reply="No definition found."
             self.bot.sendMessage(chat_id,reply)
Example #23
0
async def ud(event):

  await event.edit("Processing...")

  str = event.pattern_match.group(1)

  mean = urbandict.define(str)

  if len(mean) >= 0:

    await event.edit('Text: **'+str+'**\n\nMeaning: **'+mean[0]['def']+'**\n\n'+'Example: \n__'+mean[0]['example']+'__')

    await client.send_message(-1001162835202,"ud query "+str+"executed successfully.")

  else:

    await event.edit("No result found for **"+str+"**")
Example #24
0
def udict(query):
    print(query)
    try:
        mean = urbandict.define(query)
        #print(mean)
    except HTTPError:
        return f"Sorry, couldn't find any results for: `{query}``"
    output = ''
    limit = 2
    for i, mean_ in enumerate(mean, start=1):
        output += f"{i}. **{mean_['def']}**\n" + \
            f"  Examples:\n  * `{mean_['example'] or 'not found'}`\n\n"
    #print(output)
    if not output:
        return f"No result found for **{query}**"
    output = f"**Results**\n\n\n{output}"
    return output
Example #25
0
def urban(client, message):
    if len(message.command) > 1:
        word = str(message.text)[6:].lstrip()
        try:
            mean = ud.define(word)
        except:
            client.send_message(message.chat.id,
                                urban_not_found_text.format(word))
        else:
            if len(mean) >= 0:
                client.send_message(
                    message.chat.id,
                    urban_text.format(word, mean[0]['def'],
                                      mean[0]['example']))
            else:
                client.send_message(message.chat.id,
                                    urban_not_found_text.format(word))
Example #26
0
 def run(self):
     while 1:
         msg = self.queue_in.get()  # get() is blocking
         chat_id = msg.get_chat_id()
         if msg.get_text()[:len("/ud")] == "/ud" and len(
                 msg.get_text().split(" ")) >= 2:
             term = msg.get_text().split(" ", 1)[1]
             term_ud = ud.define(term)
             def_ud = term_ud[0]["def"]
             def_ex = ""
             if def_ud.find(
                     "There aren't any definitions") == -1:  #there is a def
                 reply = def_ud.strip("\n\r ")
                 if self.output_example:
                     reply += "\nExample: %s" % def_ex
             else:
                 reply = "No definition found."
             self.bot.sendMessage(chat_id, reply)
    async def urban(self, ctx, *, word):
        api = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"

        querymsg = {'term':word} #term is the word that needs to be searched. in our case, *word*, the param

        headers = {
            'x-rapidapi-key': os.environ.get('urban_dict_key'), #get your own key from rapidapi for free and paste it here instead of the whole os.environ thingy
            'x-rapidapi-host': 'mashape-community-urban-dictionary.p.rapidapi.com'
        }

        response = requests.request('GET', api, headers=headers, params=querymsg)
        response = response.json() #This will be a very big dictionary, we need to 'decorate' it

        try:
            definition = response['list'][0]['definition'] #You can print the response to get an idea of why I did this
            example = response['list'][0]['example']

            for bracket in str(definition):
                if bracket == '[' or bracket == ']':
                    definition = definition.replace(bracket,'')

            for other_bracket in str(example):
                if other_bracket == '[' or other_bracket == ']':
                    example = example.replace(other_bracket, '')

            em = discord.Embed(title=word, color=random.choice(hex_colors.colors))
            em.add_field(name='Top definition:', value=definition, inline=False)
            em.add_field(name='Example:', value=example)

            await ctx.send(embed=em)
        except:
            try:
                raw_dict = urbandict.define(word) #returns a dictionary
                defintion = raw_dict[0]['def']
                example = raw_dict[0][str('example')]

                em = discord.Embed(name=word, color=random.choice(hex_colors.colors))
                em.add_field(name='Top definition:', value=defintion, inline=False)
                em.add_field(name='Example:', value=example)
                em.set_footer(text="I couldn't find the defintion using the primary API, so this might not be very accurate")

                await ctx.send(embed=em)
            except:
                await ctx.send("I couldn't find the defintion because both the API and the library are broken")
Example #28
0
def urbandefine():
	#Store the word in a variable
	word = userword.get()

	#Use Urban Dict API to grab dictionary data
	data = urbandict.define(word)

	#Store data for each word depending on user word
	word = data[index]['word']
	definition =  data[index]['def']
	example = data[index]['example']	

	#Set the DEFINITION widget
	labelText.set(definition) 
	widgetLabelResult.pack(padx=15,pady=8)

	#Set the WORD widget
	labelwordText.set(word) 
	widgetLabelword.pack(padx=15,pady=8)
Example #29
0
async def urban(ctx, *, word: str):
    """Browse Urban Dictionary."""
    defi = urbandict.define(word)

    definition = defi[0]['def']  #definition of the word
    example = defi[0]['example']  #example of usage (if available)

    #make an embedded message colored blue
    embed = discord.Embed(title=word, description=definition, color=0x0062f4)
    embed.add_field(name="Example", value=example, inline=False)
    embed.set_footer(
        text="Urban Dictionary",
        icon_url=
        'https://vignette.wikia.nocookie.net/logopedia/images/a/a7/UDAppIcon.jpg/revision/latest?cb=20170422211150'
    )
    embed.set_thumbnail(
        url=
        'https://s3.amazonaws.com/pushbullet-uploads/ujxPklLhvyK-RGDsDKNxGPDh29VWVd5iJOh8hkiBTRyC/urban_dictionary.jpg?w=188&h=188&fit=crop'
    )
    await ctx.send(embed=embed)
Example #30
0
def urbandictionary(bot: Bot, update: Update, args):
    spam = spamfilters(update.effective_message.text,
                       update.effective_message.from_user.id,
                       update.effective_chat.id, update.effective_message)
    if spam == True:
        return
    msg = update.effective_message
    chat_id = update.effective_chat.id
    message = update.effective_message
    if args:
        text = " ".join(args)
        try:
            mean = urbandict.define(text)
        except Exception as err:
            send_message(update.effective_message, "Error: " + str(err))
            return
        if len(mean) >= 0:
            teks = ""
            if len(mean) >= 3:
                for x in range(3):
                    teks = "*Result of {}*\n\n*{}*\n*Meaning:*\n`{}`\n\n*Example:*\n`{}`\n\n".format(
                        text, mean[x].get("word")[:-7], mean[x].get("def"),
                        mean[x].get("example"))
            else:
                for x in range(len(mean)):
                    teks = "*Result of {}*\n\n*{}*\n**Meaning:*\n`{}`\n\n*Example:*\n`{}`\n\n".format(
                        text, mean[x].get("word")[:-7], mean[x].get("def"),
                        mean[x].get("example"))
            send_message(update.effective_message,
                         teks,
                         parse_mode=ParseMode.MARKDOWN)
        else:
            send_message(
                update.effective_message,
                "{} couldn't be found in urban dictionary!".format(text),
                parse_mode=ParseMode.MARKDOWN)
    else:
        send_message(
            update.effective_message,
            "Use `/ud <text` for search meaning from urban dictionary.",
            parse_mode=ParseMode.MARKDOWN)
Example #31
0
async def urban_dict(message: Message):
    await message.edit("Processing...")
    query = message.input_str
    if not query:
        await message.err(text="No found any query!")
        return
    try:
        mean = urbandict.define(query)
    except HTTPError:
        await message.err(
            text=f"Sorry, couldn't find any results for: `{query}``")
        return
    output = ''
    for i, mean_ in enumerate(mean, start=1):
        output += f"{i}. **{mean_['def']}**\n" + \
            f"  Examples:\n  * `{mean_['example'] or 'not found'}`\n\n"
    if not output:
        await message.err(text=f"No result found for **{query}**")
        return
    output = f"**Query:** `{query}`\n\n{output}"
    await message.edit_or_send_as_file(text=output, caption=query)
Example #32
0
def index() :
        
    try :
        data = loads(request.get_json())
        args = data.get('args')
    except :
        return dumps({"result":"something broke"})

    pprint(data)

    try :
        action = args[3]
    except :
        return dumps({"result":"Invalid JSON arguments"})

    if action == ':!define':
        term = " ".join(args[4:])
        res = urbandict.define(term)
        defi = res[0].get('def').strip()
        return dumps({'result' : defi})

    return dumps({"result":"noop"})
Example #33
0
async def urban_random(ctx):
    urb = UrbanDictionary(loop=client.loop)
    word = str(await urb.get_random())
    defi = urbandict.define(str(word))
    define = defi[0]['def']
    example = defi[0]['example']
    out = discord.Embed(title=str.upper(word),
                        descripition=define,
                        color=0x0062f4)
    out.add_field(name="Meaning", value=str.title(define), inline=False)
    out.add_field(name="Example", value=str.title(example), inline=False)
    out.set_footer(
        text="Urban Dictionary, " + ctx.message.author.name,
        icon_url=
        'https://vignette.wikia.nocookie.net/logopedia/images/a/a7/UDAppIcon.jpg/revision/latest?cb=20170422211150'
    )
    out.set_thumbnail(
        url=
        'https://s3.amazonaws.com/pushbullet-uploads/ujxPklLhvyK-RGDsDKNxGPDh29VWVd5iJOh8hkiBTRyC/urban_dictionary.jpg?w=188&h=188&fit=crop'
    )
    await client.send_message(ctx.message.channel, embed=out)
    await client.delete_message(ctx.message)
Example #34
0
 async def urban(self, ctx, *, word_search):
     '''Urban Dictionary'''
     embed = discord.Embed(colour=ctx.author.colour)
     common_words = []
     definition = []
     examples = []
     category = []
     a = ""
     c = ""
     try:
         for i in urbandict.define(word_search):
             if i['word']:
                 common_words.append(i['word'])
             if i['def']:
                 definition.append(i['def'])
             if i['example']:
                 examples.append(i['example'])
             if i['category']:
                 category.append(i['category'])
         for j in common_words:
             a += j + ", "
         kall = [k for k in definition]
         dall = [d for d in examples]
         embed.set_author(name=f"Urban Dictionary - {word_search}")
         embed.set_footer(text=f'Requested By {ctx.author}',
                          icon_url=ctx.author.avatar_url)
         embed.add_field(name="Possible Words Related",
                         value=f"`{a}`",
                         inline=False)
         embed.add_field(name="Possible Meanings",
                         value=f"`{' '.join([k for k in kall])}`",
                         inline=False)
         embed.add_field(name="Examples For The Word",
                         value=f"`{' '.join([d for d in dall])}`",
                         inline=False)
         await ctx.send(embed=embed)
     except:
         await ctx.send("Hmm, the word you are looking for is not found!")
Example #35
0
    def incoming(self, user, hostname, channel, msg, current_time, bot):
        if (msg[:3] == '.ud'):
            word = msg[4:]

            definition = urbandict.define(word)

            o = ''
            
            for d in definition:
                o += d['word'] + ' - ' + d['def'].strip().replace('\n', ' ')

                ex = d['example'].strip().replace('\n', ' ')

                if len(ex) > 0:                
                    o += ' - \x02' + d['example'].strip().replace('\n', ' ') +'\x02'
                break
            
            # output
            if len(o) > 0:
                if len(o) > 325:
                    o = o[:323] + '...'
                
                self.bot.say(channel, o[0:350].encode('ascii', 'ignore'))
Example #36
0
async def _(event):
    if event.fwd_from:
        return
    hmm = await edit_or_reply(event, "Searching...🔎")
    query = event.pattern_match.group(1)
    if not query:
        get = await event.get_reply_message()
        query = get.text

    if not query and not event.reply_to_msg_id:
        await hmm.edit("`Gibe some keywords N***a`")
        return

    try:
        mean = urbandict.define(query)

    except BaseException:
        await hmm.edit(
            text=
            f"Sorry, couldn't find any results fer: `{query}``\nSed vary sed \n**TIP**: \n`Now head towerd Googal u nibba`"
        )
        return

    output = ""
    for i, mean_ in enumerate(mean, start=1):
        output += (f"{i}- **{mean_['def']}**\n" +
                   f" Examples:\n » `{mean_['example'] or 'not found'}`\n\n")
        if i == 8:
            break

    if not output:
        await hmm.edit(text=f"No result found for **{query}**")
        return

    output = f"**Query Text:** `{query}`\n\n{output}\n**Source:** __Urban Dictionary__"

    await hmm.edit(output)
Example #37
0
async def urban_dict(message: Message):
    await message.edit("Processing...")
    query = message.filtered_input_str
    if not query:
        await message.err("No found any query!")
        return
    try:
        mean = urbandict.define(query)
    except HTTPError:
        await message.edit(f"Sorry, couldn't find any results for: `{query}`",
                           del_in=5)
        return
    output = ''
    limit = int(message.flags.get('-l', 1))
    for i, mean_ in enumerate(mean, start=1):
        output += f"{i}. **{mean_['def']}**\n" + \
            f"  Examples:\n  * `{mean_['example'] or 'not found'}`\n\n"
        if limit <= i:
            break
    if not output:
        await message.edit(f"No result found for **{query}**", del_in=5)
        return
    output = f"**Query:** `{query}`\n**Limit:** `{limit}`\n\n{output}"
    await message.edit_or_send_as_file(text=output, caption=query)
Example #38
0
    def incoming(self, user, hostname, channel, msg, current_time, bot):
        if (msg[:3] == '.ud'):
            word = msg[4:]

            definition = urbandict.define(word)

            o = ''

            for d in definition:
                o += d['word'] + ' - ' + d['def'].strip().replace('\n', ' ')

                ex = d['example'].strip().replace('\n', ' ')

                if len(ex) > 0:
                    o += ' - \x02' + d['example'].strip().replace('\n',
                                                                  ' ') + '\x02'
                break

            # output
            if len(o) > 0:
                if len(o) > 325:
                    o = o[:323] + '...'

                self.bot.say(channel, o[0:350].encode('ascii', 'ignore'))
Example #39
0
def process_chat(*args):
    img = "anna" + str(random.randint(6,8)) + ".png"
    try:
        ident = args[0]["identifier"]
        global users
        global lastpost
        global cb
        if ident in users:
            interval = (datetime.now() - users[ident]).total_seconds()
            #if interval < 7:
            #    return
        message = args[0]["body"]
        name = args[0]["name"]
        count = str(args[0]["count"])
        convo = args[0]["convo"]
        country_name = args[0]["country_name"]
        country = args[0]["country"]
        if "trip" in args[0]:
            trip = args[0]["trip"]
        else:
            trip = ""
        if trip == "!!n60sL82Wd2" and name == "anna":
            annaposts.append(count)
            return
        # default message
        out_message = ""

        if not message.strip().startswith('.'):
            with sqlite3.connect('lb.sqlite') as conn:
                conn.execute('INSERT INTO posts(id,ident,name,trip,convo,text,country,country_name,date) VALUES(?,?,?,?,?,?,?,?,?);',(count, ident, name, trip, convo, message, country, country_name, datetime.now()))
        

        for k, v in replies.items():
            if message.lower() == '.%s' % k:
                out_message = v

        #if (('to die' in message.lower() or 'death' in message.lower() or 'suicide' in message.lower()) and 'want' in message.lower()) or "kill me" in message.lower():
        #    out_message = random.choice(["Kill urself already.", "Just do it. Kill yourself.", "Suicide is the answer.", "Die"])

        # helpful
        
        if 'dat boi' in message.lower() or 'datboi' in message.lower():
            out_message = "O shit waddup"
        elif 'pian' in message.lower() or 'scriabin' in message.lower():
            out_message = "f**k off"
#        elif (('zack' in message.lower() or 'zach' in message.lower() or 'cali' in message.lower()) and 'f*g' in message.lower()):
#            post_chat('shutting down due to insufficient BTC funds', channel, name="anna", trip=config.annaTrip, convo='', file=img)
#            os.kill(os.getpid(),9)
        elif 'k' in message.lower() and 'pop' in message.lower():
			out_message = "pop pop pop"
			img = "pop.jpg"
        

#        t = re.compile('[wW]hat (is|are) (.+)\?').match(message)
#        if (t):
#            try:
#                res = wolfram.query(t.group(2))
#                #out_message = next(res.results).text
#                out_message = '\n'.join(z.text for z in res.pods[1:] if z)
#                #out_message = wikipedia.summary(t.group(1), sentences=1)
#            except Exception as e:
#                print res.__dict__
#                print out_message
#                out_message = ""
#                print "wolfram error",e

        # kc
        t = re.compile('\.kc( (.+))?').match(message)
        if (t):
            res = kc_quote(t.group(1))
            if res:
                out_message = res

		# lb
        t = re.compile('\.lb( (.+))?').match(message)
        if (t):
            res = lb_quote(t.group(1))
            if res:
                out_message = res

        # reddit
        t = re.compile('\.reddit( (.+))?').match(message)
        if (t):
            if t.group(1) and t.group(1).strip().replace('_','').isalpha() and not re.match('.*(4chan)',t.group(1)):
                res = reddit(t.group(1).strip())
            else:
                res = reddit()
            if res:
                out_message, img = res
        # urban
        t = re.compile('\.urban (.+)').match(message)
        if (t):
            res = ''
            for l in urbandict.define(t.group(1)):
                res += "def: %s\nexample: %s\n" % (l['def'].strip(), l['example'].strip())
            if res:
                out_message = res
        # play
        t = re.compile('\.play( (.+))?').match(message)
        if (t):
            out_message, img = game.play(t.group(1), ident, name, country)
            convo = "hangman"
            
        # buttben
        #t = re.compile('\.buttben( (.+))?').match(message)
        #if (t):
			#img = game.buttbenx(ident, name, country)
			#post_chat(out_message, channel, name="anna", trip=config.annaTrip, convo='hangman', file=img)
			#out_message, img = game.buttbenx(ident, name, country)
			#out_message, img = game.buttbeny(ident, name, country)
			#out_message, img = game.buttbenz(ident, name, country)
			#out_message, img = game.buttbenq(ident, name, country)
			#out_message, img = game.buttbenw(ident, name, country)
			#out_message, img = game.buttbenv(ident, name, country)
			#convo = "hangman"

        # wolfram
#        t = re.compile('\.wa (.+)').match(message)
#        if (t):
#            try:
#                res = wolfram.query(t.group(1))
#                out_message = next(res.results).text
#            except Exception as e:
#                out_message = refuse_message
#                #img = "anna" + str(random.randint(1,5)) + ".png"
#                img = "shit.jpg"
#                print e
         
        # wiki
        t = re.compile('\.wiki(pedia)? (.+)').match(message)
        if (t):
            try:
                out_message = wikipedia.summary(t.group(2), sentences=3)
            except wikipedia.DisambiguationError as e:
                out_message = str(e)
            except Exception as e:
                out_message = refuse_message
                #img = "anna" + str(random.randint(1,5)) + ".png"
                img = "shit.jpg"
                print e
     
        # google
#        t = re.compile('\.google( (.+))?').match(message)
#        if (t):
#            try:
#                r = duckduckgo.query(t.group(2))
#                for i in xrange(len(r.related) if len(r.related) < 4 else 3):
#                    result = r.related[i]
#                    out_message += '\n'+ result.text + '\n'
#                    out_message += '[i]' + result.url + ' [/i]\n'
#            except Exception as e:
#                out_message = refuse_message
#                #img = "anna" + str(random.randint(1,5)) + ".png"
#                img = "shit.jpg"
#                print e

        # random
        t = re.compile('\.random( (.+))?').match(message)
        if (t):
            try:
                if t.group(1) and t.group(2).isdigit():
                    out_message += str(random.randint(0, int(t.group(2))))
                else:
                    out_message += str(random.randint(0, 100))
                    if int(out_message)%10 == int(out_message)/10:
                        out_message += " (you got doubles :3)"
            except Exception as e:
                out_message = "That was ambiguous, Onii-chan"
                #img = "anna" + str(random.randint(1,5)) + ".png"
                img = "shit.jpg"
                print e
        # fortune
        t = re.compile('\.fortune( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune fortunes').read().strip()
            #out_message = os.popen('fortune').read().strip()
        
        # fortune-pl
        t = re.compile('\.fortunepl( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune pl').read().strip()
            
        # fortune-ru
        t = re.compile('\.fortuneru( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune ru').read().strip()
            
        # fortune-fr
        t = re.compile('\.fortunefr( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune fr').read().strip()
            
        # riddle
        t = re.compile('\.riddle( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune riddles').read().strip()
        # stats
        t = re.compile('\.stats( (.+))?').match(message)
        if (t):
            out_message = stats()
        # scores
        t = re.compile('\.scores( (.+))?').match(message)
        if (t):
            out_message = game.stats()
        # online
        t = re.compile('\.online( (.+))?').match(message)
        if (t):
            out_message = online()
        # countries
        t = re.compile('\.countries( (.+))?').match(message)
        if (t):
            out_message = countries()
        # regions
        t = re.compile('\.regions( (.+))?').match(message)
        if (t):
            out_message = regions()
        # joke
        t = re.compile('\.joke( (.+))?').match(message)
        if (t):
            out_message = norris()#random.choice(open('jokes.txt').read().split('\n-')).strip()
        # meme
        t = re.compile('\.meme( (.+))?').match(message)
        if (t):
            out_message = " "
            img = 'memes/'+random.choice(os.listdir('memes'))
        # hi
        t = re.compile('\.hi( (.+))?').match(message)
        if (t):
            out_message = "%s, %s!" % (random.choice(['Hi', 'Hello', 'Privet', 'Hola', 'Bonjour', 'Hallo', 'Siema', 'Pryvitanne', 'Zdravstvuj', 'Pryvit', 'Shlamalokh', 'Shalom', 'Shalam', 'Aloha']), name)
        # help
        t = re.compile('\.help( (.+))?').match(message)
        if (t):
            out_message = "commands are .hi .p**n .kc .random .joke .fortune .fortuneru .fortunefr .fortunepl .google .urban .wa .wiki .riddle .meme .play .reddit .stats .countries .regions .online .scores"
            out_message += '\nor "Anna ...?" or "What is/are ...?"'
        # p**n
        t = re.compile('\.p**n( (.+))?').match(message)
        if (t):
            out_message = random.choice([
                'You are wankaholic',
                'You are addicted to masturbating',
                'You are addicted to pornography',
                'Hi wanka',
                ])
            img = 'wanka.jpg'
            img = 'p**n/'+random.choice(os.listdir('p**n'))
            convo = 'General'

        ## add
        #t = re.compile('\.add (\w+) (.+)').match(message)
        #if (t):
        #    #print t.groups(1)[0], t.groups(1)[1]
        #    replies[t.groups(1)[0]] = t.groups(1)[1]


        if (message.splitlines() and message.splitlines()[0].lstrip('>') in annaposts) or (message.lower().startswith('anna') and message.endswith('?')):
            try:
                if message.lower().startswith('anna'):
                    message = message[4:].strip()
                out_message = cb.ask(u'\n'.join(line for line in message.splitlines() if not line.startswith('>')))
            except Exception as e:
                out_message = refuse_message
                #img = "anna" + str(random.randint(1,5)) + ".png"
                img = "shit.jpg"
                print e
                cb = Cleverbot()

#        if count[-1]==count[-1] and random.randint(1,20)==2 and not count[-1]==count[-2]:
#            out_message = "nice singles bro"
#            img = "anna" + str(random.randint(6,8)) + ".png"

		###this checks trips, quads, quints and septs
		###>you need not dubs folder but files dubs1.jpg - dubs5.jpg right in anna folder
		#if count[-1]==count[-2]==count[-3] or count[-1]==count[-2]==count[-3]==count[-4] or count[-1]==count[-2]==count[-3]==count[-4]==count[-5] or count[-1]==count[-2]==count[-3]==count[-4]==count[-5]==count[-6]:
		# out_message = "CHECKED"
		# img = "dubs" + str(random.randint(1,5)) + ".jpg"

        #if 'anna' in message.lower():
        #    out_message = "you said my name, Onii-chan?"
        #if 'kcmod' in message.lower():
        #    out_message = "mods are cucks"

        if not out_message and random.randint(0,45) == 5 and (datetime.now() - lastpost).total_seconds() > 30:
            print (datetime.now() - lastpost).total_seconds()
            out_message = kc_quote()
            count = 0
            
        if re.search('\d+\.\d+.\d+.\d+', out_message):
            out_message = ''

        if out_message != "":
            users[ident] = datetime.now()
            lastpost = datetime.now()
            if (count):
                out_message = ">>"+count+"\n"+out_message#.encode('ascii', 'ignore')
            post_chat(out_message, channel,
                    name="anna", trip=config.annaTrip,
                    convo=convo, file=img)
    except Exception as e:
        #print type(e), e
        #raise
        print e
Example #40
0
#!/usr/bin/python

#https://github.com/novel/py-urbandict
import urbandict
import time
import json
from string import ascii_lowercase

# Open a file
with open('foo2.txt', 'w') as outfile:    
    for a in ascii_lowercase:
        for b in ascii_lowercase:
            #print a+b
            #fo.write(a+b);
            time.sleep(1)
            result = urbandict.define(a+b)
            #print result[0]        
            json.dump(result[0], outfile)

# Open a file
with open('foo3.txt', 'w') as outfile:    
    for a in ascii_lowercase:
        for b in ascii_lowercase:
            for c in ascii_lowercase:
                #print a+b+c
                time.sleep(1)
                result = urbandict.define(a+b+c)
                #print result[0]        
                json.dump(result[0], outfile)
Example #41
0
def process_chat(*args):
    img = "anna" + str(random.randint(6, 8)) + ".png"
    try:
        ident = args[0]["identifier"]
        global users
        global lastpost
        global cb
        if ident in users:
            interval = (datetime.now() - users[ident]).total_seconds()
            #if interval < 7:
            #    return
        message = args[0]["body"]
        name = args[0]["name"]
        count = str(args[0]["count"])
        convo = args[0]["convo"]
        country_name = args[0]["country_name"]
        country = args[0]["country"]
        if "trip" in args[0]:
            trip = args[0]["trip"]
        else:
            trip = ""
        if trip == "!!n60sL82Wd2" and name == "anna":
            annaposts.append(count)
            return
        # default message
        out_message = ""

        if not message.strip().startswith('.'):
            with sqlite3.connect('lb.sqlite') as conn:
                conn.execute(
                    'INSERT INTO posts(id,ident,name,trip,convo,text,country,country_name,date) VALUES(?,?,?,?,?,?,?,?,?);',
                    (count, ident, name, trip, convo, message, country,
                     country_name, datetime.now()))

        for k, v in replies.items():
            if message.lower() == '.%s' % k:
                out_message = v

        #if (('to die' in message.lower() or 'death' in message.lower() or 'suicide' in message.lower()) and 'want' in message.lower()) or "kill me" in message.lower():
        #    out_message = random.choice(["Kill urself already.", "Just do it. Kill yourself.", "Suicide is the answer.", "Die"])

        # helpful

        if 'dat boi' in message.lower() or 'datboi' in message.lower():
            out_message = "O shit waddup"
        elif 'pian' in message.lower() or 'scriabin' in message.lower():
            out_message = "f**k off"
        elif (('zack' in message.lower() or 'zach' in message.lower()
               or 'cali' in message.lower()) and 'f*g' in message.lower()):
            post_chat('shutting down due to insufficient BTC funds',
                      channel,
                      name="anna",
                      trip=config.annaTrip,
                      convo='',
                      file=img)
            os.kill(os.getpid(), 9)
        elif 'k' in message.lower() and 'pop' in message.lower():
            out_message = "pop pop pop"
            img = "pop.jpg"

#        t = re.compile('[wW]hat (is|are) (.+)\?').match(message)
#        if (t):
#            try:
#                res = wolfram.query(t.group(2))
#                #out_message = next(res.results).text
#                out_message = '\n'.join(z.text for z in res.pods[1:] if z)
#                #out_message = wikipedia.summary(t.group(1), sentences=1)
#            except Exception as e:
#                print res.__dict__
#                print out_message
#                out_message = ""
#                print "wolfram error",e

# kc
        t = re.compile('\.kc( (.+))?').match(message)
        if (t):
            res = kc_quote(t.group(1))
            if res:
                out_message = res

        # reddit
        t = re.compile('\.reddit( (.+))?').match(message)
        if (t):
            if t.group(1) and t.group(1).strip().replace(
                    '_',
                    '').isalpha() and not re.match('.*(4chan)', t.group(1)):
                res = reddit(t.group(1).strip())
            else:
                res = reddit()
            if res:
                out_message, img = res
        # urban
        t = re.compile('\.urban (.+)').match(message)
        if (t):
            res = ''
            for l in urbandict.define(t.group(1)):
                res += "def: %s\nexample: %s\n" % (l['def'].strip(),
                                                   l['example'].strip())
            if res:
                out_message = res
        # play
        t = re.compile('\.play( (.+))?').match(message)
        if (t):
            out_message, img = game.play(t.group(1), ident, name, country)
            convo = "hangman"

        # wolfram
#        t = re.compile('\.wa (.+)').match(message)
#        if (t):
#            try:
#                res = wolfram.query(t.group(1))
#                out_message = next(res.results).text
#            except Exception as e:
#                out_message = refuse_message
#                #img = "anna" + str(random.randint(1,5)) + ".png"
#                img = "shit.jpg"
#                print e

# wiki
        t = re.compile('\.wiki(pedia)? (.+)').match(message)
        if (t):
            try:
                out_message = wikipedia.summary(t.group(2), sentences=3)
            except wikipedia.DisambiguationError as e:
                out_message = str(e)
            except Exception as e:
                out_message = refuse_message
                #img = "anna" + str(random.randint(1,5)) + ".png"
                img = "shit.jpg"
                print e

        # google
#        t = re.compile('\.google( (.+))?').match(message)
#        if (t):
#            try:
#                r = duckduckgo.query(t.group(2))
#                for i in xrange(len(r.related) if len(r.related) < 4 else 3):
#                    result = r.related[i]
#                    out_message += '\n'+ result.text + '\n'
#                    out_message += '[i]' + result.url + ' [/i]\n'
#            except Exception as e:
#                out_message = refuse_message
#                #img = "anna" + str(random.randint(1,5)) + ".png"
#                img = "shit.jpg"
#                print e

# random
        t = re.compile('\.random( (.+))?').match(message)
        if (t):
            try:
                if t.group(1) and t.group(2).isdigit():
                    out_message += str(random.randint(0, int(t.group(2))))
                else:
                    out_message += str(random.randint(0, 100))
                    if int(out_message) % 10 == int(out_message) / 10:
                        out_message += " (you got doubles :3)"
            except Exception as e:
                out_message = "That was ambiguous, Onii-chan"
                #img = "anna" + str(random.randint(1,5)) + ".png"
                img = "shit.jpg"
                print e
        # fortune
        t = re.compile('\.fortune( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune fortunes').read().strip()
            #out_message = os.popen('fortune').read().strip()

        # fortune-pl
        t = re.compile('\.fortunepl( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune pl').read().strip()

        # fortune-ru
        t = re.compile('\.fortuneru( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune ru').read().strip()

        # fortune-fr
        t = re.compile('\.fortunefr( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune fr').read().strip()

        # riddle
        t = re.compile('\.riddle( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune riddles').read().strip()
        # stats
        t = re.compile('\.stats( (.+))?').match(message)
        if (t):
            out_message = stats()
        # scores
        t = re.compile('\.scores( (.+))?').match(message)
        if (t):
            out_message = game.stats()
        # online
        t = re.compile('\.online( (.+))?').match(message)
        if (t):
            out_message = online()
        # countries
        t = re.compile('\.countries( (.+))?').match(message)
        if (t):
            out_message = countries()
        # regions
        t = re.compile('\.regions( (.+))?').match(message)
        if (t):
            out_message = regions()
        # joke
        t = re.compile('\.joke( (.+))?').match(message)
        if (t):
            out_message = norris(
            )  #random.choice(open('jokes.txt').read().split('\n-')).strip()
        # meme
        t = re.compile('\.meme( (.+))?').match(message)
        if (t):
            out_message = " "
            img = 'memes/' + random.choice(os.listdir('memes'))
        # hi
        t = re.compile('\.hi( (.+))?').match(message)
        if (t):
            out_message = "%s, %s!" % (random.choice(
                ['Hi', 'Hello', 'Privet', 'Hola', 'Bonjour', 'Hallo']), name)
        # help
        t = re.compile('\.help( (.+))?').match(message)
        if (t):
            out_message = "commands are .hi .p**n .kc .random .joke .fortune .fortuneru .fortunefr .fortunepl .google .urban .wa .wiki .riddle .meme .play .reddit .stats .countries .regions .online .scores"
            out_message += '\nor "Anna ...?" or "What is/are ...?"'
        # p**n
        t = re.compile('\.p**n( (.+))?').match(message)
        if (t):
            out_message = random.choice([
                'You are wankaholic',
                'You are addicted to masturbating',
                'You are addicted to pornography',
                'Hi wanka',
            ])
            img = 'wanka.jpg'
            img = 'p**n/' + random.choice(os.listdir('p**n'))
            convo = 'General'

        ## add
        #t = re.compile('\.add (\w+) (.+)').match(message)
        #if (t):
        #    #print t.groups(1)[0], t.groups(1)[1]
        #    replies[t.groups(1)[0]] = t.groups(1)[1]

        if (message.splitlines() and message.splitlines()[0].lstrip('>')
                in annaposts) or (message.lower().startswith('anna')
                                  and message.endswith('?')):
            try:
                if message.lower().startswith('anna'):
                    message = message[4:].strip()
                out_message = cb.ask(u'\n'.join(
                    line for line in message.splitlines()
                    if not line.startswith('>')))
            except Exception as e:
                out_message = refuse_message
                #img = "anna" + str(random.randint(1,5)) + ".png"
                img = "shit.jpg"
                print e
                cb = Cleverbot()

        #if count[-1]==count[-2] and random.randint(1,5)==2:
        #    out_message = "CHECKED"
        #    img = "dubs" + str(random.randint(1,5)) + ".jpg"

###this checks trips, quads, quints and septs
###>you need not dubs folder but files dubs1.jpg - dubs5.jpg right in anna folder
#if count[-1]==count[-2]==count[-3] or count[-1]==count[-2]==count[-3]==count[-4] or count[-1]==count[-2]==count[-3]==count[-4]==count[-5] or count[-1]==count[-2]==count[-3]==count[-4]==count[-5]==count[-6]:
# out_message = "CHECKED"
# img = "dubs" + str(random.randint(1,5)) + ".jpg"

#if 'anna' in message.lower():
#    out_message = "you said my name, Onii-chan?"
#if 'kcmod' in message.lower():
#    out_message = "mods are cucks"

        if not out_message and random.randint(
                0,
                45) == 5 and (datetime.now() - lastpost).total_seconds() > 30:
            print(datetime.now() - lastpost).total_seconds()
            out_message = kc_quote()
            count = 0

        if out_message != "":
            users[ident] = datetime.now()
            lastpost = datetime.now()
            if (count):
                out_message = ">>" + count + "\n" + out_message  #.encode('ascii', 'ignore')
            post_chat(out_message,
                      channel,
                      name="anna",
                      trip=config.annaTrip,
                      convo=convo,
                      file=img)
    except Exception as e:
        #print type(e), e
        #raise
        print e
Example #42
0
File: milu.py Project: zunc/milubot
def queryUrbandict(query):
	uRes = urbandict.define(query)
	if len(uRes) > 0:
		for word in uRes:
			if 'def' in word:
				return word['def']
Example #43
0
 def run(self, term):
     result = urbandict.define(term)
     result = json.dumps(result)
     return result
Example #44
0
async def getUrbanDef(message):
	word = message.content.replace("-urban ", "")
	definition = urbandict.define(word)
	example = definition[0]['example']
	defi = definition[0]['def']
	await client.send_message(message.channel, "```\nPhrase: " + word + "\nDefinition: " + defi + "\nExample: " + example + "\n```")
Example #45
0
def process_chat(*args):
    img = "anna" + str(random.randint(6,8)) + ".png"
    try:
        ident = args[0]["identifier"]
        global users
        global lastpost
        global cb
        if ident in users:
            interval = (datetime.now() - users[ident]).total_seconds()
            #if interval < 7:
            #    return
        message = args[0]["body"]
        name = args[0]["name"]
        count = str(args[0]["count"])
        convo = args[0]["convo"]
        country_name = args[0]["country_name"]
        country = args[0]["country"]
        if "trip" in args[0]:
            trip = args[0]["trip"]
        else:
            trip = ""
        if trip == "!!n60sL82Wd2" and name == "anna":
            annaposts.append(count)
            return
        # default message
        out_message = ""

        if not message.strip().startswith('.'):
            with sqlite3.connect('lb.sqlite') as conn:
                conn.execute('INSERT INTO posts(id,ident,name,trip,convo,text,country,country_name,date) VALUES(?,?,?,?,?,?,?,?,?);',(count, ident, name, trip, convo, message, country, country_name, datetime.now()))
        

        for k, v in replies.items():
            if message.lower() == '.%s' % k:
                out_message = v

        #if (('to die' in message.lower() or 'death' in message.lower() or 'suicide' in message.lower()) and 'want' in message.lower()) or "kill me" in message.lower():
        #    out_message = random.choice(["Kill urself already.", "Just do it. Kill yourself.", "Suicide is the answer.", "Die"])

        # helpful
        t = re.compile('[wW]hat (is|are) (.+)\?').match(message)
        if (t):
            try:
                res = wolfram.query(t.group(2))
                #out_message = next(res.results).text
                out_message = '\n'.join(z.text for z in res.pods[1:] if z)
                #out_message = wikipedia.summary(t.group(1), sentences=1)
            except Exception as e:
                print res.__dict__
                print out_message
                out_message = ""
                print "wolfram error",e

        # kc
        t = re.compile('\.kc( (.+))?').match(message)
        if (t):
            res = kc_quote(t.group(1))
            if res:
                out_message = res


        # reddit
        t = re.compile('\.reddit( (.+))?').match(message)
        if (t):
            if t.group(1) and t.group(1).strip().replace('_','').isalpha() and not re.match('.*(gay|c**k|penis|ass)',t.group(1)):
                res = reddit(t.group(1).strip())
            else:
                res = reddit()
            if res:
                out_message, img = res
        # urban
        t = re.compile('\.urban (.+)').match(message)
        if (t):
            res = ''
            for l in urbandict.define(t.group(1)):
                res += "def: %s\nexample: %s\n" % (l['def'].strip(), l['example'].strip())
            if res:
                out_message = res
        # play
        t = re.compile('\.play( (.+))?').match(message)
        if (t):
            out_message, img = game.play(t.group(1), ident, name, country)
            convo = "hangman"

        # wolfram
        t = re.compile('\.wa (.+)').match(message)
        if (t):
            try:
                res = wolfram.query(t.group(1))
                out_message = next(res.results).text
            except Exception as e:
                out_message = refuse_message
                img = "anna" + str(random.randint(1,5)) + ".png"
                #img = "shit.jpg"
                print e
         
        # wiki
        t = re.compile('\.wiki(pedia)? (.+)').match(message)
        if (t):
            try:
                out_message = wikipedia.summary(t.group(2), sentences=3)
            except wikipedia.DisambiguationError as e:
                out_message = str(e)
            except Exception as e:
                out_message = refuse_message
                img = "anna" + str(random.randint(1,5)) + ".png"
                #img = "shit.jpg"
                print e
     
        # google
        t = re.compile('\.google( (.+))?').match(message)
        if (t):
            try:
                r = duckduckgo.query(t.group(2))
                for i in xrange(len(r.related) if len(r.related) < 4 else 3):
                    result = r.related[i]
                    out_message += '\n'+ result.text + '\n'
                    out_message += '[i]' + result.url + ' [/i]\n'
            except Exception as e:
                out_message = refuse_message
                img = "anna" + str(random.randint(1,5)) + ".png"
                #img = "shit.jpg"
                print e

        # random
        t = re.compile('\.random( (.+))?').match(message)
        if (t):
            try:
                if t.group(1) and t.group(2).isdigit():
                    out_message += str(random.randint(0, int(t.group(2))))
                else:
                    out_message += str(random.randint(0, 100))
                    if int(out_message)%10 == int(out_message)/10:
                        out_message += " (you got doubles :3)"
            except Exception as e:
                out_message = "That was ambiguous, Onii-chan"
                img = "anna" + str(random.randint(1,5)) + ".png"
                #img = "shit.jpg"
                print e
        # fortune
        t = re.compile('\.fortune( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune fortunes').read().strip()
        # riddle
        t = re.compile('\.riddle( (.+))?').match(message)
        if (t):
            out_message = os.popen('fortune riddles').read().strip()
        # stats
        t = re.compile('\.stats( (.+))?').match(message)
        if (t):
            out_message = stats()
        # scores
        t = re.compile('\.scores( (.+))?').match(message)
        if (t):
            out_message = game.stats()
        # online
        t = re.compile('\.online( (.+))?').match(message)
        if (t):
            out_message = online()
        # countries
        t = re.compile('\.countries( (.+))?').match(message)
        if (t):
            out_message = countries()
        # regions
        t = re.compile('\.regions( (.+))?').match(message)
        if (t):
            out_message = regions()
        # joke
        t = re.compile('\.joke( (.+))?').match(message)
        if (t):
            out_message = norris()#random.choice(open('jokes.txt').read().split('\n-')).strip()
        # meme
        t = re.compile('\.meme( (.+))?').match(message)
        if (t):
            out_message = " "
            img = 'memes/'+random.choice(os.listdir('memes'))
        # hi
        t = re.compile('\.hi( (.+))?').match(message)
        if (t):
            out_message = "%s, %s!" % (random.choice(['Hi', 'Hello', 'Privet', 'Hola', 'Bonjour', 'Hallo']), name)
        # help
        t = re.compile('\.help( (.+))?').match(message)
        if (t):
            out_message = "commands are .hi .p**n .kc .random .joke .fortune .google .urban .wa .wiki .riddle .meme .play .reddit .stats .countries .regions .online .scores"
            out_message += '\nor "Anna ...?" or "What is/are ...?"'
        # p**n
        t = re.compile('\.p**n( (.+))?').match(message)
        if (t):
            out_message = random.choice([
                'You are wankaholic',
                'You are addicted to masturbating',
                'You are addicted to pornography',
                'Hi wanka',
                ])
            img = 'wanka.jpg'
            img = 'p**n/'+random.choice(os.listdir('p**n'))
            convo = 'nsfw'

        ## add
        #t = re.compile('\.add (\w+) (.+)').match(message)
        #if (t):
        #    #print t.groups(1)[0], t.groups(1)[1]
        #    replies[t.groups(1)[0]] = t.groups(1)[1]


        if (message.splitlines() and message.splitlines()[0].lstrip('>') in annaposts) or (message.lower().startswith('anna') and message.endswith('?')):
            try:
                if message.lower().startswith('anna'):
                    message = message[4:].strip()
                out_message = cb.ask(u'\n'.join(line for line in message.splitlines() if not line.startswith('>')))
            except Exception as e:
                out_message = refuse_message
                img = "anna" + str(random.randint(1,5)) + ".png"
                #img = "shit.jpg"
                print e
                cb = Cleverbot()

        #if count[-1]==count[-2] and random.randint(1,5)==2:
        #    out_message = "CHECKED"
        #    img = "dubs" + str(random.randint(1,5)) + ".jpg"


        #if 'anna' in message.lower():
        #    out_message = "you said my name, Onii-chan?"
        #if 'kcmod' in message.lower():
        #    out_message = "mods are cucks"

        if not out_message and random.randint(0,45) == 5 and (datetime.now() - lastpost).total_seconds() > 30:
            print (datetime.now() - lastpost).total_seconds()
            out_message = kc_quote()
            count = 0

        if out_message != "":
            users[ident] = datetime.now()
            lastpost = datetime.now()
            if (count):
                out_message = ">>"+count+"\n"+out_message#.encode('ascii', 'ignore')
            post_chat(out_message, channel,
                    name="anna", trip=config.annaTrip,
                    convo=convo, file=img)
    except Exception as e:
        #print type(e), e
        #raise
        print e
Example #46
0
def urbandefine(word):
	data = urbandict.define(word)
	
	return data
Example #47
0
def temp(data, what):
	final=""
	d=urbandict.define(str(what))
	for item in d:
		final =final + item['def'] 
	return final
Example #48
0
# check what we've already done - may have to rerun script in case of timeout
done_words = dict()
with open('suggestive.txt') as f:
    for word in f:
        done_words[word.strip()] = 1
with open('non_suggestive.txt') as g:
    for word in g:
        done_words[word.strip()] = 1


path_to_urban_dictionary = '/home/michelle/Language_Resources/english/urban-dictionary-word-list/data/'
with open('suggestive.txt', 'a') as g1:
    with open('non_suggestive.txt', 'a') as g2:
        for letter in string.ascii_uppercase:
            with open(path_to_urban_dictionary + letter + '.data') as f:
                for term in f:
                    term = term.strip().lower()
                    if term in done_words:
                        continue
                    if is_term_in_pnp(term):
                        defns = urbandict.define(term)
                        if seems_suggestive(defns):
                            print(defns)
                            g1.write(term + '\n')
                            g1.flush()
                        else:
                            g2.write(term + '\n')
                            g2.flush()
                        time.sleep(1)
                    done_words[term] = 1
Example #49
0
def index():
	os.system('clear')
	print("\033[1;31m")
	print(" ______".center(width))
	print("/ dave \\".center(width, "_"))
	print("".center(width, "~"))
	print("\033[1;32m\n")
	print(" version 2.1.2 ".center(width, "."))
	print("\033[1;34m\n")
	print(" for help type \"help\" and press enter".center(width))
	print("\n \033[1;32m")
	query = input("\033[1;33m-> ")
	os.system('clear')
	if "wiki" in query:
		print("Searching Wikipedia...")
		try:
			wikiSearch = query.replace('wiki ', '')
			outputs = wikipedia.summary(wikiSearch, sentences=8)
			os.system('clear')
			print("\n")
			print('Wikipedia says:'.center(width))
			print("\n")
			print("\n")
			print(outputs)
			print("\n")
			print("Press enter to return")
			_return_ = input()
			index()
		except:
			os.system('clear')
			print("\n")
			print('\033[1;35mNo Wikipeda Page Found'.center(width))
			print("\n\n")
			print('\033[1;34mNo wikipedia page found, check your request and try again or search google by typing \"search\" followed by your request.'.center(width, " "))
			print("\033[1;33m\n")
			print("Press enter to return")
			_return_ = input()
			index()

	if "open" in query:
		openApp = query.replace('open ', '')
		print("Opening " + openApp + "...")
		os.system('open -a "' + openApp + '"')
		os.system('clear')
		print(openApp + " has been opened")
		print("\n")
		print("Press enter to return")	
		_return_ = input()
		index()
		
	if "solve" in query:
		eq = query.replace('solve ', '')
		print("solving " + eq + "...")
		solved = eval(eq)
		print("\n")
		print(solved)
		print("\n")
		print("Press enter to return")	
		_return_ = input()
		index()

	if "weather" in query:
		city = input("Where do you live: ")
		try:
			data.get_yahoo_weather_by_city(city, Unit.celsius)
			os.system('clear')
			print("Today in " + city + " it is ", data.condition.text, "and it is ",data.condition.temperature, "degrees celcius.")
			print("\n")
			print("Press enter to return")
			_return_ = input()
			index()
		except:
			print("No city found")
			print("\n")
			print("Press enter to return")
			_return_ = input()
			index()

	if "joke" in query:
		print("What do you do if you're cold?")
		engine.say("What do you do if you're cold?")
		engine.runAndWait()
		print("\n")
		time.sleep(1)
		print("Stand in the corner of the room, it's 90 degrees")
		engine.say("Stand in the corner of the room, it's 90 degrees")
		engine.runAndWait()
		engine.say("Ha. Ha. Ha. Ha. Ha.")
		engine.runAndWait()
		print("\n")
		print("Press enter to return")
		_return_ = input()
		index()

	if "ud" in query:
		os.system('clear')
		print("Searching urban dictionary...")
		try:
			to_def = query.replace('ud ', '')
			defs = urbandict.define(to_def)
			os.system('clear')
			print(to_def)
			print("\n")
			print("Press enter to return")
			_return_ = input()
			index()
		except:
			os.system('clear')
			print("Nothing can be found")
			print("\n")
			print("Press enter to return")
			_return_ = input()
			index()
	#day because date is used with update
	if "day" in query:
		today = datetime.now()
		d = date.today()
		wd = date.weekday(today)
		days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
		os.system('clear')
		print("Today is the", d, "which is a " + days[wd])
		print("\n")
		print("Press enter to return")
		_return_ = input()
		index()

	if "search" in query:
		search = query.replace('search ', '')
		print("Searching " + search + "...")
		webbrowser.open_new_tab("https://www.google.com/search?q=" + search)
		os.system('clear')
		print(search + " has been opened in default browser")
		print("\n")
		print("Press enter to return")	
		_return_ = input()
		index()

	if "help" in query:
		os.system('clear')
		print("Help Section: \n Wikipedia: Write \"wiki\" followed your querie (You can use brackets to make your querie more specific) \n Open: Open apps by typing \"open\" followed by desired app \n Urban Dictionary: Get definition by typing \"ud\" followed by desired word \n Search: Search things on google by typing \"search\" followed by your querie \n Weather: Type \"weather\" and follow the prompts \n Solve: Solve equations by typing \"solve\" followed by your problem \n Day: Type \"day\" to see the date\n Update: Type \"update\" and follow prompts to update to the newest version of dave \n Help: Write \"help\" for list of all queries ")
		print("\n")
		print("Press enter to return")	
		_return_ = input()
		index()
	
	if "exit" in query:
		os.system("reset")
		time.sleep(0.5)
		os.system("clear")
		exit()

	if "update" in query:
		print("Note: Updating for the first time will take a while")
		time.sleep(0.5)
		os.system("rm -R ~/dave-master/")
		os.system("rm -R ~/downloads/dave-master/")
		os.system("rm ~/downloads/master.zip")
		os.system("xcode-select --install")
		os.system("/usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"")
		os.system("brew install wget")
		os.system("wget --no-check-certificate -P  ~/Downloads https://github.com/Handmade-Studios/dave/archive/master.zip")
		os.system("open ~/Downloads/master.zip")
		time.sleep(1)
		os.system("mkdir ~/dave-master/")
		time.sleep(1)
		os.system("ditto ~/Downloads/dave-master/ ~/dave-master")
		time.sleep(1)
		os.system("clear")
		print("\033[1;31m\nDave has been updated restart to see new version")
		os.system("rm -R ~/downloads/dave-master/")
		time.sleep(1)
		print("\033[1;31m\nDave is self-closing...")
		time.sleep(1)
		os.system("rm ~/downloads/master.zip")
		time.sleep(2)
		os.system("reset")
		time.sleep(0.5)
		exit()

	else:
		print("What? Unrecognised command")
		print("\nType \"help\" for a list of commands")
		print("\n")
		print("Press enter to return")
		_return_ = input()
		index()
Example #50
0
def urbandefine(word):
	raw_data = urbandict.define(word)
	json_data = open(raw_data)
	data = json.load(raw_data)
	pprint(data)
Example #51
0
def temp(data, what):
    final = ""
    d = urbandict.define(str(what))
    for item in d:
        final = final + item['def']
    return final
Example #52
0
async def urban(query):
    'Urban directory'
    res = ''
    for l in urbandict.define(query):
        res += "def: %s\nexample: %s\n" % (l['def'].strip(), l['example'].strip())
    return res or "Didn't find anything"
 def run(self, term):
     result = urbandict.define(term)
     result = json.dumps(result)
     return result
def echo(bot, update_id):

    # Request updates after the last update_id
    for update in bot.getUpdates(offset=update_id, timeout=10):
        # chat_id is required to reply to any message
        chat_id = update.message.chat_id
        update_id = update.update_id + 1
        try:
            # UCS-4
            patt = re.compile(u'([\U00002600-\U000027BF])|([\U0001f300-\U0001f64F])|([\U0001f680-\U0001f6FF])')
        except re.error:
            # UCS-2
            patt = re.compile(u'([\u2600-\u27BF])|([\uD83C][\uDF00-\uDFFF])|([\uD83D][\uDC00-\uDE4F])|([\uD83D][\uDE80-\uDEFF])')        
        message = patt.sub('_emoji_', update.message.text)             

        if message:
            # Reply to the message
            words = message.split(' ')
            requester = update.message.from_user.username
            users = "@meeoh @KamalZia @Sh4ni @basil3 @jullybhai @Paytheo @amadrx8 @moezb @gaandslayer @nomar"
            zias = "@KamalZia @Sh4ni"
            ahmads = "@jullybhai @basil3 @gaandslayer"
            abdullahs = "@meeoh @Paytheo @amadrx8 @nomar"
            bhattis = "@moezb @riyad"
            words[0] = words[0].lower()

            if (words[0] == "/all"):
                if(len(words) >= 2):
                    response = users + " " + message.split(' ', 1)[1]
                    bot.sendMessage(chat_id=chat_id, text=response)
                else:
                    bot.sendMessage(chat_id=chat_id, text=users)
            elif (words[0] == "/ahmads"):
                if(len(words) >= 2):
                    response = ahmads + " " + message.split(' ', 1)[1]
                    bot.sendMessage(chat_id=chat_id, text=response)
                else:
                    bot.sendMessage(chat_id=chat_id, text=ahmads)
            elif (words[0] == "/zias"):
                if(len(words) >= 2):
                    response = zias + " " + message.split(' ', 1)[1]
                    bot.sendMessage(chat_id=chat_id, text=zias)
                else:
                    bot.sendMessage(chat_id=chat_id, text=zias)
            elif (words[0] == "/abdullahs"):
                if(len(words) >= 2):
                    response = abdullahs + " " + message.split(' ', 1)[1]
                    bot.sendMessage(chat_id=chat_id, text=abdullahs)
                else:
                    bot.sendMessage(chat_id=chat_id, text=abdullahs)
            elif (words[0] == "/bhattis"):
                if(len(words) >= 2):
                    response = abdullahs + " " + message.split(' ', 1)[1]
                    bot.sendMessage(chat_id=chat_id, text=bhattis)
                else:
                    bot.sendMessage(chat_id=chat_id, text=bhattis)
            elif (words[0] == "/urban"):
                if(len(words) < 2):
                    response = "Please provide a term to look up in the Urban Dictionary"
                    bot.sendMessage(chat_id=chat_id, text=response)
                else:
                    query = message.split(' ', 1)[1]
                    urban = urbandict.define(query)[0]
                    defn = urban["def"]
                    reply = urban["word"].rstrip() + ": " + defn + \
                        "\nexamples: " + urban["example"]
                    bot.sendMessage(chat_id=chat_id, text=reply)

            elif (words[0] == "/wolf"):
                if(len(words) < 2):
                    err = "Please provide an argument to Wolfram Alpha"
                    bot.sendMessage(chat_id=chat_id, text=err)
                else:
                    query = message.split(' ', 1)[1]
                    query = query.replace('+', 'plus')
                    r = requests.get(
                        "http://api.wolframalpha.com/v2/query?appid=E533KV-9URK4TXPJK&input=" + query + "&format=plaintext")
                    soup = BeautifulSoup(r.content, "html.parser")
                    try:
                        pod_value = soup.find_all('pod')[1].find(
                            'plaintext').contents[0]
                    except:
                        pod_value = "Invalid query for wolframalpha, try again"
                    bot.sendMessage(chat_id=chat_id, text=pod_value)
            elif (words[0] == "/song"):
                response = ""
                query = message.split(' ', 1)[1]
                query = query.replace(' ', '%20')
                r = requests.get("http://api.genius.com/search?q=" + query, headers = {'Authorization': 'Bearer ' + RAP_GENIUS}).json()
                for i in range(3):
                     if(r['response'] and r['response']['hits'] and r['response']['hits'][i]):
                        #pp.pprint(r['response']['hits'][i]['result']['full_title'])
                        response = response + str(i+1) + ". " + r['response']['hits'][i]['result']['full_title'] + "\n"
                if response == "":
                    response = "Couldnt find anything on rap genius"
                bot.sendMessage(chat_id=chat_id, text=response)


            elif (words[0] == "/help"):
                response = "The commands you can type are: \n1. '/all {{message}}' to send a message with everyone mentioned\n2. '/cs {{message}}' or '/play' or '/ow' to send a message with people who play cs/ow mentioned\n3. '/urban {{term}}' to define a term in urban dictionary\n 4. '/wolf {{expression}}' to evaluate an expression using wolframalpha\n 5. '/song {{query}}' to find the top 3 songs in rap genius for your query.\n"
                bot.sendMessage(chat_id=chat_id, text=response)
            elif (words[0] == "/test"):
                response = "Test message for @" + str(requester)
                bot.sendMessage(chat_id=chat_id, text=response)                
            elif (words[0] == "/id"):
                bot.sendMessage(chat_id=chat_id, text="ID: " + str(chat_id))
            else:
                response = words[0].strip(
                ) + " is not a recognized command, ask shameel to make it or stop trying dumb crap"
                bot.sendMessage(chat_id=chat_id, text=response)


    return update_id