Пример #1
0
def google_search(query1, query2):
    if (not os.environ.get('PYTHONHTTPSVERIFY', '') and
            getattr(ssl, '_create_unverified_context', None)):
        ssl._create_default_https_context = ssl._create_unverified_context
    search_result1 = search(query1, num_results=1)
    search_result2 = search(query2, num_results=1)
    if len(search_result1)>=1 and len(search_result2)>=1:
        return search_result1[0][1], search_result2[0][1]
    else:
        print("there is a problem with google search API.")
        sys.exit()
Пример #2
0
def google_search(query, site='straitstimes.com'):
    """Google search.

    Args:
        query (str): search query.
        site (str): url of website to search from. Defaults to ST.com.

    Returns:
        The search results if successful. Limited to 5 results.
    """
    init_results = list()
    retry = 0
    while len(init_results) == 0:
        searching = search(f'{query} site:{site}', num_results=10)
        init_results += searching
        retry += 1
        if retry == 3:
            return

    results = list()

    # return only articles that have the h1 heading tag,
    # else skip over the article
    for (headline, url) in init_results:
        try:
            headline = get_h1_text(url)
            results.append((headline, url))
        except AttributeError:
            pass

    return results[:5]
Пример #3
0
def google(msg):
    if msg.get('text'):
        if msg['text'].startswith('!s'):
            input_str = msg['text'][3:]
            if input_str == '':
                bot.sendMessage(msg['chat']['id'],
                                '*Use:* `/s or !g <search query>`',
                                parse_mode='Markdown',
                                reply_to_message_id=msg['message_id'])
            else:
                sent = bot.sendMessage(
                    msg['chat']['id'],
                    '*Processing your request..... 🔁*',
                    'Markdown',
                    reply_to_message_id=msg['message_id'])['message_id']
                start = datetime.now()
                req = search(input_str, num_results=GLOBAL_LIMIT)
                x = ''
                for text, url in req:
                    x += "  🔎 [{}]({}) \n\n".format(text, url)
                end = datetime.now()
                ms = (end - start).seconds
                bot.editMessageText(
                    (msg['chat']['id'], sent),
                    "searched Google for {} in {} seconds. \n\n{}".format(
                        input_str, ms, x),
                    'Markdown',
                    disable_web_page_preview=True)
Пример #4
0
def searchError(myError):
  print(myError)
  print("Error found, searching for solution...\n\n\n\n")
  thisSearch = search(myError)
  thisUrl = thisSearch[0][1]
  print(thisUrl)
  webbrowser.open(thisUrl)
def get_url_string(query):
    url_string = ""
    results = search(query, num_results=3)
    for url_iter in results:
        if url_iter[1].startswith('https://www.gamestop.com'):
            url_string = url_iter[1]
            return url_string
    return url_string
Пример #6
0
def google_search():
    form = GoogleSearchForm()
    raw_data = []
    if request.method == 'POST':
        keyword = form.keyword.data
        raw_data = [url for url in search(keyword.casefold(), num_results=10)]
        return render_template('google_search.html', form = form, raw_data = raw_data)
    return render_template('google_search.html', form = form)
Пример #7
0
	def search_(keyword,amount=3):
	    title=[]
	    j=1
	    for u in search(keyword):
	        title.append(u)
	        if j==amount:
	            break
	        j+=1   
	    return title
def search_keywords(key_list, type):
	N = len(key_list)
	key_list=[ 'solution scoutingit', 'keyword list', 'search', 'information.the end user' , 'relevance ’', 'tool', 'solution scouting.the list', '95% accuracy expected.it', 'keyword', 'performed.the end user', 'tool /application', 'controlledthe search', 'challenge uploaded', '‘ extent',  'information', 'web.the information']
	N = len(key_list)
	
	if(type == 1):
		results = []
		for j in range(0, N, 3):
			search_query = str(key_list[j])+' '+str(key_list[(j+1)%N])+' '+str(key_list[(j+2)%N])
			res = search(search_query, num_results = 5)
			res_tup = (search_query, res)
			results.append(res_tup)
			break
	elif(type == 2):
		results = []
		for j in range(0, N, 3):
			search_query0 = str(key_list[j])+' '+str(key_list[(j+1)%N])
			search_query1 = search_query0 +' '+ str(key_list[(j+2)%N])
			search_query2 = search_query1 +' '+ str(key_list[(j+3)%N])

			res_tup0 = (search_query0, search(search_query0, num_results = 5))
			res_tup1 = (search_query1, search(search_query1, num_results = 5))
			res_tup2 = (search_query2, search(search_query2, num_results = 5))
			
			results.append(res_tup0)
			results.append(res_tup1)
			results.append(res_tup2)
	elif(type == 3):
		results = []
		for j in range(0, N, 3):
			search_query0 = str(key_list[j])
			search_query1 = search_query0 +' '+	str(key_list[(j+1)%N])
			search_query2 = search_query0 +' '+ str(key_list[(j+2)%N])
			search_query3 = search_query1 +' '+ str(key_list[(j+3)%N])
			search_query3 = search_query1 +' '+ str(key_list[(j+4)%N])
			
			res_tup0 = (search_query0, search(search_query0, num_results = 5))
			res_tup1 = (search_query1, search(search_query1, num_results = 5))
			res_tup2 = (search_query2, search(search_query2, num_results = 5))
			res_tup3 = (search_query3, search(search_query3, num_results = 5))
			res_tup4 = (search_query4, search(search_query4, num_results = 5))

			results.append(res_tup0)
			results.append(res_tup1)
			results.append(res_tup2)
			results.append(res_tup3)
			results.append(res_tup4) 
	print(results)
	return results
Пример #9
0
def getInitJSON(Url):
    ## BEGIN BUILDING INITIAL ARTICLE
    article = Article(Url.strip())  # Instantiate article
    article.download()  # Required
    article.parse()  # Required

    title = article.title
    # for counter, _ in enumerate (title[::-1]):
    #     if (title[counter] == '-'):
    #         title = title[:counter]
    #         break

    author_head = article.authors  ## Sometimes this fnc. does not work
    if len(author_head) == 0:
        author_head = getAuthor(article)  # Try again w my fnc
    else:
        author_head = article.authors[0]

    publish_date = article.publish_date
    img_src = article.top_image
    summary = article.summary.strip()
    text = article.text.strip()
    summary = summarize(text)

    try:
        article_data['title'] = title
        article_data['author'] = author_head
        # datetime objs are not serializable
        article_data['publish_date'] = publish_date.strftime("%Y-%m-%d")
        article_data['img_src'] = img_src
        article_data['text'] = text
    except AttributeError:
        pass  # This is fine
    ## END BUILDING INITIAL ARTICLE

    with open('modules/json/init.json', 'w') as outfile:
        json.dump(article_data, outfile)

    if text is not None or text != '':
        summarize(text)

    # Sentiment analysis
    analyze(text)

    ## Search google for related articles/links
    json_results = {}
    results = search(title, num_results=4)
    for result in results:
        json_results.update({result[0]: result[1]})

    with open('modules/json/relatedLinks.json', 'a') as outfile:
        json.dump(json_results, outfile)
