def __get_genius_data(self, query, genius_url): # get top google result is no genius_url provided urls = gsearch(f'site:genius.com {query} lyrics', stop=5) if genius_url is None else [genius_url] for url in urls: self.log("\tTrying URL", url) try: song_id, html = self.__fetch_page(url) # replace all <br> with new-lines html = re.sub(r'<br/?>', '\n', html) # try to get lyrics soup = BeautifulSoup(html, 'html.parser') try: lyrics = None l = re.compile(r'(?i)^lyrics') lyrics = soup.find('div', attrs={'class': l}).text.strip() except: self.log("\tFailed to fetch lyrics!") return (song_id, lyrics) except Exception as e: self.log(f'\t{e}') raise Exception('\tFailed to find the song on Genius.com!')
def find_genius_data(title, genius_url): urls = [genius_url] # get top google result is no genius_url provided if genius_url is None: urls = gsearch(f'site:genius.com {title}', stop=1) for url in urls: r = requests.get(url) html = r.text # get song_id key = re.search(r'"Song ID":[0-9]+', html).group() song_id = re.search(r'[0-9]+', key).group() # get lyrics lyrics = '' genre = '' try: soup = BeautifulSoup(html, 'html.parser') lyrics = soup.find('div', attrs={'class': 'lyrics'}).text.strip() genre = json.loads( soup.find('meta', attrs={ "itemprop": "page_data" })['content'])['dmp_data_layer']['page']['genres'][0] except Exception as e: print("Failed to fetch lyrics:", e) pass return (song_id, lyrics, genre)
def search_web(voix_user): for j in gsearch(voix_user, tld="fr", num=10, stop=5, pause=2): if 'youtube' in j: if 'channel' in j or 'user' in j: assistant_speaks("J'ai trouvé une chaîne Youtube") elif 'watch' in j: assistant_speaks("J'ai trouvé une vidéo Youtube") else: assistant_speaks("J'ai trouvé quelque chose sur Youtube") elif 'wikipedia' in j: if 'en.' in j: assistant_speaks("J'ai trouvé un article Wikipédia anglais") elif 'fr.' in j: assistant_speaks("J'ai trouvé un article Wikipédia français") else: assistant_speaks("J'ai trouvé un article Wikipédia") else: print(str(j)) url = j.split("//")[-1].split("/")[0].split('?')[0] assistant_speaks("J'ai trouvé le site " + str(url)) assistant_speaks("Est-ce que c'est ce que vous cherchez ?") ans = get_audio() if 'oui' in str(ans) or 'ouais' in str(ans): webbrowser.open(j, new=0, autoraise=True) sys.exit() sys.exit()
def search_web(self): # look for "genius" in results results = [] genius_query = "site:genius.com " + self.query for url in gsearch(genius_query): results.append(url) for link in results: if "genius" in link: self.url = link return link return None
def _googlesearch(self, query, **kwargs): """ simple google search """ # defaults defaults = {'stop': 100, 'user_agent': self.useragent} # merge kwargs = {**defaults, **kwargs} for url in gsearch(query, **kwargs): yield url return
def googleSearch(domain): print("\tGoogle:") googleResults = [] query = 'site:*.'+ domain + \ ' -https://' + domain + \ ' -https://www.' + domain + \ ' -http://' + domain + \ ' -http://www.' + domain for j in gsearch(query, tld='com', lang='en', num=100, start=0, stop=100, pause=2.0): googleResults.append(j) return googleResults
def search(self, search_term: str): # Searching lyrics for <search_term> for url in gsearch(search_term, tld='com.pk', lang='en', stop=10): for website in self.__websites: if website.accept(url): try: print("Lyrics found in {0.name}! ({0.url})".format( website)) return website.get_lyrics(url) except Exception as e: print(e) continue # Improve search accuracy (2nd try) if not search_term.find("lyrics"): return self.search(search_term + " lyrics") return None
def get_google(query, n_answers=3, best_so=False, mute=False, break_on_best=False): """ Prints links to the top hits on google given a search query (str) and returns a link to the top one. :param query: str, search query :param n_answers: int, number of max results to get :param best_so: bool, False. If true the 'best' result must be from SO :param mute: bool, False. If true the it doesn't print the results :param break_on_best: bool, False. If true the it stops after finding the best answer """ out = [ f"[{white}]Links to the top 3 results on [{lightsalmon}]google.com[/{lightsalmon}] for the error:\n" ] best = None for n, j in enumerate( gsearch( "python " + query, tld="co.in", num=n_answers, stop=n_answers, pause=0.3, )): out.append(f" [{ls}]{j}[/{ls}]\n") if best is None: if not best_so or "stackoverflow" in j: best = j if break_on_best: break if not mute: console.print(*out, "\n") return best
async def google(self, ctx, *, search: str): await ctx.channel.trigger_typing() for result in gsearch(search, num=1, pause=0.5, stop=1): await ctx.send(result)
def chatbot(message): original_message = message message = original_message.split() # Break message by space, if [0] == "/sum" sum = [1]+[2] if message[0] == "/sum": numbers = original_message.replace('/sum', '').split() s = 0 for x in numbers: c = int(x) s += c j = ' '.join(numbers) response = "Sum of Given Number " + str(s) elif message[0] == "/diff": response = int(message[2]) - int(message[1]) elif message[0] == "/multi": response = int(message[1]) * int(message[2]) elif message[0] == "/power": response = int(message[1])**int(message[2]) elif message[0] == "/sqrt": response = int(message[1])**(1 / 2) elif message[0] == "/cbrt": response = int(message[1])**(1 / 3) elif message[0] == "/fact": #try: factorial = 1 num = int(message[1]) if num < 0: response = "Sorry, factorial does not exist for negative numbers" elif num == 0: response = "The factorial of 0 is 1" else: for i in range(1, num + 1): factorial = factorial * i response = "The factorial of " + str(num) + " is " + str( factorial) #except: # response= "Error" elif message[0] == "/reword": l = message[0] r = l[::-1] if l == r: response = "Word is Palindrome!" else: response = "Word in not Palindrome!" elif message[0] == "/dict": response = "Meaning: " + str(dictionary.meaning( message[1])) + "<br><br>" + "Synonyms: " + str( dictionary.synonym( message[1])) + "<br><br>" + "Antonyms: " + str( dictionary.antonym(message[1])) elif message[0] == "/translate": try: tmessage = original_message.replace('/translate', '').splitlines() omessage = tmessage[1] translator = Translator(to_lang="hi") translation = translator.translate(omessage) response = "Your Translation: " + str(translation) except: response = "Failed to translate" elif message[0] == "/wiki": #c=message[1].lower() message.pop(0) message = "".join(message) response = str(wikipedia.summary(message, sentences=5)) elif message[0] == "/search": message.pop(0) message = "".join(message) response = "" for j in gsearch(message): response = str(response) + str(j) + str("\n") elif message[0] == "/jokes": url = urllib.request.urlopen( "https://official-joke-api.appspot.com/jokes/random") response = url.read().decode() elif message[0] == "/gen": message = "".join(message) n = message[0] password_characters = string.punctuation n1 = string.digits p1 = ''.join(random.choice(n1) for j in range(7)) p = ''.join(random.choice(password_characters) for i in range(4)) c = n[0].upper() + p + n[1:] + p1 response = str(c) elif message[0] == "/time": strTime = datetime.datetime.now().strftime("%H:%M:%S") response = "Sir Time is: " + str(strTime) #/addcontact #name #phone #email elif message[0] == "/addcontact": try: contact_details = original_message.replace('/addcontact', '').splitlines() name = contact_details[1] mobile = contact_details[2] email = contact_details[3] x = employee(name=name, mobile=mobile, email=email) x.save() response = "Contact added!" except: response = "Please send details in correct format as below:" response += "<br>/addcontact<br>Name<br>Phone<br>Email" elif message[0] == "/searchcontact": srch = message[1] if srch: match = employee.objects.filter( Q(name__icontains=srch) | Q(email__icontains=srch)) if match: response = "I got following results - <br><br>" for each_match in match: response += "Name: " + each_match.name + "<br>" response += "Mobile: " + each_match.mobile + "<br>" response += "Email: " + each_match.email + "<br><br>" else: response = "No contact found" elif message[0] == "/sendmail": try: email_detail = original_message.replace('/sendmail', '').splitlines() to = email_detail[1] content = email_detail[2] sendEmail(to, content) response = "Mail sent" except Exception as e: print(e) response = "Not able to send email Sorry!" elif message[0] == "/help": response = "Here the things I can do" + "<br>" + "/dict <word>: to find any word meaning with antonyms and Synonyms " + "<br>" + "/translate: to translate any sentence in Hindi language" + "<br>" + "/wiki <word>: to find any information on Wikipedia" + "<br>" + "/search <word>: to find any information on google.com" + "<br>" + "/addcontact: to add any contact detail on server" + "<br>" + "Here is the format to add Contact in a proper way:" + "<br>" + "/addcontact" + "<br>" + "[Name]" + "<br>" + "[Mobile Number]" + "<br>" + "[Email]" + "<br>" + "/searchcontact: to search any contact detail on server" + "<br>" + "Here is the format to search contact on the server" + "<br>" + "/searchcontact [Name]" + "<br>" + "/jokes: to get any randrom jokes" + "<br>" + "/facts: to get interesting random facts" + "<br>" + "/weather <City Name>: To get any details of Weather of any city" + "<br>" + "/gen: to generate random password" + "<br>" + "/sendmail: Used to send message through mail" + "<br>" + "Send Email in the following:<br>" + "/sendmail<br>" + "[Email Address]" + "<br>" + "[Content/Message]" + "<br>" + "/time: it can also show current time" elif message[0] == "/weather": response = Weather.weather(message[1]) '''api_key = "ac9ae5f24855de6ba928d40fc22af036" base_url = "http://api.openweathermap.org/data/2.5/weather?" city_name = message[1].capitalize() complete_url = base_url + "appid=" + api_key + "&q=" + city_name r = requests.get(complete_url) x = r.json() if x["cod"] != "404": y = x["main"] current_temperature = y["temp"] current_pressure = y["pressure"] current_humidity = y["humidity"] z = x["weather"] weather_description = z[0]["description"] current_tempc = float(current_temperature) - 273.15 response = "Temperature (in Celcius) = "+str(current_tempc)+"<br> Atmospheric Pressure (in hPa unit) = "+str(current_pressure)+"<br> Humidity (in percent) = "+str(current_humidity)+"<br> Description = "+str(weather_description) else: response = "City Not Found"''' elif message[0] == "/facts": x = randfacts.getFact() response = str(x) elif message[0] == "/prime": try: num = int(message[1]) if num > 1: for i in range(2, num): if (num % i) == 0: response = str(num) + " is not a prime number" response = str(i) + " times " + str( num // i) + " is " + str(num) break else: response = str(num) + " is a prime number" ##else: #response=num+" is not a prime number" except: response = "Please enter correct format" # don't run next condition elif message[0].lower() == "hi" or message[0].lower( ) == "hello" or message[0].lower() == "hey": response = "Hello there! I'm Anjan's bot, type /help to see list of commands :)" else: response = "Hi, I don't know this command" return response