def createFavorite(**kwargs): if kwargs is not None: script= None ranking= None db = None try: db = lite.connect(dbname) db.text_factory = str cursor = db.cursor() if kwargs.has_key("name") and kwargs.has_key("ranking"): script = kwargs["name"] ranking = kwargs["ranking"] elif kwargs.has_key("name"): script = kwargs["name"] ranking = "normal" else: print "Bad Params" cursor.execute(''' Insert into favorites (name,ranking) values (?,?) ''',(script,ranking,)) db.commit() if cursor.rowcount == 1: print "[+] "+script+" "+i18n.t("setup.add_fav_ok") except Exception, e: print "[-] "+script+" "+i18n.t("setup.add_fav_error") finally:
def get_file(message): user_lang(message) if message.content_type == 'document': file_size = message.document.file_size bot.reply_to(message, str(u'\U00002705') + 'Downloaded ' + str(file_size) + ' bytes.') file_info = bot.get_file(message.document.file_id) file_url = ('https://api.telegram.org/file/bot' + TOKEN + '/' + file_info.file_path) # print(file_url) elif message.content_type == 'text': if message.text.lower() in cmds: return 0 file_url = message.text else: msg = bot.send_message(message.from_user.id, i18n.t('bot.askfile')) bot.register_next_step_handler(msg, get_file) return 0 # data = select_user(db, table, message.from_user.id, '*') # f = requests.get(file_url) upd_user_file(db, table, message.from_user.id, file_url) print(file_url) if '.pdf' in file_url.lower(): msg = bot.send_message(message.from_user.id, i18n.t('bot.askconvert'), parse_mode='HTML', reply_markup=button2) else: data = select_user(db, table, message.from_user.id, '*') send_mail(str(message.from_user.id), data[2], data[3], ' ', str(message.from_user.id), data[7])
def set_buttons(): global button global button2 button = types.InlineKeyboardMarkup() btn1 = types.InlineKeyboardButton(i18n.t('bot.btn1'), callback_data='/send') btn2 = types.InlineKeyboardButton(i18n.t('bot.btn2'), callback_data='/email') button.row(btn1, btn2) button2 = types.InlineKeyboardMarkup() btn3 = types.InlineKeyboardButton(i18n.t('bot.btn3'), callback_data='/as_is') btn4 = types.InlineKeyboardButton(i18n.t('bot.btn4'), callback_data='/converted') button2.row(btn3, btn4)
def launch(): webrelaylist = reloadrelays() print(webrelaylist) """Build the GUI and start the app.""" logger.debug('Setting up...') APP.setTitle(t('label.title')) APP.setIcon("icon.ico") APP.startLabelFrame(t('label.remoteconn'), 10, 1) # this sticky option only applies to the label frame. APP.setSticky("w") relaylist = '{' for webrelay in webrelaylist: relaylist = relaylist + '"' + webrelay + '":False, ' relaylist = relaylist[:-2] + '}' print(relaylist) APP.addProperties(t('label.relays'), ) APP.stopLabelFrame() APP.startLabelFrame(t('label.localconn'), 10, 2) # this sticky option only applies to the label frame. APP.setSticky("e") APP.addEntry(t('label.localconnection'), 1, 1, 1) APP.addButton(t('label.bindlocal'), press, 1, 2, 1) APP.setEntryDefault(t('label.localconnection'), DEFAULTS["localconnection"]) APP.stopLabelFrame() APP.go()
def com_perfil(perfis, tipo_busca, primeira_palavra, complemento, emoji, username, password, modo_bot, linguagem, navegador, inicio): instagram = InstagramBot(username, password, modo_bot, linguagem, navegador, inicio) time.sleep(5) instagram.login() while True: if len(perfis) != 0: try: tag = random.choice(perfis) print( '--------------------------------------------------------------------------------' ) print('\n' + i18n.t("sem_hashtags_inicia") + f'@{tag} ' + i18n.t("com_hashtags_inicia") + datetime.now().strftime("%Y-%m-%d %H:%M:%S")) instagram.listar_perfis_do_perfil(tag) print( f'{i18n.t("sem_hashtags_numero_seg")} {len(instagram.seguidores_perfil)}.\n' ) instagram.tabela_stdout() while len(instagram.seguidores_perfil) != 0: time.sleep(20) instagram.selecionar_fotos_perfil() eval('instagram.' + tipo_busca) instagram.limpar_urefs() print( '\n-------------------------------------------------------------------\n' ) print('\n' + i18n.t("sem_hashtags_inicia") + f' @{tag} ' + i18n.t("com_hashtags_finalizada") + datetime.now().strftime("%Y-%m-%d %H:%M:%S")) print( '\n--------------------------------------------------------------------------------\n' ) perfis.remove(tag) except Exception as e: print(f'\n {e} \n') instagram.deu_ruim() else: instagram.close_browser() print( i18n.t('lista_sem_hashtags_acabou') + datetime.now().strftime("%Y-%m-%d %H:%M:%S")) sys.exit()
def build_sim_sir_w_date_chart(*, alt, sim_sir_w_date_floor_df: pd.DataFrame, max_y_axis: Optional[int] = None, use_log_scale: bool = False) -> Chart: """ This builds the "Susceptible, Infected, and Recovered" chart, projecting the number of those individuals in the hospital's region over time. Args: alt: Reference to the Altair package. sim_sir_w_date_floor_df: A Pandas data frame with columns named "susceptible", "infected", and "recovered". max_y_axis: Optional maximum value for the Y axis of the chart. use_log_scale: Set to true to use a logarithmic scale on the Y axis. Default is linear scale. Returns: The newly created chart. """ adjusted_sim_sir_w_date_floor_df = __adjust_data_for_log_scale( sim_sir_w_date_floor_df) if use_log_scale else sim_sir_w_date_floor_df y_scale = __build_y_scale(alt, max_y_axis, use_log_scale) x = dict(shorthand="date:T", title=i18n.t("charts-date"), axis=alt.Axis(format=(DATE_FORMAT))) y = dict(shorthand="value:Q", title=i18n.t("charts-count"), scale=y_scale) color = "key:N" tooltip = ["key:N", "value:Q"] # TODO fix the fold to allow any number of dispositions points = (alt.Chart().transform_fold( fold=[i18n.t("susceptible"), i18n.t("infected"), i18n.t("recovered")]).encode(x=alt.X(**x), y=alt.Y(**y), color=color, tooltip=tooltip).mark_line().encode( x=alt.X(**x), y=alt.Y(**y), color=color, tooltip=tooltip, )) bar = (alt.Chart().encode(x=alt.X(**x)).transform_filter( alt.datum.day == 0).mark_rule(color="black", opacity=0.35, size=2)) sim_sir_w_date_floor_df_renamed = adjusted_sim_sir_w_date_floor_df.rename( { "susceptible": i18n.t("susceptible"), "infected": i18n.t("infected"), "recovered": i18n.t("recovered") }, axis=1) return (alt.layer(points, bar, data=sim_sir_w_date_floor_df_renamed).configure_legend( orient="bottom").interactive())
def statesMenu(): ms = QMenu() actions = [] act = ms.addAction(i18n.t('E.stateClone')) actions.append(act) act = ms.addAction(i18n.t('E.stateMoveLeft')) actions.append(act) act = ms.addAction(i18n.t('E.stateMoveRight')) actions.append(act) ms.addSeparator() act = ms.addAction(i18n.t('E.stateDelete')) actions.append(act) return ms, actions
def start(self, update, context): context.bot.send_message( chat_id=update.effective_chat.id, text=i18n.t( "bot_welcome", name=context.bot.first_name, username=context.bot.username, ), )
def handle(self, handler_input): # type: (HandlerInput) -> Response speak_output = i18n.t("strings.GOODBYE_MSG") return ( handler_input.response_builder .speak(speak_output) .response )
def start(message): user_lang(message) data = select_user(db, table, message.from_user.id, '*') try: aux1 = data[2] aux2 = data[3] except: aux1 = ' ' aux2 = ' ' if len(aux1) < 3 or len(aux2) < 3: msg = bot.send_message(message.from_user.id, i18n.t('bot.startnewuser'), parse_mode='HTML') bot.register_next_step_handler(msg, add_email) else: bot.send_message(message.from_user.id, i18n.t('bot.startolduser').format( str(u'\U0001F4E4'), data[2], str(u'\U0001F4E5'), data[3] ), parse_mode='HTML', reply_markup=button)
def generic_file(message): user_lang = (message.from_user.language_code or "en-us").lower() #bot.send_chat_action(message.chat.id, "typing") try: get_file(message) except: bot.send_message(message.chat.id, i18n.t("bot.filenotfound", locale=user_lang))
def hash_seguidores(self, hashtags): while True: seleciona_tarefa = input(i18n.t('hash_seguidores')) if seleciona_tarefa == '1': print( '\n--------------------------------------------------------------------------------\n' ) self.hash_local_trends(hashtags) print( '\n--------------------------------------------------------------------------------\n' ) return 'com_hashtags(hashtags, tipo_busca, primeira_palavra, complemento, ' \ 'emoji, username, password, modo_bot, linguagem, navegador, inicio)' elif seleciona_tarefa == '2': return 'com_perfil(perfis, tipo_busca, primeira_palavra, complemento, ' \ 'emoji, username, password, modo_bot, linguagem, navegador, inicio)' else: print(i18n.t('invalid_value'))
async def on_ready(): channel = client.get_channel(int(os.environ.get("DISCORD_CHANNEL_ID"))) now = dt.now() now = now.astimezone(timezone('UTC')) await channel.send(i18n.t('kaggle.hi', hour=now.hour)) competitions_list = api.competitions_list() for competition in competitions_list: if getattr(competition, 'awardsPoints') and not getattr( competition, 'submissionsDisabled'): deadline = getattr(competition, 'deadline') deadline = deadline.astimezone(timezone('UTC')) diff = deadline - now if diff.days > 0: await channel.send('{}: {}'.format( i18n.t('kaggle.to_go', days=diff.days), getattr(competition, 'title'))) print('We have logged in as {0.user}'.format(client)) sys.exit(0)
def get_to_menu_kbd(lang='ua'): return types.InlineKeyboardMarkup( row_width=1, inline_keyboard=( ( types.InlineKeyboardButton(t('BACK_TO_MENU_BTN', locale=lang), callback_data='Menu'), ), ) )
def get_format(args, place=2): format = 'n3' if len(args) >= place: _format = args[place-1].strip() if _format in rdftools.FORMATS: format = _format else: warning(i18n.t('shell.invalid_format', format=_format)) return format
def deleteFavorite(**kwargs): if kwargs is not None: db = None try: db = lite.connect(dbname) db.text_factory = str cursor = db.cursor() if kwargs.has_key("name"): script = kwargs["name"] cursor.execute(''' DELETE FROM favorites WHERE name=? ''',(script,)) db.commit() if cursor.rowcount == 1: print "[+] "+script+" "+i18n.t("setup.del_fav_ok") except Exception, e: print "[-] "+script+" "+i18n.t("setup.del_fav_error") finally:
def parse(context, args): """ parse filename [format=n3] Read a file into the current context graph.""" args2 = args.strip().split() format = get_format(args2) if len(args2) >= 1: try: context.graph = rdftools.read_into( SimpleFile(args2[0]), format, context.graph, context.base) info(i18n.t('shell.graph_updated', len=len(context.graph))) except SyntaxError as ex: error(i18n.t('shell.file_read_err', err=ex)) except IOError as ex: error(i18n.t('shell.file_read_err', err=ex)) else: warning(i18n.t('shell.invalid_params')) return context
async def current(ctx: commands.Context): reset_leave_timer() if _player: song = _player.get_current() if song: playtime = utils.to_human_readable_position( _player.get_playtime(), ctx.guild.preferred_locale) length = utils.to_human_readable_position( song.get_length(), ctx.guild.preferred_locale) await ctx.send( t("commands.current", locale=ctx.guild.preferred_locale, desc=song.get_song_description(), pos=playtime, len=length)) return await ctx.send( t("commands.current_no_song", locale=ctx.guild.preferred_locale))
async def exec(): try: await ctx.channel.edit(topic=t("commands.channel_topic_playing", locale=ctx.guild.preferred_locale, desc=song.get_song_description())) except discord.Forbidden: _logger.warning( "Unable to edit channel description to current song (missing permission)" )
def verify(info, finding_id: str, vulnerabilities: List[Dict[str, str]], closed_vulns: List[str], date) -> List[bool]: finding = finding_dal.get_finding(finding_id) success = [ update_vuln_state(info, [vuln], {'state': 'closed'}, finding_id, date) for vuln in vulnerabilities if vuln.get('UUID') in closed_vulns ] finding_utils.send_finding_verified_email( finding_id, str(finding.get('finding', '')), str(finding.get('project_name', ''))) project_users = project_dal.get_users(str(finding.get('project_name', ''))) notifications.notify_mobile( project_users, t('notifications.verified.title'), t('notifications.verified.content', finding=str(finding.get('finding', '')), project=str(finding.get('project_name', '')).upper())) return success
def execute(self): obj_id = input(i18n.t('ENTER_THE_ID_OF_THE_ARTICLE')) obj_article = self.base.get_article_by_id(obj_id) if obj_article: state = i18n.t( 'ARTICLE_AVAILABLE') if obj_article.is_available else i18n.t( 'ARTICLE_NOT_AVAILABLE') if obj_article.is_available: quantity = int(input(i18n.t('HOW_MANY_TO_BORROW'))) if obj_article.quantity > quantity: new_obj = self.base.add_article_quantity( obj_id, (-1 * quantity), True) if new_obj: self.base.remove_article_by_id(obj_id) self.base.add_article(new_obj) self.logger.add_log( obj_id, Log(str(datetime.date(datetime.now())), "Borrowed " + str(quantity))) self.app_info_logger.log_info(i18n.t('ARTICLES_BORROWED')) IOWrapper.continue_pause() elif obj_article.quantity == quantity: new_obj = self.base.add_article_quantity( obj_id, (-1 * quantity), False) if new_obj: self.base.remove_article_by_id(obj_id) self.base.add_article(new_obj) self.logger.add_log( obj_id, Log(str(datetime.date(datetime.now())), "Borrowed " + str(quantity))) self.logger.add_log( obj_id, Log(str(datetime.date(datetime.now())), "Made article unavailable")) self.app_info_logger.log_info(i18n.t('ARTICLES_BORROWED')) IOWrapper.continue_pause() elif obj_article.quantity < quantity: self.app_info_logger.log_info( i18n.t('NOT_ENOUGH_ARTICLE_AVAILABLE')) IOWrapper.continue_pause() else: self.app_info_logger.log_info(i18n.t('ARTICLE_NOT_AVAILABLE')) IOWrapper.continue_pause() else: self.app_info_logger.log_info(i18n.t('ARTICLE_OF_ID_LACKING')) IOWrapper.continue_pause()
def get_file(message): user_lang(message) if message.content_type == 'document': file_size = message.document.file_size file_name = message.document.file_name document = Document(file_name) document_dict[str(message.from_user.id)] = document bot.reply_to( message, str(u'\U00002705') + 'Downloaded ' + str(file_size) + ' bytes.') bot.send_chat_action(message.from_user.id, 'upload_document') if file_size > 20000000: bot.send_message(message.from_user.id, i18n.t('bot.fsize'), parse_mode='HTML', disable_web_page_preview=True) return 0 file_info = bot.get_file(message.document.file_id) file_url = ('https://api.telegram.org/file/bot' + TOKEN + '/' + file_info.file_path) # print(file_url) elif message.content_type == 'text': if message.text.lower() in cmds: return 0 file_url = message.text else: msg = bot.send_message(message.from_user.id, i18n.t('bot.askfile')) bot.register_next_step_handler(msg, get_file) return 0 # data = select_user(db, table, message.from_user.id, '*') # f = requests.get(file_url) upd_user_file(db, table, message.from_user.id, file_url) # print(file_url) if '.pdf' in file_url.lower(): msg = bot.send_message(message.from_user.id, i18n.t('bot.askconvert'), parse_mode='HTML', reply_markup=button2) else: data = select_user(db, table, message.from_user.id, '*') send_mail(str(message.from_user.id), data[2], data[3], ' ', str(message.from_user.id), data[7])
def com_local(local, tipo_busca, primeira_palavra, complemento, emoji, username, password, modo_bot, linguagem, navegador, inicio): instagram = InstagramBot(username, password, modo_bot, linguagem, navegador, inicio) time.sleep(5) instagram.login() while True: if len(local) != 0: try: tag = random.choice(local) regex_tag = tag.replace( 'https://www.instagram.com/explore/locations/', '').split('/') print( '--------------------------------------------------------------------------------' ) print(f'\nLocal: 📍{regex_tag[1]} ' + i18n.t('com_hashtags_inicia') + ' ' + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '\n') instagram.selecionar_fotos_local(tag) print( f'{i18n.t("num_com_hashtags_coletadas")} {len(instagram.pic_hrefs)} \n' ) instagram.tabela_stdout() eval('instagram.' + tipo_busca) print('\n----------------------------------------\n') print(f'\nLocal: 📍{regex_tag[1]} ' + i18n.t('lista_com_locais_acabou') + datetime.now().strftime("%Y-%m-%d %H:%M:%S")) print( '\n--------------------------------------------------------------------------------\n' ) local.remove(tag) instagram.limpar_urefs() except Exception as e: print(f'\n {e} \n') instagram.deu_ruim() else: instagram.close_browser() print( i18n.t('lista_com_hashtags_acabou') + datetime.now().strftime("%Y-%m-%d %H:%M:%S")) sys.exit()
def main(): (LOG, cmd) = rdftools.startup('scripts.query_command', add_args) graph = rdftools.read_all(cmd.input, cmd.read) LOG.info(i18n.t('scripts.query_started')) LOG.debug(cmd.query) start = timer() results = graph.query(cmd.query) end = timer() LOG.debug(i18n.t('scripts.query_rows', len=len(results))) if len(results) > 0: columns = results.bindings[0].keys() LOG.debug( i18n.t('scripts.query_columns', names=', '.join([str(c) for c in columns]))) rdftools.report(columns, results, end - start) else: print(i18n.t('scripts.query_no_results'))
def notifyset(msg): find = db.users.find_one({"id": str(msg.chat.id)}) i18n.set("locale", find["lang"]) if find["notify"]: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.onn"), i18n.t("msg.setl")) db.users.update({"id": str(msg.chat.id)}, {"$set": {"notify": False}}) bot.send_message(msg.chat.id, i18n.t("msg.disabled"), reply_markup=markup) else: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.offn"), i18n.t("msg.setl")) db.users.update({"id": str(msg.chat.id)}, {"$set": {"notify": True}}) bot.send_message(msg.chat.id, i18n.t("msg.enabled"), reply_markup=markup)
def get_queues_kbd(queues, my_queues=False, lang='ua'): queues = filter(lambda x: x['active'], queues) kbd = list(types.InlineKeyboardButton(queue['name'], callback_data=f'GetMyQueue{queue["id"]}' if my_queues else f'GetQueue{queue["id"]}') for queue in queues) return types.InlineKeyboardMarkup( row_width=2, inline_keyboard=list(divide_chunks(kbd, 2)) + [[types.InlineKeyboardButton(t('BACK_TO_MENU_BTN', locale=lang), callback_data='Menu')]] )
def speak(codes, *param, **key): lang = Config.get_current_lang(short=True) i18n.config.set( 'load_path', ['/home/pi/mopidy-rstation/mopidy_rstation/audio/i18n']) i18n.config.set('locale', lang) i18n.config.set("encoding", "utf-8") val = '' text = '' if ('val' in key): val = key['val'] if isinstance(val, int): val = str(val) val = convert_text(val) if type(codes) == list: for code in codes: text = text + i18n.t('voice.' + code) + ' ' else: text = i18n.t('voice.' + codes) speak_text(text + ' ' + val)
def add_email(message): user_lang(message) if '/' not in message.text: data = select_user(db, table, message.from_user.id, '*') if validate_email(message.text.lower()): if '@kindle.com' in message.text.lower(): upd_user_email(db, table, message.from_user.id, '"' + str(message.text) + '"') # check = select_user(db, table, message.from_user.id, # 'remetente') if len(data[3]) < 5: msg = bot.reply_to(message, i18n.t('bot.askemail')) bot.register_next_step_handler(msg, add_email) return 0 msg = bot.reply_to(message, str(u'\U00002705') + i18n.t('bot.success'), parse_mode='HTML', reply_markup=button) # elif len(data[3]) < 5: # msg = bot.reply_to(message, # 'Type your email used on your Amazon account.') # bot.register_next_step_handler(msg, add_email) # return 0 else: upd_user_email(db, table, message.from_user.id, '"' + str(message.text) + '"') msg = bot.reply_to(message, str(u'\U00002705') + i18n.t('bot.success'), parse_mode='HTML', reply_markup=button) else: msg = bot.send_message(message.from_user.id, str(u'\U000026A0') + i18n.t('bot.askemail'), parse_mode='HTML') bot.register_next_step_handler(msg, add_email) else: msg = bot.send_message(message.from_user.id, i18n.t('bot.askemail'), parse_mode='HTML') bot.register_next_step_handler(msg, add_email)
def handle(self, handler_input): # type: (HandlerInput) -> Response speak_output = i18n.t("strings.HELLO_MSG") return ( handler_input.response_builder .speak(speak_output) # .ask("add a reprompt if you want to keep the session open for the user to respond") .response )
def deleteFavorite(**kwargs): if kwargs is not None: db = None try: db = lite.connect(dbname) db.text_factory = str cursor = db.cursor() if kwargs.has_key("name"): script = kwargs["name"] cursor.execute( ''' DELETE FROM favorites WHERE name=? ''', (script, )) db.commit() if cursor.rowcount == 1: print "[+] " + script + " " + i18n.t("setup.del_fav_ok") except Exception, e: print "[-] " + script + " " + i18n.t("setup.del_fav_error") finally:
async def skip(ctx, number_of_songs: Optional[int]): reset_leave_timer() if _player: current = _player.get_current() if current: _player.skip() queue = _player.get_queue() if number_of_songs is not None and number_of_songs > 1: # Remove the first (number_of_songs - 1) songs from the queue for i in range(number_of_songs - 1): if queue.get_next() is None: break await ctx.send( t("commands.skip_to", locale=ctx.guild.preferred_locale, num=number_of_songs)) elif current: await ctx.send( t("commands.skip_single", locale=ctx.guild.preferred_locale))
async def on_command_error(ctx, error: BaseException): _logger.error(f"Exception occurred during command: {error}") # Handle all remaining exceptions root_error = error.__cause__ if error.__cause__ else error message = "\n".join( [str(root_error), *traceback.format_tb(root_error.__traceback__)]) await ctx.send( t("commands.general_error", locale=ctx.guild.preferred_locale, message=message))
def ask_file_call(call): user_lang = (call.from_user.language_code or "en-us").lower() try: bot.answer_callback_query(call.id) except: pass bot.send_message(call.from_user.id, i18n.t("bot.askfile", locale=user_lang))
def main(): global LOG (LOG, cmd) = rdftools.startup('shell.command', add_args=None, read_files=False) info(i18n.t('shell.welcome', version=rdftools.__VERSION__)) configure_readline() context = clear(None, None) context.base = cmd.base parse_cmdfile(context, os.path.join(os.path.expanduser("~"), ".rdfshrc")) run_loop(context)
def inner(*args, **kwargs): original_member = args[2].bot.get_chat_member( args[1].effective_chat.id, args[1].effective_user.id) if original_member["status"] not in ("creator", "administrator"): args[2].bot.answer_callback_query( callback_query_id=args[1].callback_query.id, text=i18n.t("not_permitted"), ) return return func(*args, **kwargs)
def updateApp(): print i18n.t("setup.checking_db")+" "+dbname db = None try: cursor = __dbconnect()['cursor'] # Create Favorite Table cursor.execute(''' create table if not exists favorites (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,name TEXT NOT NULL UNIQUE, ranking TEXT NOT NULL) ''') if hashlib.md5(open(filePath, 'rb').read()).hexdigest() == currentChecksum: print i18n.t("setup.db_is_update")+" "+dbname else: print i18n.t("setup.update_db") cursor.executescript(''' DROP TABLE IF EXISTS scripts; DELETE FROM SQLITE_SEQUENCE WHERE name='scripts'; DROP TABLE IF EXISTS categories; DELETE FROM SQLITE_SEQUENCE WHERE name='categories'; DROP TABLE IF EXISTS script_category; DELETE FROM SQLITE_SEQUENCE WHERE name='script_category'; ''') __dbconnect()['db'].commit() __dbconnect()['db'].close() initSetup() except Exception, e: print "Error %s:" % e.args[0]
def createBackUp(): print i18n.t("setup.create_backup") shutil.copy2(filePath, fileBackup) if os.path.isfile(fileBackup): print i18n.t("setup.create_backup_ok") else: print i18n.t("setup.create_backup_error")
def updateFavorite(**kwargs): if kwargs is not None: sql = None db = None try: db = lite.connect(dbname) db.text_factory = str cursor = db.cursor() if kwargs.has_key("name") and kwargs.has_key("newname") and kwargs.has_key("newranking"): script = kwargs["name"] newname = kwargs["newname"] newranking = kwargs["newranking"] cursor.execute(''' UPDATE favorites SET name=?, ranking=? WHERE name=? ''', (newname, newranking, script,)) elif kwargs.has_key("name") and kwargs.has_key("newname"): script = kwargs["name"] newname = kwargs["newname"] cursor.execute(''' UPDATE favorites SET name=? WHERE name=? ''', (newname, script,)) elif kwargs.has_key("name") and kwargs.has_key("newranking"): script = kwargs["name"] newranking = kwargs["newranking"] cursor.execute(''' UPDATE favorites SET ranking=? WHERE name=? ''', (newranking, script,)) else: print "Bad Params" db.commit() if cursor.rowcount == 1: print "[+] "+script+" "+i18n.t("setup.update_fav_ok") except Exception, e: print "Error %s:" % e.args[0] print "[-] "+script+" "+i18n.t("setup.update_fav_error") finally:
def insertScriptCategory(scriptid,categoryid): db = None try: db = lite.connect(dbname) cursor = db.cursor() cursor.execute(''' INSERT INTO script_category (id_category,id_script) VALUES (?,?) ''',(categoryid,scriptid,)) db.commit() if cursor.rowcount == 1: print "[+] "+str(categoryid)+" "+i18n.t("setup.update_fav_ok") except Exception, e: if db: db.rollback() print "Error %s:" % e.args[0]
def ask_file(message): user_lang(message) msg = bot.send_message(message.from_user.id, i18n.t('bot.askfile')) bot.register_next_step_handler(msg, get_file)
def help(message): user_lang(message) bot.send_message(message.from_user.id, i18n.t('bot.info'), parse_mode='HTML', disable_web_page_preview=True)
def send_mail(chatid, send_from, send_to, subject, text, file_url): if len(send_from) < 5 or len(send_to) < 5: bot.send_message(chatid, i18n.t('bot.error'), parse_mode='HTML') return 0 msg = MIMEMultipart() msg['From'] = send_from msg['To'] = send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText('Send2KindleBot')) try: files = open_file(file_url, chatid) except: bot.send_message(chatid, i18n.t('bot.filenotfound')) return 0 bot.send_chat_action(chatid, 'upload_document') bot.send_message(chatid, str(u'\U0001F5DE') + i18n.t('bot.sendingfile'), parse_mode='HTML') part = MIMEBase('application', 'octet-stream') part.set_payload(open(files, 'rb').read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(files))) msg.attach(part) smtp = smtplib.SMTP('127.0.0.1') try: smtp.sendmail(send_from, send_to, msg.as_string()) except smtplib.SMTPRecipientsRefused: msg = bot.send_message(chatid, str(u'\U000026A0') + i18n.t('bot.checkemail'), parse_mode='HTML') smtp.close() logger_info.info(str(datetime.datetime.now()) + '\tError:\t' + str(chatid) + '\t' + send_from + '\t' + send_to) upd_user_last(db, table, chatid) return 0 smtp.close() upd_user_last(db, table, chatid) logger_info.info(str(datetime.datetime.now()) + '\tSENT:\t' + str(chatid) + '\t' + send_from + '\t' + send_to) try: os.remove(files) except FileNotFoundError: pass msg = ( '{icon_x} {msg_a}\n\n' '{icon_y} {msg_b}\n\n' '{icon_z} {msg_c}' ).format( icon_x=u'\U0001F4EE', icon_y=u'\U00002B50', icon_z=u'\U0001F4B5', msg_a=i18n.t('bot.filesent'), msg_b=i18n.t('bot.rate'), msg_c=i18n.t('bot.donate'), ) bot.send_message(chatid, msg, parse_mode='HTML', reply_markup=button, disable_web_page_preview=True)
def ask_file(call): bot.answer_callback_query(call.id) msg = bot.send_message(call.from_user.id, i18n.t('bot.askfile')) bot.register_next_step_handler(msg, get_file)
def initSetup(): print i18n.t("setup.create_db")+" "+dbname db = None try: cursor = __dbconnect()['cursor'] # Create Script Table cursor.execute(''' create table if not exists scripts(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,name TEXT NOT NULL, author TEXT NULL) ''') print i18n.t("setup.create_script_table") # Create Categories Table cursor.execute('''create table if not exists categories( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL) ''') print i18n.t("setup.create_category_table") # Create Script/Category Table cursor.execute('''create table if not exists script_category( id_category INTEGER NOT NULL, id_script INETGER NOT NULL) ''') print i18n.t("setup.create_category_script_table") print i18n.t("setup.upload_categories") for category in categories: cursor.execute(''' INSERT INTO categories (name) VALUES (?) ''',(category,)) # Create Favorite Table print i18n.t("setup.create_favorites_table") cursor.execute(''' create table if not exists favorites (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,name TEXT NOT NULL UNIQUE, ranking TEXT NOT NULL) ''') __dbconnect()['db'].commit() setData() createBackUp() except Exception, e: print "Error %s:" % e.args[0] sys.exit(1)
def ask_email(message): user_lang(message) msg = bot.send_message(message.from_user.id, i18n.t('bot.askemail')) bot.register_next_step_handler(msg, add_email)
def email(call): bot.answer_callback_query(call.id) msg = bot.send_message(call.from_user.id, i18n.t('bot.askemail3')) bot.register_next_step_handler(msg, add_email)