Пример #10
0
 def search(self, mask, channel, args):
     """Use google to look up words or phrases.
         %%search [<word>...]"""
     if args['<word>']:
         udict = search(" ".join(args['<word>']))
         if udict:
             udict = udict[0]
             self.bot.privmsg(
                 channel, "\x02{}  \x0F--  {}".format(udict[0], udict[1]))
         else:
             self.bot.privmsg(channel, "Something went wrong?")
     else:
         self.bot.privmsg(channel, "I can't look for nothing!")
Пример #11
0
def get_articles():
    term = request.args.get('term')
    results = search(term,num_results=5)
    thislist = []

    for l in results:
        print("Resource: " + l[1])
        try:
            article = analyze(l[1])
            thislist.append({'url':l[1],'summary':article.summary,'keywords':article.keywords,'published date':article.publish_date})
        except:
            print("result Failed")
    jsonStr = json.dumps(thislist)
    return jsonify(results=thislist)
Пример #12
0
async def google_search(client, message):
    if len(message.text.split()) == 1:
        await message.edit("Usage: `google how to search from google`")
        return
    text = message.text.split(None, 1)[1]
    results = search(text)
    teks = "<b>Search results from</b> <code>{}</code>\n".format(text)
    if results == []:
        await message.edit("Please try again later:\n`{}`".format(text),
                           parse_mode="markdown")
        return
    for x in range(len(results)):
        teks += '<b>{}.</b> <a href="{}">{}</a>\n'.format(
            x + 1, results[x][1], results[x][0])
    await message.edit(teks, parse_mode="html", disable_web_page_preview=True)
Пример #13
0
async def _(event):
    if event.fwd_from:
        return
    start = datetime.now()
    await event.edit("Processing ...")
    input_str = event.pattern_match.group(1) # + " -inurl:(htm|html|php|pls|txt) intitle:index.of \"last modified\" (mkv|mp4|avi|epub|pdf|mp3)"
    search_results = search(input_str, num_results=Config.GOOGLE_SEARCH_COUNT_LIMIT)
    output_str = " "
    for text, url in search_results:
        output_str += " 👉🏻  [{}]({}) \n\n".format(text, url)
    end = datetime.now()
    ms = (end - start).seconds
    await event.edit("searched Google for {} in {} seconds. \n{}".format(input_str, ms, output_str), link_preview=False)
    await asyncio.sleep(5)
    await event.edit("Google: {}\n{}".format(input_str, output_str), link_preview=False)
Пример #14
0
def google_search(question):
    first_page = search(question, 1)

    print('ques: ', question)
    print('page',len(first_page.results[0]))
    top_three_result = []
    for i in first_page:
        if len(top_three_result)>1:
            break
        top_three_result.append(i.description)

    first_search = ''.join(top_three_result).encode('ascii','replace')
    #print(first_page)

    #print('first answer: ',first_search.decode("utf-8")[0:299])
    return first_search.decode("utf-8")
Пример #15
0
def main():
    global isClipboard
    arg_c = len(argv)
    if arg_c <= 1:
        return makeReturn([])
    query = argv[1]
    if not query:
        return makeReturn([])
    results = search(query, num_results=10)
    items = []
    if len(results) == 0:
        items.append(makeItem(query, 'Please try again after 20 seconds', 'RATE LIMIT EXCEEDED'))
    for r in results:
        items.append(makeItem(query, r[1], r[0]))
    # return back
    out = makeReturn(items)
    return json.dumps(out, indent=4, encoding='utf-8') + '\n' # WEIRD BUG
Пример #16
0
    def __init__(self, selected, level):
        QWidget.__init__(self)

        self.setGeometry(300, 300, 300, 220)
        self.selected = selected
        self.level = level
        layout = QVBoxLayout()
        layout1 = QHBoxLayout()
        self.e1 = QLineEdit()
        layout.addWidget(self.e1)
        layout1.addStretch()
        layout.addLayout(layout1)
        self.listWidget = QListWidget()
        self.listWidget.setVisible(True)
        layout.addWidget(self.listWidget)

        self.listWidget.itemClicked.connect(self.Clicked)

        j = 0
        str3 = ''
        str4 = ''
        self.collect = []
        for i in self.selected:
            j = (j + 1) % 3
            str3 = str3 + str(i)
            if (j == 0):
                r = s.search(str3, num_results=20)
                for k in r:
                    if ("tata innoverse" in k[0]):
                        continue
                    self.collect.append(k)
                    str4 = str4 + str(k[0])
                    temp1 = QListWidgetItem(str(k[0]))
                    temp1.setTextColor(QColor('#000000'))
                    temp1.setFont(QFont('SansSerif', 14))
                    self.listWidget.addItem(temp1)

                temp1 = QListWidgetItem("keywords: " + str4)
                temp1.setTextColor(QColor('#000000'))
                temp1.setFont(QFont('SansSerif', 14))
                self.listWidget.addItem(temp1)

        self.setLayout(layout)
        self.setWindowTitle("Surrogator")
        self.showMaximized()
        self.show()
Пример #17
0
 def func(self):
     try:
         num = 1
         n = [int(s) for s in self.text.split() if s.isdigit()]
         t = self.text
         if len(n) > 0:
             num += n[len(n) - 1]
             t = self.text[0:self.text.find(str(num)) - 1]
         _str = t + ':\n'
         i = 0
         results = search(t, num_results=num)
         for result in results:
             res = list(result)
             _str += str(i + 1) + '. ' + res[0] + ': ' + res[1] + '\n'
             i += 1
         self.result['message'] = _str
         return True
     except Exception as e:
         self.result['message'] = str(e)
         return False
Пример #18
0
def lifecycle():
    global db

    queries = db.get_all_queries()

    for query_raw in queries:
        query = Query(json=query_raw)
        logger.debug(f'checking query {query.id}')

        logger.debug("performing search...")
        results = search(query.search, num_results=10)
        logger.info(f"query {query.id}: hits: {len(results)}")

        new_items = False

        for result_raw in results:
            #logger.debug(f'result_raw: {result_raw[0]}\t {result_raw[1]}')

            result = Result(id=str(uuid.uuid4()),
                            query=query.id,
                            timestamp=str(get_now_as_timestamp()),
                            title=result_raw[0],
                            content=result_raw[1])

            logger.debug(
                "result: " +
                json.dumps(result.as_dict(), indent=4, sort_keys=True))

            if not db.result_exists(result):
                logger.debug("result has not previously been recorded")
                new_items = True
                db.save_result(result)

        if new_items:
            feed_string = generate_feed_for_query(query)
            write_to_file_or_s3(uri=settings.RESULTS_FOLDER,
                                query=query,
                                body=feed_string)
