def _parse_general_search(self, search_results): '''Finds the item to download from meta-search results''' parsed_results = {} for item in search_results('item'): description = str(item.description) seeds_index = description.index('Seeds') + 7 cut_description = description[seeds_index:] space_index = cut_description.index(' ') seeds = cut_description[:space_index] seeds = seeds.replace(",", "") seeds = int(seeds) file_type = str(item.category).lower() bad_file_types = ['flac', 'wma'] if file_type not in bad_file_types and seeds >= 5: title = item.title title = remove_html_tags(str(title)) title = remove_entities(title) #guid is the url of the 'choose a tracker' #page on torrentz guid = item.guid guid = remove_html_tags(str(guid)) parsed_results[title] = guid if parsed_results == {}: raise DownloaderError('No valid results for search term') return parsed_results
def gaia_post(self, queId, question, sess_id): string = utils.remove_html_tags(utils.BotMessages(id=7).get_message()) message = f"<b>{string}</b>" voice = utils.zamol_download(url=question) payload = self.bot.send_audio(chat_id=configs.GROUPID, audio=open(voice, 'rb'), caption=emoji.emojize(message, use_aliases=True), parse_mode='html') remove(voice) messageId = payload.message_id print("MESSAGE ID##########", messageId) sql.set_gaia_messageId(messageId=messageId, queId=queId) sql.create_correct(messageId=messageId) # sleep for 49 seconds then post answer local_datetime = datetime.datetime.now() strppp = local_datetime.astimezone(pytz.UTC) new_time = strppp + datetime.timedelta(seconds=int(43)) answer_time = new_time.strftime("%Y-%m-%d %H:%M:%S") sched.add_job(utils.Notify().post_gaia_answer, 'date', run_date=answer_time, args=[messageId, sess_id], id=str(messageId)) print("post answer", answer_time) utils.mr_logger(f"Posting the answer at :{answer_time}")
def _find_trackers(self, secondary_results_link, attempts=0): '''Identifies trackers that have the file that we can download from''' found_trackers = {} if attempts < 3: try: sock = urllib2.urlopen(secondary_results_link) html = sock.read() sock.close() except urllib2.URLError: attempts += 1 found_trackers = self._find_trackers(\ secondary_results_link, attempts) soup = BeautifulSoup(html) #all possible links on the page possible_trackers = soup.findAll('a') for possible_tracker in possible_trackers: tracker = remove_html_tags(str(possible_tracker)).split() if tracker: #tracker[0] is the name of the tracker stripped_tracker = tracker[0].replace('.com', '').replace( '.org', '').replace('.se', '') if stripped_tracker in self._trackers: #link is 'href="http://whatever.com' link = str(possible_tracker).split()[1] first_quote = link.index('"') + 1 second_quote = link.index('"', first_quote) tracker_url = link[first_quote:second_quote] found_trackers[stripped_tracker] = tracker_url if found_trackers == {}: raise DownloaderError('No known trackers') return found_trackers
def nuwa_post(self, question, sess_id, queId): string = utils.remove_html_tags(utils.BotMessages(id=10).get_message()) message = f"<b>{string}</b>\n\n<i>{question}</i>" payload = self.bot.send_message(chat_id=configs.GROUPID, text=emoji.emojize(message, use_aliases=True), parse_mode='html') messageId = payload.message_id print("posted mess", messageId) sql.set_nuwa_messageId(messageId=messageId, queId=queId) sql.create_correct(messageId=messageId) # sleep for 49 seconds then post answer local_datetime = datetime.datetime.now() strppp = local_datetime.astimezone(pytz.UTC) new_time = strppp + datetime.timedelta(seconds=int(35)) answer_time = new_time.strftime("%Y-%m-%d %H:%M:%S") sched.add_job(utils.Notify().post_nuwa_answer, 'date', run_date=answer_time, args=[messageId, sess_id], id=str(messageId)) print("post answer", answer_time) utils.mr_logger(f"Posting the answer at :{answer_time}")
def _find_trackers(self, secondary_results_link, attempts=0): '''Identifies trackers that have the file that we can download from''' found_trackers = {} if attempts < 3: try: sock = urllib2.urlopen(secondary_results_link) html = sock.read() sock.close() except urllib2.URLError: attempts += 1 found_trackers = self._find_trackers(\ secondary_results_link, attempts) soup = BeautifulSoup(html) #all possible links on the page possible_trackers = soup.findAll('a') for possible_tracker in possible_trackers: tracker = remove_html_tags(str(possible_tracker)).split() if tracker: #tracker[0] is the name of the tracker stripped_tracker = tracker[0].replace('.com', '').replace('.org', '').replace('.se', '') if stripped_tracker in self._trackers: #link is 'href="http://whatever.com' link = str(possible_tracker).split()[1] first_quote = link.index('"') + 1 second_quote = link.index('"', first_quote) tracker_url = link[first_quote:second_quote] found_trackers[stripped_tracker] = tracker_url if found_trackers == {}: raise DownloaderError('No known trackers') return found_trackers
def odin_post(self, queId, sess_id): key_main = [[ InlineKeyboardButton(emoji.emojize(":see_no_evil:", use_aliases=True), callback_data=f"odin+{queId}") ]] main_markup = InlineKeyboardMarkup(key_main) string = utils.remove_html_tags(utils.BotMessages(id=9).get_message()) message = f"<b>{string}</b>" payload = self.bot.send_message(chat_id=configs.GROUPID, text=emoji.emojize(message, use_aliases=True), reply_markup=main_markup, parse_mode='html') messageId = payload.message_id print("posted mess", messageId) sql.set_odin_messageId(messageId=messageId, queId=queId) sql.create_correct(messageId=messageId) # sleep for 49 seconds then post answer local_datetime = datetime.datetime.now() strppp = local_datetime.astimezone(pytz.UTC) new_time = strppp + datetime.timedelta(seconds=int(30)) answer_time = new_time.strftime("%Y-%m-%d %H:%M:%S") sched.add_job(utils.Notify().post_odin_answer, 'date', run_date=answer_time, args=[messageId, sess_id], id=str(messageId)) print("post answer", answer_time) utils.mr_logger(f"Posting the answer at :{answer_time}")
def refine(self, showId, showTitle): if ( self.seriesNum == u"" or self.epNum == u"" ): pattern = u'series-([0-9]+)(\\\)?/episode-([0-9]+)' seasonAndEpisodeMatch = re.search( pattern, self.thumbnail, re.DOTALL | re.IGNORECASE ) self.log(u"Searching for season and episode numbers in thumbnail url: %s" % self.thumbnail) if seasonAndEpisodeMatch is not None: self.seriesNum = int(seasonAndEpisodeMatch.group(1)) self.epNum = int(seasonAndEpisodeMatch.group(3)) # self.log( "End1: %s" % str(self.seriesNum), xbmc.LOGDEBUG) # self.log( str(self.epNum), xbmc.LOGDEBUG) # self.log( "End2: %s" % str(self.seriesNum), xbmc.LOGDEBUG) # self.log( str(self.epNum), xbmc.LOGDEBUG) if len(self.premieredDate) > 0: self.filename = showId + "." + self.premieredDate.replace( ' ', '.' ) else: self.filename = showId + "." + self.assetId self.epTitle = self.epTitle.strip() showTitle = utils.remove_extra_spaces(utils.remove_square_brackets(showTitle)) self.label = self.epTitle if self.epTitle == showTitle: self.label = "Series %d Episode %d" % (self.seriesNum, self.epNum) if len(self.premieredDate) > 0 and self.premieredDate not in self.label: self.label = self.label + u' [' + self.premieredDate + u']' self.description = utils.remove_extra_spaces(utils.remove_html_tags(self.description)) self.description = self.description.replace( u'&', u'&' ) self.description = self.description.replace( u'£', u'£') self.description = self.description.replace( u'"', u"'" )
def list_leaves_div(branch_id): #``````````````````````````````````````````````````````````` # GET METHOD #``````````````````````````````````````````````````````````` #print("Inside content mgr view...") leaves = model_datastore.list_leaves(branch_id) branch = model_datastore.read_branch(branch_id) #Read and print each leaf with all its parameters di = {} lstleaves = [] for content in leaves: obj = objects.clsLeaf() obj.id = content.id obj.branch_id = content['branch_id'] obj.content_type_id = content['content_type_id'] obj.source_doc_id = content['source_doc_id'] if content['content_eng']: obj.content_eng = utils.remove_html_tags(content['content_eng']) if content['content_san']: obj.content_san = utils.remove_html_tags(content['content_san']) if content['content_kan']: obj.content_kan = utils.remove_html_tags(content['content_kan']) obj.content_type_name = config.DICT_CONTENT_TYPE[ content['content_type_id']] obj.source_doc_name = config.DICT_SOURCEDOCS[content['source_doc_id']] #Add to list lstleaves.append(obj) del obj #Send output di = { "lstleaves": lstleaves, "catname": branch['name'], "branch_id": branch_id, "branch_parent_id": branch['branch_parent_id'] } return utils.render_template("contentmgr-list-div.html", lstleaves=lstleaves, catname=branch['name'], branch_id=branch_id, branch_parent_id=branch['branch_parent_id'])
def post_odin_answer(self, messageId, sess_id): try: utils.mr_logger(f"answer was posted") query = sql.get_odin_answer_by_msgId(msgId=messageId) answer, meaning = query total = sql.check_correct(messageId=messageId) # self.bot.delete_message() stringg = utils.remove_html_tags( utils.BotMessages(id=26).get_message()).split('.') head = stringg[0] body = "\n".join(stringg[1:4]) message = f"<b>{head}</b>\n{body}" correct_answer = f"<b>{answer}</b>" total = f"<b>{total}</b>" meaning = f"<b>{meaning}</b>" payload = self.bot.edit_message_text( chat_id=configs.GROUPID, message_id=messageId, text=emoji.emojize(message, use_aliases=True).format( correct_answer, meaning, total), parse_mode='html') sleep(5) self.bot.delete_message(chat_id=configs.GROUPID, message_id=messageId) sql.delete_correct(messageId=messageId) sql.delete_chance(messageId=messageId) sql.delete_odin(messageId) utils.mr_logger(f"message was deleted") self.bot.delete_message(chat_id=configs.GROUPID, message_id=payload.message_id) check_count = sql.get_odin_count(sess_id=sess_id) sess_state = sql.get_session_status(sess_id=sess_id) utils.mr_logger(f"{check_count} odin questions remaining") if check_count == 0 and sess_state == 0: sql.update_session(sessId=sess_id) msg = ":fire:The LIVE session is over. Thank you for learning with us. The next session starts soon. ❤:heart:Enjoy creative learning!❤:heart:" sent = self.bot.send_message(chat_id=configs.GROUPID, text=emoji.emojize( msg, use_aliases=True)) self.bot.pin_chat_message(chat_id=configs.GROUPID, message_id=sent.message_id) except: pass
def _pirate_title(self, url): try: sock = urllib2.urlopen(url) html = sock.read() sock.close() except URLError: raise DownloaderError('Connection issue') soup = BeautifulSoup(html) title = soup.find('div', {'id': 'title'}) pirate_title = None if title: formatted_title = str(title) formatted_title = remove_html_tags(formatted_title) formatted_title = formatted_title.strip() formatted_title = formatted_title.replace(',', '_') pirate_title = formatted_title.replace(' ', '_') return pirate_title
def _pirate_title(self, url): try: sock = urllib2.urlopen(url) html = sock.read() sock.close() except URLError: raise DownloaderError('Connection issue') soup = BeautifulSoup(html) title = soup.find('div', {'id':'title'}) pirate_title = None if title: formatted_title = str(title) formatted_title = remove_html_tags(formatted_title) formatted_title = formatted_title.strip() formatted_title = formatted_title.replace(',', '_') pirate_title = formatted_title.replace(' ', '_') return pirate_title
def _pirate_title(self, url): try: sock = urllib2.urlopen(url) html = sock.read() sock.close() except URLError: raise DownloaderError("Connection issue") soup = BeautifulSoup(html) title = soup.find("div", {"id": "title"}) pirate_title = None if title: formatted_title = str(title) formatted_title = remove_html_tags(formatted_title) formatted_title = formatted_title.strip() formatted_title = formatted_title.replace(",", "_") pirate_title = formatted_title.replace(" ", "_") return pirate_title
def session_start(self, bot, questions, qlevel, session_name, total_time): try: stringg = utils.remove_html_tags( utils.BotMessages(id=4).get_message()).split('.') heading = stringg[0] body = "\n".join(stringg[1:6]) message = f"<b>{heading}</b>\n{body}" print(message) timeinmins = "{:.2f}".format(int(total_time) / 60) payload = self.bot.send_message( chat_id=configs.GROUPID, text=emoji.emojize(message.format(bot, questions, qlevel, session_name, timeinmins), use_aliases=True), parse_mode='html') self.bot.pin_chat_message(chat_id=configs.GROUPID, message_id=payload.message_id) except: pass
def refine(self, showId, showTitle): if (self.seriesNum == u"" or self.epNum == u""): pattern = u'series-([0-9]+)(\\\)?/episode-([0-9]+)' seasonAndEpisodeMatch = re.search(pattern, self.thumbnail, re.DOTALL | re.IGNORECASE) self.log( u"Searching for season and episode numbers in thumbnail url: %s" % self.thumbnail) if seasonAndEpisodeMatch is not None: self.seriesNum = int(seasonAndEpisodeMatch.group(1)) self.epNum = int(seasonAndEpisodeMatch.group(3)) # self.log( "End1: %s" % str(self.seriesNum), xbmc.LOGDEBUG) # self.log( str(self.epNum), xbmc.LOGDEBUG) # self.log( "End2: %s" % str(self.seriesNum), xbmc.LOGDEBUG) # self.log( str(self.epNum), xbmc.LOGDEBUG) if len(self.premieredDate) > 0: self.filename = showId + "." + self.premieredDate.replace(' ', '.') else: self.filename = showId + "." + self.assetId self.epTitle = self.epTitle.strip() showTitle = utils.remove_extra_spaces( utils.remove_square_brackets(showTitle)) self.label = self.epTitle if self.epTitle == showTitle: self.label = "Series %d Episode %d" % (self.seriesNum, self.epNum) if len(self.premieredDate ) > 0 and self.premieredDate not in self.label: self.label = self.label + u' [' + self.premieredDate + u']' self.description = utils.remove_extra_spaces( utils.remove_html_tags(self.description)) self.description = self.description.replace(u'&', u'&') self.description = self.description.replace(u'£', u'£') self.description = self.description.replace(u'"', u"'")
def wala_post_main(self, question): string = utils.remove_html_tags( utils.BotMessages(id=14).get_message()).split('.') fmt = ".\n".join(string) message = f"<b>{fmt}</b>\n\n{question}" payload = self.bot.send_message(chat_id=configs.GROUPID, text=emoji.emojize(message, use_aliases=True), parse_mode='html') messageId = payload.message_id local_datetime = datetime.datetime.now() strppp = local_datetime.astimezone(pytz.UTC) new_time = strppp + datetime.timedelta(minutes=int(3)) delete_time = new_time.strftime("%Y-%m-%d %H:%M:%S") sched.add_job(utils.Notify().wala_delete_main, 'date', run_date=delete_time, args=[messageId], id=str(messageId)) print("delete answer", delete_time) utils.mr_logger(f"deleting the main question at :{delete_time}")
def post_nuwa_answer(self, messageId, sess_id): try: utils.mr_logger(f"answer was posted") total = sql.check_correct(messageId=messageId) # self.bot.delete_message() stringg = utils.remove_html_tags( utils.BotMessages(id=3).get_message()).split('.') head = stringg[1] message = f"<b>{head}</b>" payload = self.bot.send_message( chat_id=configs.GROUPID, text=emoji.emojize(message, use_aliases=True).format(total), parse_mode='html') self.bot.delete_message(chat_id=configs.GROUPID, message_id=messageId) sql.delete_correct(messageId=messageId) sql.delete_chance(messageId=messageId) sleep(5) sql.delete_nuwa(messageId) utils.mr_logger(f"message was deleted") self.bot.delete_message(chat_id=configs.GROUPID, message_id=payload.message_id) check_count = sql.get_nuwa_count(sess_id=sess_id) sess_state = sql.get_session_status(sess_id=sess_id) utils.mr_logger(f"{check_count} nuwa questions remaining") if check_count == 0 and sess_state == 0: sql.update_session(sessId=sess_id) msg = ":fire:The LIVE session is over. Thank you for learning with us. The next session starts soon. ❤:heart:Enjoy creative learning!❤:heart:" sent = self.bot.send_message(chat_id=configs.GROUPID, text=emoji.emojize( msg, use_aliases=True)) self.bot.pin_chat_message(chat_id=configs.GROUPID, message_id=sent.message_id) except: pass
def seshat_post(self, queId, question, instruction, gif, sess_id): string = utils.remove_html_tags(utils.BotMessages(id=15).get_message()) message = f"<b>{instruction}\n<i>{question}</i>\n\n{string}</b>" if "gif" in gif: utils.mr_logger(f"posting gif: {gif}") payload = self.bot.send_document(chat_id=configs.GROUPID, document=gif, caption=emoji.emojize( message, use_aliases=True), parse_mode=ParseMode.HTML) else: utils.mr_logger(f"posting photo: {gif}") payload = self.bot.send_photo(chat_id=configs.GROUPID, photo=gif, caption=emoji.emojize( message, use_aliases=True), parse_mode=ParseMode.HTML) messageId = payload.message_id print("posted mess", messageId) sql.set_seshat_messageId(messageId=messageId, queId=queId) sql.create_correct(messageId=messageId) # sleep for 49 seconds then post answer local_datetime = datetime.datetime.now() strppp = local_datetime.astimezone(pytz.UTC) new_time = strppp + datetime.timedelta(seconds=int(20)) answer_time = new_time.strftime("%Y-%m-%d %H:%M:%S") sched.add_job(utils.Notify().post_seshat_answer, 'date', run_date=answer_time, args=[messageId, sess_id], id=str(messageId)) print("post answer", answer_time) utils.mr_logger(f"Posting the answer at :{answer_time}")
def getCostElgiganten(self, soup: Type[BS]): results = soup.find_all('div', class_="product-price-container") price = utils.remove_white_space( utils.remove_html_tags(results[0].text)) return price
for entry in parser['entries']: if entry.get('link'): link = entry['link'] else: if entry.get('id') and is_valid_url(entry['id']): link = entry['id'] else: print("Unfortunately this news doesn\'t have a link.") print(entry) continue content = None if entry.get('summary'): text_to_search_in = entry['summary'] elif entry.get('content') and entry['content'][0]['value']: content = remove_html_tags(entry['content'][0]['value']) text_to_search_in = content else: text_to_search_in = '' # existing_query = queries_in_text(f'{entry["title"]} {text_to_search_in}', queries) # if not existing_query: # continue existing_query = queries[0] main_data = { 'link': link, 'published_at': entry.get('published') or entry.get('updated'), 'query_id': existing_query['id'], 'source_id': parser['source_id']
import datetime import pytz import utils # sql= utils.DBHelper().setup() stringg = utils.remove_html_tags( utils.BotMessages(id=28).get_message()).split('.') print(".\n".join(stringg))
async def format_page(self, menu: MediaPages, data: dict) -> utils.Embed: """Formats the media into a embed showing the main informations""" embed = await super().format_page(menu, data) if desc := data["description"]: return embed(description=utils.remove_html_tags(desc))
def reply_check(update,context): bot_username = update.message.reply_to_message.from_user.username user = update.message.from_user username =utils.get_username(update,context) user_answer = update.message.text group_id = update.message.chat.id chat_type = update.message.chat.type admin = utils.Admin(userid=user.id, language=configs.LANGUAGE).get_data() #check if the user is replying in the group and to the bot's message if chat_type != "private" and bot_username == configs.BOTUSERNAME: # chat message id message_id = update.message.reply_to_message.message_id #question type(apollo,gaia,etc) bot_type = utils.bot_type(message_id=message_id) botify.logger.warning(f'bot type: {bot_type}') if bot_type=='Apollo': # if the user is not an admin if admin==False: """register/confirm the db under the question and language""" res = utils.CreateStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type, name=username).get_data() botify.logger.warning(f'creating student api called : {res}') """Check how many chances a user has got remaining,1 chance per user per question""" tries = sql.check_try(userId=user.id, messageId=message_id, bot=bot_type) if tries != True: """mark the user as tried the question""" sql.create_chance(userId=user.id, messageId=message_id, bot=bot_type) """Check user level""" student = utils.GetStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() student_level = student['level'] qlevel = sql.get_apollo_level_by_msgId(msgId=message_id) que_level = utils.levelq(qlevel) botify.logger.warning(f'question level : {que_level}') if int(que_level) >= int(student_level): """Check user answer""" answer = sql.get_apollo_answer_by_msgId(msgId=message_id) if utils.stripper(text=user_answer) == utils.stripper(text=answer): """add user's fortuna in this language and exercise""" utils.AddFortunas(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() """increase count of users who tried this question""" sql.update_correct(messageId=message_id) elif bot_type=='Seshat': if admin==False: """register/confirm the db under the question and language""" res = utils.CreateStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type, name=username).get_data() botify.logger.warning(f'creating student api called : {res}') """Check how many chances a user has got remaining,1 chance per user per question""" tries = sql.check_try(userId=user.id, messageId=message_id, bot=bot_type) if tries != True: """mark the user as tried the question""" sql.create_chance(userId=user.id, messageId=message_id, bot=bot_type) """Check user level""" student = utils.GetStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() student_level = student['level'] qlevel = sql.get_seshat_level_by_msgId(msgId=message_id) que_level = utils.levelq(qlevel) botify.logger.warning(f'question level : {que_level}') if int(que_level) >= int(student_level): """Check user answer""" answer = sql.get_seshat_answer_by_msgId(msgId=message_id) correct_answer=utils.stripper(text=answer).lower() answer_submitted=utils.stripper(text=user_answer).lower() if answer_submitted == correct_answer: """add user's fortuna in this language and exercise""" utils.AddFortunas(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() """increase count of users who tried this question""" sql.update_correct(messageId=message_id) elif bot_type == 'Tyche': if admin==False: """register/confirm the db under the question and language""" res = utils.CreateStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type, name=username).get_data() botify.logger.warning(f'creating student api called : {res}') """Check how many chances a user has got remaining,1 chance per user per question""" tries = sql.check_try(userId=user.id, messageId=message_id, bot=bot_type) if tries != True: """mark the user as tried the question""" sql.create_chance(userId=user.id, messageId=message_id, bot=bot_type) """Check user level""" student = utils.GetStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() student_level = student['level'] qlevel = sql.get_tyche_level_by_msgId(msgId=message_id) que_level = utils.levelq(qlevel) botify.logger.warning(f'question level : {que_level}') if int(que_level) >= int(student_level): """Check user answer""" answer = sql.get_tyche_answer_by_msgId(msgId=message_id) correct_answer = utils.stripper(text=answer).lower() answer_submitted = utils.stripper(text=user_answer).lower() if answer_submitted == correct_answer: """add user's fortuna in this language and exercise""" utils.AddFortunas(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() """increase count of users who tried this question""" sql.update_correct(messageId=message_id) elif bot_type == 'Leizi': if admin==False: """register/confirm the db under the question and language""" res = utils.CreateStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type, name=username).get_data() botify.logger.warning(f'creating student api called : {res}') """Check how many chances a user has got remaining,1 chance per user per question""" tries = sql.check_try(userId=user.id, messageId=message_id, bot=bot_type) if tries != True: """mark the user as tried the question""" sql.create_chance(userId=user.id, messageId=message_id, bot=bot_type) """Check user level""" student = utils.GetStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() student_level = student['level'] qlevel = sql.get_leizi_level_by_msgId(msgId=message_id) que_level = utils.levelq(qlevel) botify.logger.warning(f'question level : {que_level}') if int(que_level) >= int(student_level): """Check user answer""" answer = sql.get_leizi_answer_by_msgId(msgId=message_id) try: answer1, answer2 = answer correct_answer1 = utils.stripper(text=answer1).lower() correct_answer2 = utils.stripper(text=answer2).lower() answer_submitted = utils.stripper(text=user_answer).lower() if answer_submitted == correct_answer1 or answer_submitted == correct_answer2: """add user's fortuna in this language and exercise""" utils.AddFortunas(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() """increase count of users who tried this question""" sql.update_correct(messageId=message_id) except : pass elif bot_type == 'Odin': if admin==False: """register/confirm the db under the question and language""" res = utils.CreateStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type, name=username).get_data() botify.logger.warning(f'creating student api called : {res}') """Check how many chances a user has got remaining,1 chance per user per question""" tries = sql.count_chances(userId=user.id, messageId=message_id, bot=bot_type) if tries ==1: """mark the user as tried the question""" sql.create_chance(userId=user.id, messageId=message_id, bot=bot_type) """Check user level""" student = utils.GetStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() student_level = student['level'] qlevel = sql.get_odin_level_by_msgId(msgId=message_id) que_level = utils.levelq(qlevel) botify.logger.warning(f'question level : {que_level}') if int(que_level) >= int(student_level): """Check user answer""" # answer = sql.get_odin_answer_by_msgId(msgId=message_id) query = sql.get_odin_answer_by_msgId(msgId=message_id) answer, meaning = query try: correct_answer = utils.stripper(text=answer).lower() answer_submitted = utils.stripper(text=user_answer).lower() if answer_submitted == correct_answer: """add user's fortuna in this language and exercise""" utils.AddFortunas(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() """increase count of users who tried this question""" sql.update_correct(messageId=message_id) except : pass elif bot_type == 'Zamo': if admin==False: """register/confirm the db under the question and language""" res = utils.CreateStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type, name=username).get_data() botify.logger.warning(f'creating student api called : {res}') """Check how many chances a user has got remaining,1 chance per user per question""" tries = sql.check_try(userId=user.id, messageId=message_id, bot=bot_type) if tries != True: """mark the user as tried the question""" sql.create_chance(userId=user.id, messageId=message_id, bot=bot_type) """Check user level""" student = utils.GetStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() student_level = student['level'] qlevel = sql.get_zamo_level_by_msgId(msgId=message_id) que_level = utils.levelq(qlevel) botify.logger.warning(f'question level : {que_level}') if int(que_level) >= int(student_level): """Check user answer""" answer = sql.get_zamo_answer_by_msgId(msgId=message_id) correct_answer=utils.stripper(text=answer).lower() answer_submitted=utils.stripper(text=user_answer).lower() if answer_submitted == correct_answer: """add user's fortuna in this language and exercise""" utils.AddFortunas(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() """increase count of users who tried this question""" sql.update_correct(messageId=message_id) elif bot_type == 'nuwa': print(bot_type) if admin == False: """register/confirm the db under the question and language""" res = utils.CreateStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type, name=username).get_data() botify.logger.warning(f'creating student api called : {res}') """Check how many chances a user has got remaining,1 chance per user per question""" tries = sql.check_try(userId=user.id, messageId=message_id, bot=bot_type) if tries != True: """mark the user as tried the question""" sql.create_chance(userId=user.id, messageId=message_id, bot=bot_type) """Check user level""" student = utils.GetStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() student_level = student['level'] qlevel = sql.get_nuwa_level_by_msgId(msgId=message_id) que_level = utils.levelq(qlevel) botify.logger.warning(f'question level : {que_level}') if int(que_level) >= int(student_level): """voice to text""" answer = sql.get_nuwa_answer_by_msgId(msgId=message_id) correct_answer = utils.stripper(text=answer).lower() file_id = update.message.voice.file_id newFile = context.bot.get_file(file_id) newFile.download(f'nuwa_{user.id}.ogg') length = update.message.voice.duration if length < 10: new = utils.convert_ogg_to_wav(f"nuwa_{user.id}.ogg", f"nuwa_{user.id}.wav") speech.file = new langue = utils.language_select(language=configs.LANGUAGE) text = speech.to_text(lang=langue) utils.mr_logger(f"totext: {text},answer {answer}") if text == 401: update.message.reply_text( f"Hi {user.first_name}, I did not understand this, please try again") elif text == 500: update.message.reply_text( f"Sorry {user.first_name}, I got a little light headed, please try again") elif text.lower() == correct_answer: """add user's fortuna in this language and exercise""" utils.AddFortunas(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() """increase count of users who tried this question""" sql.update_correct(messageId=message_id) return utils.clear_nuwa(user_id=user.id) elif bot_type == 'gaia': print("BOT NAME",bot_type) if admin == False: """register/confirm the db under the question and language""" res = utils.CreateStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type, name=username).get_data() botify.logger.warning(f'creating student api called : {res}') """Check how many chances a user has got remaining,1 chance per user per question""" tries = sql.check_try(userId=user.id, messageId=message_id, bot=bot_type) if tries != True: """mark the user as tried the question""" sql.create_chance(userId=user.id, messageId=message_id, bot=bot_type) """Check user level""" student = utils.GetStudent(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() student_level = student['level'] qlevel = sql.get_gaia_level_by_msgId(msgId=message_id) que_level = utils.levelq(qlevel) botify.logger.warning(f'question level : {que_level}') if int(que_level) >= int(student_level): """voice to text""" answer = sql.get_gaia_answer_by_msgId(msgId=message_id) correct_answer = utils.stripper(text=answer) file_id = update.message.voice.file_id newFile = context.bot.get_file(file_id) newFile.download('gaia_{}.ogg'.format(user.id)) length = update.message.voice.duration if length < 10: new = utils.convert_ogg_to_wav(f"gaia_{user.id}.ogg", f"gaia_{user.id}.wav") speech.file = new langue = utils.language_select(language=configs.LANGUAGE) text = speech.to_text(lang=langue) utils.mr_logger(f"totext: {text},answer {answer}") if text == 401: update.message.reply_text( f"Hi {user.first_name}, I did not understand this, please try again") elif text == 500: update.message.reply_text( f"Sorry {user.first_name}, I got a little light headed, please try again") elif text.lower() == correct_answer: """add user's fortuna in this language and exercise""" utils.AddFortunas(userid=user.id, language=configs.LANGUAGE, exercise=bot_type).get_data() """increase count of users who tried this question""" sql.update_correct(messageId=message_id) return utils.clear_gaia(user_id=user.id) elif chat_type=='private': message_id = update.message.reply_to_message.message_id session_type =solosql.get_session_type(userid=user.id,msgid=message_id) if session_type=='Apollo': canswer = solosql.get_answer_msgid(userid=user.id, msgid=message_id) if utils.stripper(text=user_answer) == utils.stripper(text=canswer): context.bot.delete_message(chat_id=user.id, message_id=message_id) pl = context.bot.send_message(chat_id=user.id, text=emoji.emojize(":fire:Your Answer is Correct:fire:", use_aliases=True)) correct = solosql.get_correct(user.id) print("correct", correct) correct += 1 solosql.update_correct(user_id=user.id, correct=correct) print(pl.result().message_id) sleep(2) context.bot.delete_message(chat_id=user.id, message_id=pl.result().message_id) session, tries = solosql.get_tries(userid=user.id) tries -= 1 solosql.update_tries(user.id, tries) session, tries = solosql.get_tries(userid=user.id) print(tries) if tries > 0: apollo_ques = solosql.get_apollo_question() if apollo_ques != False: question, answer = apollo_ques string = utils.remove_html_tags(utils.BotMessages(id=6).get_message()) message = f"<b>{string}</b>\n\n:orange_book:<i>{question}</i>" payload = context.bot.send_message(chat_id=user.id, text=emoji.emojize(message, use_aliases=True), parse_mode='html') messageId = payload.result().message_id solosql.update_user_question(userid=user.id, answer=answer, session='Apollo', message_id=messageId, tries=tries, correct=correct) else: key_main = [[InlineKeyboardButton('Africa', callback_data='solo_africa'), InlineKeyboardButton('Apollo', callback_data='solo_apollo')], [InlineKeyboardButton('Gaia', callback_data='solo_gaia'), InlineKeyboardButton('Kadlu', callback_data='solo_kadlu')], [InlineKeyboardButton('Leizi', callback_data='solo_leizi'), InlineKeyboardButton('Nuwa', callback_data='solo_nuwa')], [InlineKeyboardButton('Odin', callback_data='solo_odin'), InlineKeyboardButton('Seshat', callback_data='solo_seshat')], [InlineKeyboardButton('Tyche', callback_data='solo_tyche'), InlineKeyboardButton('Wala', callback_data='solo_wala')], [InlineKeyboardButton('Zamo', callback_data='solo_zamo'), InlineKeyboardButton('Instructions', url='https://telegra.ph/Ra-v3-tutorials-05-08')], [InlineKeyboardButton('Donate', url='https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WJYMNYLP9TQHL&source=url')]] main_markup = InlineKeyboardMarkup(key_main) correct = solosql.get_correct(user.id) msg = f":fire: Congratulations you got {correct}/10,Keep on practicing to be the G.O.A.T" context.bot.send_message(chat_id=user.id, text=emoji.emojize(msg, use_aliases=True), reply_markup=main_markup) else: context.bot.delete_message(chat_id=user.id, message_id=message_id) pl = context.bot.send_message(chat_id=user.id, text=emoji.emojize( f":fire:Your Answer is Incorrect, the correct answer was: <b>{canswer}</b> :fire:", use_aliases=True), parse_mode='html') print(pl.result().message_id) sleep(3) context.bot.delete_message(chat_id=user.id, message_id=pl.result().message_id) session, tries = solosql.get_tries(userid=user.id) tries -= 1 solosql.update_tries(user.id, tries) session, tries = solosql.get_tries(userid=user.id) print(tries) if tries > 0: apollo_ques = solosql.get_apollo_question() if apollo_ques != False: question, answer = apollo_ques string = utils.remove_html_tags(utils.BotMessages(id=6).get_message()) message = f"<b>{string}</b>\n\n:orange_book:<i>{question}</i>" payload = context.bot.send_message(chat_id=user.id, text=emoji.emojize(message, use_aliases=True), parse_mode='html') messageId = payload.result().message_id correct = solosql.get_correct(user.id) solosql.update_user_question(userid=user.id, answer=answer, session='Apollo', message_id=messageId, tries=tries, correct=correct) else: key_main = [[InlineKeyboardButton('Africa', callback_data='solo_africa'), InlineKeyboardButton('Apollo', callback_data='solo_apollo')], [InlineKeyboardButton('Gaia', callback_data='solo_gaia'), InlineKeyboardButton('Kadlu', callback_data='solo_kadlu')], [InlineKeyboardButton('Leizi', callback_data='solo_leizi'), InlineKeyboardButton('Nuwa', callback_data='solo_nuwa')], [InlineKeyboardButton('Odin', callback_data='solo_odin'), InlineKeyboardButton('Seshat', callback_data='solo_seshat')], [InlineKeyboardButton('Tyche', callback_data='solo_tyche'), InlineKeyboardButton('Wala', callback_data='solo_wala')], [InlineKeyboardButton('Zamo', callback_data='solo_zamo'), InlineKeyboardButton('Instructions', url='https://telegra.ph/Ra-v3-tutorials-05-08')], [InlineKeyboardButton('Donate', url='https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WJYMNYLP9TQHL&source=url')]] main_markup = InlineKeyboardMarkup(key_main) correct = solosql.get_correct(user.id) msg = f":fire: Congratulations you got {correct}/10,Keep on practicing to be the G.O.A.T" context.bot.send_message(chat_id=user.id, text=emoji.emojize(msg, use_aliases=True), reply_markup=main_markup) elif session_type=='Gaia': canswer = solosql.get_answer_msgid(userid=user.id, msgid=message_id) correct_answer = utils.stripper(text=canswer) try: file_id = update.message.voice.file_id newFile = context.bot.get_file(file_id) newFile.download('gaia_{}.ogg'.format(user.id)) length = update.message.voice.duration if length < 10: new = utils.convert_ogg_to_wav(f"gaia_{user.id}.ogg", f"gaia_{user.id}.wav") speech.file = new langue = utils.language_select(language=configs.LANGUAGE) text = speech.to_text(lang=langue) utils.mr_logger(f"totext: {text},answer {canswer}") if text == 401: update.message.reply_text( f"Hi {user.first_name}, I did not understand this, please try again") elif text == 500: update.message.reply_text( f"Sorry {user.first_name}, I got a little light headed, please try again") elif text.lower() == correct_answer: context.bot.delete_message(chat_id=user.id, message_id=message_id) pl = context.bot.send_message(chat_id=user.id, text=emoji.emojize(":fire:Your Answer is Correct:fire:", use_aliases=True)) correct = solosql.get_correct(user.id) print("correct", correct) correct += 1 solosql.update_correct(user_id=user.id, correct=correct) print(pl.result().message_id) sleep(2) context.bot.delete_message(chat_id=user.id, message_id=pl.result().message_id) session, tries = solosql.get_tries(userid=user.id) tries -= 1 solosql.update_tries(user.id, tries) session, tries = solosql.get_tries(userid=user.id) print(tries) utils.clear_gaia(user_id=user.id) if tries > 0: gaia_ques = solosql.get_gaia_question() if gaia_ques != False: question, answer = gaia_ques string = utils.remove_html_tags(utils.BotMessages(id=7).get_message()) message = f"<b>{string}</b>" voice = utils.zamol_download(url=question) payload = context.bot.send_audio(chat_id=user.id, audio=open(voice, 'rb'), caption=emoji.emojize(message, use_aliases=True), parse_mode='html') # sleep(2) # remove(voice) messageId = payload.result().message_id solosql.update_user_question(userid=user.id, answer=answer, session='Gaia', message_id=messageId, tries=tries, correct=correct) else: key_main = [[InlineKeyboardButton('Africa', callback_data='solo_africa'), InlineKeyboardButton('Apollo', callback_data='solo_apollo')], [InlineKeyboardButton('Gaia', callback_data='solo_gaia'), InlineKeyboardButton('Kadlu', callback_data='solo_kadlu')], [InlineKeyboardButton('Leizi', callback_data='solo_leizi'), InlineKeyboardButton('Nuwa', callback_data='solo_nuwa')], [InlineKeyboardButton('Odin', callback_data='solo_odin'), InlineKeyboardButton('Seshat', callback_data='solo_seshat')], [InlineKeyboardButton('Tyche', callback_data='solo_tyche'), InlineKeyboardButton('Wala', callback_data='solo_wala')], [InlineKeyboardButton('Zamo', callback_data='solo_zamo'), InlineKeyboardButton('Instructions', url='https://telegra.ph/Ra-v3-tutorials-05-08')], [InlineKeyboardButton('Donate', url='https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WJYMNYLP9TQHL&source=url')]] main_markup = InlineKeyboardMarkup(key_main) correct = solosql.get_correct(user.id) msg = f":fire: Congratulations you got {correct}/10,Keep on practicing to be the G.O.A.T" context.bot.send_message(chat_id=user.id, text=emoji.emojize(msg, use_aliases=True), reply_markup=main_markup) elif text.lower() != correct_answer: context.bot.delete_message(chat_id=user.id, message_id=message_id) pl = context.bot.send_message(chat_id=user.id, text=emoji.emojize( f":fire:Your Answer is Incorrect, the correct answer was: <b>{canswer}</b> :fire:", use_aliases=True), parse_mode='html') print(pl.result().message_id) sleep(3) context.bot.delete_message(chat_id=user.id, message_id=pl.result().message_id) session, tries = solosql.get_tries(userid=user.id) tries -= 1 solosql.update_tries(user.id, tries) session, tries = solosql.get_tries(userid=user.id) print(tries) if tries > 0: gaia_ques = solosql.get_gaia_question() if gaia_ques != False: question, answer = gaia_ques string = utils.remove_html_tags(utils.BotMessages(id=7).get_message()) message = f"<b>{string}</b>" voice = utils.zamol_download(url=question) payload = context.bot.send_audio(chat_id=user.id, audio=open(voice, 'rb'), caption=emoji.emojize(message, use_aliases=True), parse_mode='html') # sleep(2) # remove(voice) messageId = payload.result().message_id correct = solosql.get_correct(user.id) solosql.update_user_question(userid=user.id, answer=answer, session='Gaia', message_id=messageId, tries=tries, correct=correct) else: key_main = [[InlineKeyboardButton('Africa', callback_data='solo_africa'), InlineKeyboardButton('Apollo', callback_data='solo_apollo')], [InlineKeyboardButton('Gaia', callback_data='solo_gaia'), InlineKeyboardButton('Kadlu', callback_data='solo_kadlu')], [InlineKeyboardButton('Leizi', callback_data='solo_leizi'), InlineKeyboardButton('Nuwa', callback_data='solo_nuwa')], [InlineKeyboardButton('Odin', callback_data='solo_odin'), InlineKeyboardButton('Seshat', callback_data='solo_seshat')], [InlineKeyboardButton('Tyche', callback_data='solo_tyche'), InlineKeyboardButton('Wala', callback_data='solo_wala')], [InlineKeyboardButton('Zamo', callback_data='solo_zamo'), InlineKeyboardButton('Instructions', url='https://telegra.ph/Ra-v3-tutorials-05-08')], [InlineKeyboardButton('Donate', url='https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WJYMNYLP9TQHL&source=url')]] main_markup = InlineKeyboardMarkup(key_main) correct = solosql.get_correct(user.id) msg = f":fire: Congratulations you got {correct}/10,Keep on practicing to be the G.O.A.T" context.bot.send_message(chat_id=user.id, text=emoji.emojize(msg, use_aliases=True), reply_markup=main_markup) except Exception as e: print(e) string = utils.remove_html_tags(utils.BotMessages(id=7).get_message()) message = f"<b>{string}</b>" context.bot.send_message(chat_id=user.id, text=emoji.emojize(message, use_aliases=True),parse_mode="html")
def check_feed(bot, key): feed_url = re.match("^" + feed_hash.format("(.+):subs$"), key).group(1) logger.info(feed_url) data = feedparser.parse(feed_url) if "link" not in data.feed: if "status" in data and data["status"] != 200: logger.warning(_("{0} - Not a valid feed, got HTTP Code {1}").format(feed_url, data["status"])) else: logger.warning(_("{0} - Not a valid feed: {1}").format(feed_url, str(data.bozo_exception))) return None if "title" not in data.feed: feed_title = data.feed["link"] else: feed_title = data.feed["title"] last_entry_hash = feed_hash.format(feed_url + ":last_entry") last_entry = r.get(last_entry_hash) new_entries = utils.get_new_entries(data.entries, last_entry) for entry in reversed(new_entries): if "title" not in entry: post_title = _("No title") else: post_title = utils.remove_html_tags(entry["title"]).strip() post_title = post_title.replace("<", "<").replace(">", ">") if "link" not in entry: post_link = data.link link_name = post_link else: post_link = entry.link feedproxy = re.search("^https?://feedproxy\.google\.com/~r/(.+?)/.*", post_link) # feedproxy.google.com if feedproxy: link_name = feedproxy.group(1) else: link_name = urlparse(post_link).netloc link_name = re.sub("^www\d?\.", "", link_name) # remove www. if "content" in entry: content = utils.get_content(entry.content[0]["value"]) elif "summary" in entry: content = utils.get_content(entry.summary) else: content = "" text = "<b>{post_title}</b>\n<i>{feed_title}</i>\n{content}".format( post_title=post_title, feed_title=feed_title, content=content ) readmore = _("Read more on {0}").format(link_name) text += "\n<a href=\"{post_link}\">{readmore}</a>\n".format( post_link=post_link, readmore=readmore ) for member in r.smembers(key): try: bot.sendMessage( chat_id=member, text=text, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True ) except telegram.error.Unauthorized: logger.warning(_("Chat {0} doesn't exist anymore, will be deleted.").format(member)) r.srem(key, member) r.delete(feed_hash.format(member)) except telegram.error.ChatMigrated as new_chat: new_chat_id = new_chat.new_chat_id logger.info(_("Chat migrated: ") + member + " -> " + str(new_chat_id)) r.srem(key, member) r.sadd(key, new_chat_id) r.rename(feed_hash.format(member), feed_hash.format(new_chat_id)) bot.sendMessage( chat_id=member, text=text, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True ) except telegram.error.TimedOut: pass except telegram.error.BadRequest as exception: logger.error(exception) if not r.exists(key): r.delete(last_entry_hash) return # Set the new last entry if there are any if new_entries: if "id" not in new_entries[0]: new_last_entry = new_entries[0].link else: new_last_entry = new_entries[0].id r.set(last_entry_hash, new_last_entry)
def getCostKomplett(self, soup: Type[BS]): results = soup.find_all('span', class_="product-price-now") price = utils.remove_white_space( utils.remove_html_tags(results[0].text)).replace(':-', '') return price