Пример #19
0
def get_articles():
    term = request.args.get('term')
    results = search(term, num_results=5, news=True)
    thislist = []

    for l in results:
        print("Resource: " + l[1])
        try:
            article = analyze(l[1])
            print("Summary" + article.summary)
            print("TEXT____ " + article.text)
            #names = extract_entities(article.text)
            thislist.append({
                'url': l[1],
                'summary': article.summary,
                'keywords': article.keywords,
                'published date': article.publish_date
            })
        except Exception as ex:
            template = "An exception of type {0} occurred. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print(message)
    return jsonify(results=thislist)
Пример #20
0
 def test_results_count(self):
     res = search('Avi Aryan', num_results=30)
     self.assertTrue(len(res) > 10, 'Less than 11 results returned')
Пример #21
0
parser = argparse.ArgumentParser()
parser.add_argument("--target", help="Target", nargs='+')
if len(sys.argv)==1:
    parser.print_help(sys.stderr)
    sys.exit(1)
args = parser.parse_args()
argspace = ' '.join(args.target)
keyword = str(argspace)

ganti = "%s" % keyword
hasil = ganti.replace(" ", "_")

os.mkdir("output/%s" % hasil)

for url in search('"%s" site:t.me' % str(keyword), num_results=50):
    file = open("output/%s.txt" % str(keyword), 'a')
    file.write("%s\n" % url[1])
    file.close()


#createScreenshot
lis = [x.rstrip() for x in open('output/%s.txt' % str(keyword), 'r').readlines() if len(x.rstrip())]
for link in lis:
	rndm = random.random()
	os.system("wget -nH --cut-dirs=1 --output-document=output/%s/%s.html --convert-links %s" % (hasil, str(rndm), link))
	os.system("ls output/%s/ > output/%s.txt" % (hasil, hasil))

#Createiframe
lis = [x.rstrip() for x in open('output/%s.txt' % hasil, 'r').readlines() if len(x.rstrip())]
for frame in lis:
Пример #22
0
import codecs
from gsearch.googlesearch import search

# results = search('Github')
results = search('Github', num_results=100)

# print(results)

file = codecs.open("result.txt", "w", "utf-8")

for item in results:

    # It will not works on windows OS : utf8 problem...
    # https://stackoverflow.com/questions/16346914/python-3-2-unicodeencodeerror-charmap-codec-cant-encode-character-u2013-i
    # https://github.com/llSourcell/twitter_sentiment_challenge/issues/1
    # print(item)
    # print(item[0])
    # print(item[1])
    # print("----------------")

    file.write(item[0])
    file.write("\n")
    file.write(item[1])
    file.write("\n----------------\n")

file.close()
Пример #23
0
async def on_message(message):

    #Greetings and Cookies and Random Stuff

    if message.content.upper().startswith('HELLO!'):
        userID = message.author.id
        await client.send_message(message.channel, "Hello <@%s>!" % (userID))
    if message.content.upper().startswith('YO!'):
        userID = message.author.id
        await client.send_message(message.channel,
                                  "Yo to you too, <@%s>!" % (userID))
    if message.content.upper().startswith('WAZZ POPPIN!'):
        userID = message.author.id
        await client.send_message(message.channel,
                                  "Not much, <@%s>!" % (userID))
    if message.content.upper().startswith('COOKIE!'):
        cookies = [
            'choco chip', 'vanilla', 'caramel', 'butterscotch', 'almond',
            'chunky coconut', 'marmalade', 'choco lava', 'butter'
        ]
        index_cookie = random.randint(0, len(cookies) - 1)
        cookie_send = cookies[index_cookie]
        cookie_message = '{} , {} gave you a nice {} cookie :cookie: !'.format(
            message.content.split(' ')[1], message.author.mention, cookie_send)
        await client.send_message(message.channel, cookie_message)

    #Movies,TV Series and Video Games plot summaries

    if message.content.upper().startswith('MOVIE!'):
        userID = message.author.id
        args = message.content.split(" ")
        moviename = " ".join(args[1:])
        movie = ia.search_movie(moviename)
        movie1 = movie[0]
        movieid = ia.get_imdbID(movie1)
        movieinfo = ia.get_movie(movieid)
        plot = movieinfo['plot'][0]
        embed = discord.Embed(title='PLOT SUMMARY',
                              description='',
                              colour=discord.Colour.teal())
        embed.add_field(name=moviename, value=plot, inline=False)
        await client.send_message(message.channel, embed=embed)

    #Wikipedia Search

    if message.content.upper().startswith('WIKI!'):
        args = message.content.split(" ")
        item_search_title = " ".join(args[1:])
        item_summary = wk.summary(item_search_title, sentences=4)
        embed = discord.Embed(title='Wikipedia Summary',
                              description='',
                              colour=discord.Colour.teal())
        embed.add_field(name=item_search_title.capitalize(),
                        value=item_summary,
                        inline=False)
        await client.send_message(message.channel, embed=embed)

    #Server Info

    # 1.) Roles information

    if message.content.upper().startswith('ROLES!'):
        server = client.get_server(os.getenv('SERVER_ID'))
        roles_list = server.role_hierarchy
        for role in roles_list:
            if not role.is_everyone:
                embed = discord.Embed(title=role.name,
                                      description='',
                                      colour=role.colour)
                await client.send_message(message.channel, embed=embed)

    # 2.) Server information

    if message.content.upper().startswith('INFO!'):
        server = client.get_server(os.getenv('SERVER_ID'))
        people_count = server.member_count
        time_of_creation = server.created_at
        owner_name = server.owner.name
        icon = server.icon_url
        embed = discord.Embed(title=server.name,
                              description='SERVER INFO',
                              colour=discord.Colour.teal())
        embed.set_thumbnail(url=icon)
        embed.add_field(name='Member count:',
                        value='Humans : {}\nBots : 1'.format(people_count - 1),
                        inline=False)
        embed.add_field(name='Time of Origin:',
                        value='{}-{}-{}'.format(time_of_creation.day,
                                                time_of_creation.month,
                                                time_of_creation.year),
                        inline=False)
        embed.add_field(name='Owner:', value=owner_name, inline=False)
        await client.send_message(message.channel, embed=embed)

    # 3.) Bar Plot depicting statuses of people

    if message.content.upper().startswith("STATUS!"):
        server = client.get_server(os.getenv('SERVER_ID'))
        if os.path.isfile('stats.png') == "True":
            os.remove("stats.png")
        mem_list = server.members
        online = 0
        offline = 0
        idle = 0
        do_not_disturb = 0
        invisible = 0
        for mem in mem_list:
            if str(mem.status) == "online":
                online += 1
            elif str(mem.status) == "offline":
                offline += 1
            elif str(mem.status) == "idle":
                idle += 1
            elif str(mem.status) == "dnd":
                do_not_disturb += 1
            else:
                invisible += 1
        stats = ('Online', 'Offline', 'Idle', 'Do Not Disturb')
        y_pos = np.arange(len(stats))
        status_mems = [online, offline, idle, do_not_disturb]
        plt.bar(y_pos,
                status_mems,
                align='center',
                alpha=0.5,
                color=['green', 'grey', 'yellow', 'red'])
        plt.xticks(y_pos, stats)
        plt.yticks(np.arange(0, len((mem_list)), step=1))
        plt.ylabel('Members')
        plt.title('Status Statistics')
        plt.savefig('stats.png')
        await client.send_file(message.channel, 'stats.png')
        plt.clf()

    #Moderation Commands

    # 1.) Kick a user
    if message.content.upper().startswith("KICK!"):
        server = client.get_server(os.getenv('SERVER_ID'))
        flag = False
        if message.author.server_permissions.kick_members == True and message.author.server_permissions.ban_members == True:
            flag = True
        if flag == True:
            for mem_ber in server.members:
                if mem_ber.mentioned_in(message) == True:
                    await client.kick(mem_ber)
                    embed = discord.Embed(
                        title='Kicked',
                        description="{} has been kicked from the server".
                        format(mem_ber.mention),
                        colour=discord.Colour.red())
                    await client.send_message(message.channel, embed=embed)
                    break

        else:
            embed = discord.Embed(
                title='Warning',
                description='{} You are not allowed to use this command!'.
                format(message.author.mention),
                colour=discord.Colour.red())
            await client.send_message(message.channel, embed=embed)
    # 2.) Ban a user
    if message.content.upper().startswith("BAN!"):
        server = client.get_server(os.getenv('SERVER_ID'))
        flag = False
        if message.author.server_permissions.kick_members == True and message.author.server_permissions.ban_members == True:
            flag = True
        if flag == True:
            for mem_ber in server.members:
                if mem_ber.mentioned_in(message) == True:
                    await client.ban(mem_ber, 0)
                    embed = discord.Embed(
                        title='Banned',
                        description="{} has been banned from the server".
                        format(mem_ber.mention),
                        colour=discord.Colour.red())
                    await client.send_message(message.channel, embed=embed)
                    break

        else:
            embed = discord.Embed(
                title='Warning',
                description='{} You are not allowed to use this command!'.
                format(message.author.mention),
                colour=discord.Colour.red())
            await client.send_message(message.channel, embed=embed)

    #Bot Commands Help

    if message.content.upper().startswith('HELP!'):
        embed = discord.Embed(
            title='SPARKY TO YOUR RESCUE!',
            description=
            'COMMANDS [Note that the commands are case insensitive.] -->',
            colour=discord.Colour.teal())
        embed.add_field(name='help!', value='Gives this list', inline=False)
        embed.add_field(name='psrules!',
                        value='Rules of Practice Sessions',
                        inline=False)
        embed.add_field(name='modhelp!',
                        value='Moderation Commands',
                        inline=False)
        embed.add_field(name='translatehelp!',
                        value='Translation Commands',
                        inline=False)
        embed.add_field(name='lrhelp!',
                        value='Language Based Roles Commands',
                        inline=False)
        embed.add_field(name='calchelp!',
                        value='Calculator Commands',
                        inline=False)
        embed.add_field(name='servhelp!',
                        value='Server Commands',
                        inline=False)
        embed.add_field(name='funhelp!', value='Fun Commands', inline=False)
        embed.add_field(name='utilhelp!',
                        value='General Utility Commands help',
                        inline=False)
        await client.send_message(message.channel, embed=embed)

    # General Utility Commands

    if message.content.upper().startswith('UTILHELP!'):
        embed = discord.Embed(
            title='General Utility Help',
            description=
            'General Commands that dont belong in any other categories',
            colour=discord.Color.dark_grey())
        embed.add_field(name='stackov! Query',
                        value='Search for solutions to programming doubts.',
                        inline=False)
        embed.add_field(name='embed! text to be embedded',
                        value='Embeds text.',
                        inline=False)
        await client.send_message(message.channel, embed=embed)

    #Server Related Commands

    if message.content.upper().startswith('SERVHELP!'):
        embed = discord.Embed(
            title='Server Commands',
            description=
            'COMMANDS [Note that the commands are case insensitive.] -->',
            colour=discord.Colour.gold())
        embed.add_field(name='roles!',
                        value='Gives all the roles present in the server.',
                        inline=False)
        embed.add_field(name='info!', value='Gives server info.', inline=False)
        embed.add_field(
            name='status!',
            value=
            'Gives a plot depicting the statuses of people on the server.',
            inline=False)
        embed.add_field(name='profile!',
                        value='Check out your profile card.',
                        inline=False)
        embed.add_field(name='profile mention member!',
                        value='Check out profile card of any member.',
                        inline=False)
        embed.add_field(name='ping!', value='Ping Sparky.', inline=False)
        await client.send_message(message.channel, embed=embed)

    #Fun Commands

    if message.content.upper().startswith('FUNHELP!'):
        embed = discord.Embed(
            title='Fun Commands',
            description=
            'COMMANDS [Note that the commands are case insensitive.] -->',
            colour=discord.Colour.magenta())
        embed.add_field(
            name='wiki!',
            value='Gives brief summary from Wikipedia of the queried item',
            inline=False)
        embed.add_field(name='coin! type heads or tails',
                        value='Make Sparky toss a coin and see if you win',
                        inline=False)
        embed.add_field(name='slot!',
                        value='Test your luck on Sparky\'s slot machine!',
                        inline=False)
        embed.add_field(name='joke!',
                        value='Cheeky and nerdy Chuck Norris jokes',
                        inline=False)
        embed.add_field(
            name='movie! name of Movie / TV Series /  Video Game',
            value='Gives the plot summary of the Movie/ TV series / Video Game',
            inline=False)
        embed.add_field(name='hello! / yo! / wazz poppin!',
                        value='Sparky says hi to you',
                        inline=False)
        embed.add_field(name='cookie! mention user',
                        value='Give someone a delicious cookie',
                        inline=False)
        embed.add_field(name='sparkygif! gif topic',
                        value='Posts a GIF on the mentioned topic',
                        inline=False)
        embed.add_field(name='poll! item1-without-spaces item2-without-spaces',
                        value='Creates a 2 item poll',
                        inline=False)
        embed.add_field(name='trivia!',
                        value='Answer Sparky\'s CS trivia questions!',
                        inline=False)
        await client.send_message(message.channel, embed=embed)

    #MOD Commands Help

    if message.content.upper().startswith('MODHELP!'):
        if message.author.server_permissions.kick_members == True and message.author.server_permissions.ban_members == True:
            embed = discord.Embed(title='MOD COMMANDS',
                                  description='Can be used only by Admins.',
                                  colour=discord.Colour.red())
            embed.add_field(name='purge! number of messages',
                            value='Purges through a given number of messages.',
                            inline=False)
            embed.add_field(name='kick! user',
                            value='Kicks the mentioned user from the server.',
                            inline=False)
            embed.add_field(name='ban! user',
                            value='Bans the mentioned user from the server.',
                            inline=False)
            await client.send_message(message.channel, embed=embed)
        else:
            embed = discord.Embed(
                title='Warning',
                description='{} You are not allowed to use this command!'.
                format(message.author.mention),
                colour=discord.Colour.red())
            await client.send_message(message.channel, embed=embed)

    #Practice Session Rules

    if message.content.upper().startswith('PSRULES!'):
        channel_CP = client.get_channel(os.getenv('CP_CHANNEL_ID'))
        role_id_list = []
        for role in message.server.roles:
            if role.name.upper() == 'PROGRAMMERS':
                role_id_list.append(role.mention)
            if role.name.upper() == 'CODERS':
                role_id_list.append(role.mention)
        embed = discord.Embed(
            title='Practice Session Rules',
            description='To be followed by everyone who is participating',
            colour=discord.Colour.red())
        embed.add_field(
            name='Rule-1',
            value='Post your solutions in {} using appropriate discord markdown.'
            .format(channel_CP),
            inline='False')
        embed.add_field(
            name='Rule-2',
            value=
            'If you have a doubt, ping anyone of the support staff mentioned below. Don\'t ping the entire role',
            inline='False')
        embed.add_field(
            name='Rule-3',
            value=
            'Try to make your code as efficient as possible. If you don\'t know about efficiency, leave this point.',
            inline='False')
        embed.add_field(name='Rule-4',
                        value='Do not cheat or copy.',
                        inline='False')
        embed.add_field(
            name='Rule-5',
            value=
            'Use logic along with the in-built functions to get the most output.',
            inline='False')
        embed.add_field(
            name='Rule-6',
            value=
            'Use C++ / C /Python / Java. If you feel excited, use Haskell or Erlang at your own risk.',
            inline='False')
        embed.add_field(
            name='Link for Discord Markup',
            value=
            'https://support.discordapp.com/hc/en-us/articles/210298617-Markdown-Text-101-Chat-Formatting-Bold-Italic-Underline-',
            inline='False')
        embed.add_field(name='Support Staff',
                        value=role_id_list[0] + '\n' + role_id_list[1],
                        inline='False')
        await client.send_message(message.channel, embed=embed)
    #PING

    if message.content.upper().startswith('PING!'):
        start = time.time() * 1000
        msg = await client.send_message(message.channel, 'PONG! :ping_pong:')
        end = time.time() * 1000
        await client.edit_message(message=msg,
                                  new_content=':ping_pong: `{} ms`'.format(
                                      '{0:.3f}'.format(end - start)))

    #Coin Flip Game
    if message.content.upper().startswith('COIN!'):
        args = message.content.split(" ")
        result_list = ["Heads", "Tails"]
        choice = random.randint(0, 1)
        if args[1].upper() == result_list[choice].upper():
            result = "{} it is! You win!".format(result_list[choice])
            embed = discord.Embed(title='Coin Flip',
                                  description=result,
                                  colour=discord.Colour.teal())
            await client.send_message(message.channel, embed=embed)
        else:
            result = " Uh oh, its {}! Better luck next time!".format(
                result_list[choice])
            embed = discord.Embed(title='Coin Flip',
                                  description=result,
                                  colour=discord.Colour.teal())
            await client.send_message(message.channel, embed=embed)

    #Slot Machine Game
    if message.content.upper().startswith('SLOT!'):
        result_list = [':apple:', ':pear:', ':tangerine:']
        result_list2 = [':grapes:', ':strawberry:', ':cherries:']
        result_list3 = [':hotdog:', ':icecream:', ':taco:']
        choice1 = random.randint(0, 2)
        choice2 = random.randint(0, 2)
        choice3 = random.randint(0, 2)
        e11 = result_list[choice1]
        e12 = result_list[choice2]
        e13 = result_list[choice3]
        e21 = result_list2[choice1]
        e22 = result_list2[choice2]
        e23 = result_list2[choice3]
        e31 = result_list3[choice1]
        e32 = result_list3[choice2]
        e33 = result_list3[choice3]
        result = e11 + " | " + e12 + " | " + e13 + "\n" + e21 + " | " + e22 + " | " + e23 + "\n" + e31 + " | " + e32 + " | " + e33
        row1 = False
        row2 = False
        row3 = False
        row_count = 0
        if (e11 == e12) and (e12 == e13) and (e13 == e11):
            row1 = True
            row_count += 1
        if (e21 == e22) and (e22 == e23) and (e23 == e21):
            row2 = True
            row_count += 1
        if (e31 == e32) and (e32 == e33) and (e33 == e31):
            row3 = True
            row_count += 1
        if row_count == 0:
            res_mes = "Better luck next time!"
        if row_count == 1:
            res_mes = "You got 1 row! Nice work!"
        if row_count == 2:
            res_mes = "You got 2 rows! Awesome!"
        if row_count == 3:
            res_mes = "Hattrick!"
        embed = discord.Embed(title='Slot Machine',
                              description=result,
                              colour=discord.Colour.teal())
        embed.add_field(name='Result', value=res_mes, inline=False)
        await client.send_message(message.channel, embed=embed)

    #Joke

    if message.content.upper().startswith('JOKE!'):
        l = requests.get('http://api.icndb.com/jokes/random?limitTo=[nerdy]')
        l.text.split(' ')
        joke = eval(l.text)['value']['joke']
        embed = discord.Embed(title='Joke',
                              description=joke,
                              colour=discord.Colour.blue())
        await client.send_message(message.channel, embed=embed)

    #Purge Deleting Messages

    if message.content.upper().startswith('PURGE!'):
        flag = False
        if message.author.server_permissions.kick_members == True and message.author.server_permissions.ban_members == True:
            flag = True
        if flag == True:
            args = int(message.content.split(' ')[1])
            print(args)
            await client.purge_from(message.channel, limit=args)
        else:
            embed = discord.Embed(
                title="Warning!",
                description='You are not allowed to use this command',
                colour=discord.Colour.red())
            await client.send_message(message.channel, embed=embed)

    #Language Based Roles Help

    if message.content.upper().startswith('LRHELP!'):
        embed = discord.Embed(title='Language Based Roles Help',
                              description='C/C++/Java/Python',
                              colour=discord.Colour.purple())
        embed.add_field(name='LANGROLE! name of role from above 4',
                        value='Adds the role',
                        inline=False)
        embed.add_field(name='LANGROLEREMOVE! removes role from above 4',
                        value='Removes the role',
                        inline=False)
        await client.send_message(message.channel, embed=embed)

    #Add Language Based Roles

    if message.content.upper().startswith('LANGROLE!'):
        lang_role_channel = client.get_channel(os.getenv('LANG_ROLE_ID'))
        if message.channel.id == lang_role_channel.id:
            arg = message.content.split(' ')[1]
            server = client.get_server(os.getenv('SERVER_ID'))
            role_member = None
            if arg.upper() == 'C++' or arg.upper() == 'PYTHON' or arg.upper(
            ) == 'C' or arg.upper() == 'JAVA':
                for role in server.roles:
                    if role.name.upper() == arg.upper():
                        await client.add_roles(message.author, role)
                        role_member = role
                        break
                await client.delete_message(message)
                embed = discord.Embed(
                    title=message.author.name,
                    description='You have been alloted the {} role!'.format(
                        role_member.mention),
                    colour=role_member.colour)
                await client.send_message(message.channel, embed=embed)
            else:
                embed = discord.Embed(
                    title='WARNING',
                    description='You are not allowed to add this role.',
                    colour=discord.Colour.red())
                await client.send_message(message.channel, embed=embed)
        else:
            embed = discord.Embed(
                title='Warning',
                description='You can use this command only in {}'.format(
                    lang_role_channel.mention),
                colour=discord.Colour.red())
            await client.send_message(message.channel, embed=embed)

    #Remove Language Based Roles

    if message.content.upper().startswith('LANGROLEREMOVE!'):
        lang_role_channel = client.get_channel(os.getenv('LANG_ROLE_ID'))
        if message.channel.id == lang_role_channel.id:
            arg = message.content.split(' ')[1]
            server = client.get_server(os.getenv('SERVER_ID'))
            role_member = None
            if arg.upper() == 'C++' or arg.upper() == 'PYTHON' or arg.upper(
            ) == 'C' or arg.upper() == 'JAVA':
                for role in server.roles:
                    if role.name.upper() == arg.upper():
                        await client.remove_roles(message.author, role)
                        role_member = role
                        break
                await client.delete_message(message)
                embed = discord.Embed(
                    title=message.author.name,
                    description='You have removed the {} role!'.format(
                        role_member.mention),
                    colour=role_member.colour)
                await client.send_message(message.channel, embed=embed)
            else:
                embed = discord.Embed(
                    title='WARNING',
                    description='You are not allowed to remove this role.',
                    colour=discord.Colour.red())
                await client.send_message(message.channel, embed=embed)
        else:
            embed = discord.Embed(
                title='Warning',
                description='You can use this command only in {}'.format(
                    lang_role_channel.mention),
                colour=discord.Colour.red())
            await client.send_message(message.channel, embed=embed)

    #GIFs

    if message.content.upper().startswith('SPARKYGIF!'):
        g = safygiphy.Giphy()
        target = message.content.split(' ')[1]
        gif = g.random(tag=target)['data']['url']
        await client.send_message(message.channel, gif)

    #Profile

    if message.content.upper().startswith('PROFILE!'):
        server = client.get_server(os.getenv('SERVER_ID'))
        if message.content.upper() == "PROFILE!":
            name = message.author.name
            pfp = message.author.avatar_url
            joindate = message.author.joined_at
            roles = message.author.roles
            string = []
            for item in roles:
                if item.name != '@everyone':
                    string.append(item.mention)
            string = list(reversed(string))
            string = '  '.join(string)
            embed = discord.Embed(title='PROFILE',
                                  description=server.name.upper(),
                                  colour=discord.Colour.teal())
            embed.set_thumbnail(url=pfp)
            embed.add_field(name='Name:', value=name, inline='False')
            embed.add_field(name='Joined the server on:',
                            value='{}-{}-{}'.format(joindate.day,
                                                    joindate.month,
                                                    joindate.year),
                            inline='False')
            embed.add_field(name='Roles:', value=string, inline='False')
            await client.send_message(message.channel, embed=embed)
        else:
            for mem in server.members:
                if mem.mentioned_in(message) == True:
                    name = mem.name
                    pfp = mem.avatar_url
                    joindate = mem.joined_at
                    roles = mem.roles
                    string = []
                    for item in roles:
                        if item.name != '@everyone':
                            string.append(item.mention)
                    string = list(reversed(string))
                    string = '  '.join(string)
                    embed = discord.Embed(title='PROFILE',
                                          description=server.name.upper(),
                                          colour=discord.Colour.teal())
                    embed.set_thumbnail(url=pfp)
                    embed.add_field(name='Name:', value=name, inline='False')
                    embed.add_field(name='Joined the server on:',
                                    value='{}-{}-{}'.format(
                                        joindate.day, joindate.month,
                                        joindate.year),
                                    inline='False')
                    embed.add_field(name='Roles:',
                                    value=string,
                                    inline='False')
                    await client.send_message(message.channel, embed=embed)
                    break
    #Translate Commands

    if message.content.upper().startswith('TRANSLATE!'):
        args = ' '.join(message.content.split(' ')[2::])
        lang = message.content.split(' ')[1]
        translations = translator.translate(args, dest=lang)
        embed = discord.Embed(title='SPARKY TRANSLATE',
                              description='Sparky Translates for you!',
                              colour=discord.Colour.teal())
        embed.add_field(name='Original Message:', value=args, inline='False')
        embed.add_field(name='Translated Message:',
                        value=translations.text,
                        inline='False')
        await client.send_message(message.channel, embed=embed)

    if message.content.upper().startswith('TRANSLATELANGS!'):
        msg = dict(map(reversed, LANGUAGES.items()))
        args = message.content.split(' ')[1]
        languages = list(msg.keys())
        if args.lower() in languages:
            embed = discord.Embed(title=args.lower(),
                                  description='The Code is: {}'.format(
                                      msg[args.lower()]),
                                  colour=discord.Colour.teal())
            await client.send_message(message.channel, embed=embed)
        else:
            embed = discord.Embed(title='Warning!',
                                  description='This language is not available',
                                  colour=discord.Colour.teal())
            await client.send_message(message.channel, embed=embed)

    if message.content.upper().startswith('TRANSLATEHELP!'):
        embed = discord.Embed(title='Sparky Translation Help',
                              description='Commands',
                              colour=discord.Colour.teal())
        embed.add_field(name='translatelangs! language',
                        value='Gives the code of the language asked',
                        inline='False')
        embed.add_field(
            name='translate! languagecode message to be translated',
            value='Translates the given message into the selected language.',
            inline='False')
        await client.send_message(message.channel, embed=embed)

    #Calculator

    if message.content.upper().startswith('CALC!'):
        args = message.content.split(' ')
        res = 0
        if args[1].upper() == 'SIN':
            res = math.sin(math.radians(float(args[2])))
        elif args[1].upper() == 'COS':
            res = math.cos(math.radians(float(args[2])))
        elif args[1].upper() == 'TAN':
            res = math.tan(math.radians(float(args[2])))
        elif args[1].upper() == 'EXP':
            res = math.exp(float(args[2]))
        elif args[1].upper() == 'POW':
            res = math.pow(float(args[2]), float(args[3]))
        elif args[1].upper() == 'SQRT':
            if float(args[2]) >= 0:
                res = math.sqrt(float(args[2]))
            else:
                res = "Mathematical Error!"
        elif args[1].upper() == 'LOG':
            if float(args[2]) > 0 and float(args[3]) > 0:
                res = math.log(float(args[2]), float(args[3]))
            else:
                res = "Mathematical Error!"
        elif args[1].upper() == 'EVAL':
            s = ''.join(args[2:])
            res = eval(s)
        else:
            res = 'Wrong Command!'
        embed = discord.Embed(title='Sparky\'s Calculator',
                              description='Answer',
                              colour=discord.Colour.orange())
        embed.add_field(name=' '.join(args[1:]), value=res, inline='False')
        await client.send_message(message.channel, embed=embed)

    if message.content.upper().startswith('CALCHELP!'):
        embed = discord.Embed(title='Sparky\'s Calculator',
                              description='Quick Maths',
                              colour=discord.Colour.orange())
        embed.add_field(name='calc! sin/cos/tan angle',
                        value='Sine/Cosine/Tangent of the given angle',
                        inline='False')
        embed.add_field(name='calc! exp number',
                        value='Exp(number)',
                        inline='False')
        embed.add_field(name='calc! log value base',
                        value='Log of value to the given base',
                        inline='False')
        embed.add_field(name='calc! sqrt number',
                        value='Square root of number',
                        inline='False')
        embed.add_field(name='calc! pow number exponent',
                        value='Value of number raised to exponent',
                        inline='False')
        embed.add_field(name='calc! eval expression_without_spaces',
                        value='Value of the expression',
                        inline='False')
        await client.send_message(message.channel, embed=embed)

    #Poll

    if message.content.upper().startswith('POLL!'):
        args = message.content.split(' ')[1:]
        item1 = args[0]
        item2 = args[1]
        embed = discord.Embed(
            title='POLL',
            description='A poll has been created by {}!'.format(
                message.author.mention),
            colour=discord.Colour.blue())
        embed.add_field(name=':one: {}'.format(item1.upper()),
                        value='React with :one: to vote',
                        inline=False)
        embed.add_field(name=':two: {}'.format(item2.upper()),
                        value='React with :two: to vote',
                        inline=False)
        msg = await client.send_message(message.channel, embed=embed)
        await client.add_reaction(msg, '\U00000031\U000020e3')
        await client.add_reaction(msg, '\U00000032\U000020e3')

    # Stackoverflow Search

    if message.content.upper().startswith('STACKOV!'):
        args = ' '.join(message.content.split(' ')[1:])
        query = search('Stackoverflow ' + args)
        embed = discord.Embed(title='StackOverflow Search',
                              description='Results for the query',
                              colour=discord.Color.orange())
        print('Stackoverflow ' + args)
        for item in query:
            embed.add_field(name='-->', value=item, inline=False)
        await client.send_message(message.channel, embed=embed)

    # Embed Text

    if message.content.upper().startswith('EMBED!'):
        args = ' '.join(message.content.split(' ')[1:])
        embed = discord.Embed(title='Embedded by {}'.format(
            message.author.name),
                              description=args,
                              colour=discord.Color.dark_orange())
        await client.send_message(message.channel, embed=embed)

    #Trivia

    if message.content.upper().startswith("TRIVIA!"):
        req = requests.get(
            "https://opentdb.com/api.php?amount=1&category=18&type=multiple")
        texts = ast.literal_eval(req.text)
        question = texts["results"][0]["question"]
        cor_ans = texts["results"][0]["correct_answer"]
        incorrect_answers = texts["results"][0]["incorrect_answers"]
        incorrect_answers.append(cor_ans)
        answers_lis = incorrect_answers
        random.shuffle(answers_lis)
        embed = discord.Embed(
            title="CS TRIVIA by Sparky",
            description="Type a number between 1 and 4 to choose your answer.",
            colour=discord.Color.dark_teal())
        embed.add_field(name='Question', value=question, inline=False)
        embed.add_field(name=':one:', value=answers_lis[0], inline=False)
        embed.add_field(name=':two:', value=answers_lis[1], inline=False)
        embed.add_field(name=':three:', value=answers_lis[2], inline=False)
        embed.add_field(name=':four:', value=answers_lis[3], inline=False)
        await client.send_message(message.channel, embed=embed)
        msg = await client.wait_for_message(author=message.author,
                                            channel=message.channel)
        options = ["1", "2", "3", "4"]
        if msg.content in options:
            if answers_lis[int(msg.content) - 1] == cor_ans:
                embed = discord.Embed(
                    title="Correct Answer!",
                    description=
                    "{} has answered the question correctly, the answer is Option-{} : {}!"
                    .format(message.author.name, msg.content, cor_ans),
                    colour=discord.Color.green())
                await client.send_message(message.channel, embed=embed)
            else:
                embed = discord.Embed(
                    title="Wrong Answer!",
                    description=
                    "{} has answered the question wrong, the correct answer is Option-{} : {}!"
                    .format(message.author.name,
                            answers_lis.index(cor_ans) + 1, cor_ans),
                    colour=discord.Color.red())
                await client.send_message(message.channel, embed=embed)
        else:
            embed = discord.Embed(
                title="Warning!",
                description=
                "Type a number between 1 and 4 only (both inclusive)!",
                colour=discord.Color.red())
            await client.send_message(message.channel, embed=embed)
Пример #24
0
async def on_message(message):

    ########### HELP ###########
    if message.content == helpCommand:
        response = fetchThis.helpThing(message)
        this = await client.send_message(message.channel, embed=response)
        await client.add_reaction(this, '\U0001F44D')
        await client.add_reaction(this, '👎')

    if message.content.startswith(codeCommand):
        response = fetchThis.codeType(message, codeCommand)
        await client.delete_message(message)
        this = await client.send_message(message.channel, response)
        await client.add_reaction(this, '\U0001F44D')
        await client.add_reaction(this, '👎')

########### User Managment ###########
##### Role Request Information ####
    if message.content.startswith(roleInfoCommand):
        if roleChannel in message.channel.name:
            response = fetchThis.roleInfo()
            await client.send_message(message.channel, embed=response)

    #### Adding a role ##
    if message.content.startswith(addRoleCommand):
        if roleChannel in message.channel.name:
            for role in message.server.roles:
                if role.name in message.content:
                    if role.name == 'support':
                        await client.send_message(
                            message.channel,
                            'Sorry, not sorry but.. I couldnt perform this '
                            'command. \n ' + '```' + message.content + '```')
                    else:
                        await client.send_typing(message.channel)
                        await client.add_roles(message.author, role)
                        response = fetchThis.accessAdded(role.name)
                        return await client.send_message(message.author,
                                                         embed=response)

            await client.send_message(
                message.channel,
                'Sorry, not sorry but.. I couldnt perform this '
                'command. \n ' + '```' + message.content + '```')
    #### Removing a role ##
    if message.content.startswith(removeRoleCommand):
        if roleChannel in message.channel.name:
            for role in message.server.roles:
                if role.name in message.content:
                    await client.send_typing(message.channel)
                    await client.remove_roles(message.author, role)
                    return await client.send_message(
                        message.channel, 'Okay, ' + message.author.name +
                        'I have successfully removed you from \n ```Role: ' +
                        role.name + '```')

            await client.send_message(
                message.channel,
                'Sorry, not sorry but.. I couldnt perform this '
                'command. \n ' + '```' + message.content + '```')

############## Google Stuff ##############
    if searchCommand in message.content:
        from gsearch.googlesearch import search
        query = message.content.split()
        query.remove(searchCommand)
        results = search(str(query))  # returns 10 or less results
        result = []
        header = 'Thanks for using oogle, here are your results! \n ```\n'
        footer = '```'
        result = [footer] + result

        for each in results:
            eachResult = '\n The Title: ' + each[0] + ' \n Link: ' + each[
                1] + ' \n'
            result = [eachResult] + result

        result = [header] + result
        result = ' '.join(result)
        await client.send_message(message.channel, result)

############## AnonMessages ##############

    if message.content.startswith(anonCommand):
        await client.send_message(
            message.author,
            'What would you like to `Subject:` your confession?')

        subject = await client.wait_for_message(timeout=60.0,
                                                author=message.author)

        if subject is None:
            await client.send_message(
                message.author,
                '`Sorry` but your confession time `ran out` (`60 Seconds`).\n'
                'Please resubmit your confession and `fill out the subject line`.'
            )
        if subject.author == message.author:
            response = fetchThis.anonMessage(message, anonCommand,
                                             subject.content)
            for server in client.servers:
                for channel in server.channels:
                    if anonChannel == channel.name:
                        this = await client.send_message(channel,
                                                         embed=response)
                        await client.add_reaction(this, '\U0001F44D')
                        await client.add_reaction(this, '😂')
                        await client.add_reaction(this, '❤')
                        await client.add_reaction(this, '💔')
                        await client.add_reaction(this, '👎')


############## Server Management ##############

#### Kicking users ####
    if message.content.startswith(kickCommand):
        checkAuthority = configureThe.modAuthority(message)
        if checkAuthority is True:
            for user in message.mentions:
                response = fetchThis.kicked(message, user)
                await client.send_message(user, embed=response)
                this = await client.send_message(
                    message.channel,
                    user.name + ' err rip, bye felica. :unamused: ')
                await client.add_reaction(this, '\U0001F44D')
                await client.add_reaction(this, '👎')
                await client.kick(user)

    #### Banning Users ####
    if message.content.startswith(banCommand):
        checkAuthority = configureThe.adminAuthority(message)
        if checkAuthority is True:
            for user in message.mentions:
                response = fetchThis.banned(message, user)
            await client.send_message(user, embed=response)
            this = await client.send_message(
                message.channel,
                user.name + ' err rip, bye felica. :unamused: ')
            await client.add_reaction(this, '\U0001F44D')
            await client.add_reaction(this, '👎')
            await client.ban(user)

    #### Clear Messages ####
    if message.content.startswith(clearCommand):
        checkAuthority = configureThe.modAuthority(message)
        if checkAuthority is True:
            numOfMessages = message.content.split()
            numOfMessages.remove(clearCommand)
            numOfMessages = ' '.join(numOfMessages)
            count = 0
            async for msg in client.logs_from(message.channel):
                if count == int(numOfMessages):
                    return await client.send_message(
                        message.channel, 'Alright ' + message.author.mention +
                        '. I have removed ' + numOfMessages +
                        ' messages from this channel!')
                else:
                    await client.delete_message(msg)
                    count = count + 1
                    print(count)
Пример #25
0
def searchg():
    qr = input("Enter search term: ")
    ns = input("Enter max results: ")
    rs = search(qr,num_results = 10)
    print(rs)
Пример #26
0
def apisearchg(query,num):
    results = search(searchg, num_results=num)
    return results
Пример #27
0
 def test_unicode(self):
     res = search('君の名')
     self.assertTrue(len(res) > 0)
Пример #28
0
 def test_results_zero(self):
     res = search('dsjaksfajsdhkhawkehkajdwek')
     self.assertTrue(
         len(res) == 0, 'There was a result. What has this world come to?')
os.remove('data.txt')
#HN
print("HACKER NEWS: ")
try:
    f = open("data.txt", 'w')
    for story_id in hn.top_stories(limit=10):
        f.write(str(hn.get_item(story_id)))
finally:
    f.close()
analyze('data.txt')
os.remove('data.txt')
#Google Search
print("GOOGLE SEARCH FOR {}".format(searchTerm))
try:
    f = open("data.txt", 'w')
    results = search(searchTerm)
    f.write((str(results)))

finally:
    f.close()
analyze('data.txt')
os.remove('data.txt')
#CNN
print("TOP CNN ARTICLES:")
try:
    f = open("data.txt", 'w')
    results = news(3)
    f.write(str(results.get()))

finally:
    f.close()
Пример #30
0
from gsearch.googlesearch import search
results = search('Full Stack Developer')
print(results)