def construct_cities_list(cities_list, page_num): keyboard = [] list_len = len(cities_list) buttons_per_page = 5 if list_len <= buttons_per_page: for city in cities_list: keyboard.append([InlineKeyboardButton(str(city), callback_data=str(city))]) else: # compute first and last indexes last_index = page_num * buttons_per_page first_index = last_index - buttons_per_page # extract the cities for the page page_list = cities_list[first_index:last_index] # add cities for city in page_list: keyboard.append([InlineKeyboardButton(str(city), callback_data=str(city))]) # add navigation footer navigation_footer = [InlineKeyboardButton(emojis.encode(":arrow_left:"), callback_data="city_list_back"), InlineKeyboardButton(f"{last_index}/{list_len}", callback_data="do_nothing"), InlineKeyboardButton(emojis.encode(":arrow_right:"), callback_data="city_list_forward")] keyboard.append(navigation_footer) return keyboard
async def emojify2(self, ctx, *args): """Emojifies text. Syntax: //emojify <args>""" output = "" text = ' '.join(args) emojiList = sorted([ a[1:-1] for a in list(emojis.db.get_emoji_aliases().keys()) ])[::-1] while text: recent = None for emoji in emojiList: if text.startswith(emoji): recent = ':' + emoji + ': ' text = text[len(emoji):] break else: if text[0].lower() not in 'qwertyuiopasdfghjklxcvbnm': recent = text[0] else: recent = ':regional_indicator_' + text[0].lower() + ': ' text = text[1:] if len(output) + len(emojis.encode(recent)) > 2000: await ctx.send(output) output = "" output += emojis.encode(recent) await ctx.send(output)
async def send_slide(ctx, bot, direction="Forward"): if bot.curr_slide < 0 or bot.curr_slide >= len(bot.quiz_file): reply = await create_colored_message( f"Slide index out of range.\n\n" + f"Try in range [1, {len(bot.quiz_file)}]", swearing=False ) await ctx.send(reply) return with io.BytesIO() as image_binary: image = bot.quiz_file[bot.curr_slide] image.save(image_binary, "JPEG") image_binary.seek(0) reply = await create_colored_message( f"Slide {bot.curr_slide + 1}", swearing=False ) await ctx.send(reply) message = await ctx.send( file=discord.File( fp=image_binary, filename=f"Slide_{bot.curr_slide}.jpg" ) ) await message.add_reaction(emojis.encode(":arrow_backward:")) await message.add_reaction(emojis.encode(":arrow_forward:")) return message
def send_text(bot, update): # bot.send_chat_action(chat_id=update.effective_user.id, action=telegram.ChatAction.TYPING) tag = update.message.text # Data data = get_url(tag) if data == {}: bot.send_message(chat_id=update.message.chat_id, text="Sorry, nothing was found") url = list(data.values()) song = list(data.keys()) names = '\n'.join(song[:10]) # change to data {} button_list = [ InlineKeyboardButton(str(index + 1), callback_data=x) for index, x in enumerate(url[:10]) ] footer_buttons = [ InlineKeyboardButton(emojis.encode(':arrow_left:'), callback_data=1), InlineKeyboardButton(emojis.encode(':x:'), callback_data=0), InlineKeyboardButton(emojis.encode(':arrow_right:'), callback_data=tag + ',2') ] reply_markup = InlineKeyboardMarkup( build_menu(button_list, n_cols=5, footer_buttons=footer_buttons)) bot.send_message(chat_id=update.message.chat_id, text=names, reply_markup=reply_markup)
async def run(self): try: chats = await self.client.get_dialogs() except sqlite3.OperationalError: self.stdscr.addstr("Database is locked. Cannot connect with this session. Aborting") self.stdscr.refresh() await self.textinput() await self.quit() self.dialogs = [ { "dialog": dialog, "unread_count": dialog.unread_count, "online": dialog.entity.status.to_dict()["_"] == "UserStatusOnline" if hasattr(dialog.entity, "status") and dialog.entity.status else None, "online_until": None, # "last_seen": dialog.entity.status.to_dict()["was_online"] if online == False else None, } for dialog in chats ] await self.drawtool.redraw() self.ready = True while True: s = await self.textinput() if self.fin: return if s.startswith("r"): try: num = int(s[1:].split()[0]) except: continue s = s.replace("r" + str(num) + " ", "") reply_msg = self.dialogs[self.selected_chat]["messages"][num] s = emojis.encode(s) reply = await reply_msg.reply(s) await self.on_message(reply) elif s.startswith("media"): try: num = int(s[5:].split()[0]) except: continue message = self.dialogs[self.selected_chat]["messages"][num] if message.media: os.makedirs("/tmp/tttc/", exist_ok=True) path = await self.client.download_media(message.media, "/tmp/tttc/") # TODO mute calls if message.media.photo: sizes = message.media.photo.sizes w, h = sizes[0].w, sizes[0].h # w, h basesize = 1500 w3m_command=f"0;1;0;0;{basesize};{int(basesize*h/w)};;;;;{path}\n4;\n3;" W3MIMGDISPLAY="/usr/lib/w3m/w3mimgdisplay" os.system(f"echo -e '{w3m_command}' | {W3MIMGDISPLAY} & disown") await self.textinput() else: subprocess.call(["xdg-open", "{shlex.quote(path)}"], stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL) #os.system(f"(xdg-open {shlex.quote(path)} 2>&1 > /dev/null) & disown") else: s = emojis.encode(s) outgoing_message = await self.dialogs[self.selected_chat]["dialog"].send_message(s) await self.on_message(outgoing_message) await self.drawtool.redraw()
def check_portata(stato_rubinetto): if (stato_rubinetto == "on") and (float(portata) == 0.0): botLogger.warning("rubinetto: on >>> acqua: no") notifica_utenti(emojis.encode(":warning:problemi al rubinetto! Non sta passando acqua...:warning:")) elif (stato_rubinetto == "off") and (float(portata) > 0.0): botLogger.warning("rubinetto: off >>> acqua: yes") notifica_utenti(emojis.encode(":warning:problemi al rubinetto! Sta passando acqua...:warning:"))
def _show_check_result(tool): code, output = shell.execute(tool, no_exception=True) if not config.QUIET: print(f'{output.rstrip()} ', end='') print(emojis.encode(':heavy_check_mark:')) if code == 0 else print( emojis.encode(':x:')) elif code != 0: raise Exception(f'{code}, {output}')
def _get_geoj(self) -> Dict[str, Union[str, list]]: """ Downloads and processes the geojson file downloaded form self.url. Processing is done by stripping all locations which are not in self.wanted_coordinates. Returns: Dict[str, Union[str, list]]: The stripped geojson file. """ try: request = requests.get(self.geoj_url) request.raise_for_status() data = json.loads(request.text) # only keep the stations that are wanted filtered_data = [ feature for feature in data["features"] if str(feature["properties"]["idEstacao"]) in self.wanted_stations ] data["features"] = filtered_data # set with all unique stationID's that were retrieved filtered_stations = set( str(feature["properties"]["idEstacao"]) for feature in data["features"] ) # if there are coordinates wanted but they are not found in the geojson file this is printed not_available = self.wanted_stations - filtered_stations if not_available: if not_available == self.wanted_stations: print( emojis.encode(":x:"), f" {datetime.now()} none of the stations are available:", not_available, ) exit(1) else: print( emojis.encode(":warning:"), f" {datetime.now()} these stations are not available:", not_available, ) return data except requests.exceptions.HTTPError as err: print( emojis.encode(":x:"), f" {datetime.now()} could not request data, got errorcode: {request.status_code} and got HTTPError {err}", ) exit(1) except requests.ConnectionError as err: print( emojis.encode(":x:"), f" {datetime.now()} could not request data, got errorcode: {request.status_code} and got ConnectionError {err}", ) exit(1)
def get_name_list_after_update(): name_responses = [ f"Hi! {name_mentioned} fancy meeting you here" + emojis.encode(" :smile:"), f"Welcome {name_mentioned} " + emojis.encode(" :smile:"), f"Howdy {name_mentioned} :)" + emojis.encode(" :smile:"), f"{name_mentioned} ... I like that name" + emojis.encode(" :smile:"), f"{name_mentioned} What a beautiful name!" + emojis.encode(" :smile:") ] return {"animation": "excited", "msg": random.choice(name_responses)}
def send_welcome(message): bot.send_message( message.chat.id, "Bot for downloading music from the soundcloud.\n" "For example:\n" + emojis.encode(':black_circle:') + " Send track link: ****.com/gvibez/another-rainy-day\n" + emojis.encode(':white_circle:') + " In response, get the file. \n" + " Command: /about \n" + emojis.encode(':warning:') + " You can search track in soundcloud. Now this work in BETA." + emojis.encode(':warning:')) return None
class sd: iBan: str = emojis.encode(f" :information_source:{bc.BC} ") sBan: str = emojis.encode(f" :white_check_mark:{bc.BC} ") eBan: str = emojis.encode(f" :x:{bc.RC} ERROR:{bc.BC}") Author = f"{bc.BC}\n\t| Author:{bc.RC} 4{bc.GC}x{bc.BC}x{bc.RC}4{bc.GC}0{bc.BC}4 \t\t |\n" Version = f"{bc.BC}\t| Version:{bc.RC} 3{bc.GC}.{bc.BC}0 \t\t\t |\n" Github = f"{bc.BC}\t| Github:{bc.RC} h{bc.GC}t{bc.BC}t{bc.RC}p{bc.GC}s{bc.BC}:{bc.RC}/{bc.GC}/{bc.BC}g{bc.RC}i{bc.GC}t{bc.BC}h{bc.RC}u{bc.GC}b{bc.BC}.{bc.RC}c{bc.GC}o{bc.BC}m{bc.RC}/{bc.GC}4{bc.BC}x{bc.RC}x{bc.GC}4{bc.BC}0{bc.RC}4{bc.GC}/ {bc.BC}|\n" Logo = f'''{bc.BC}
async def status(gh, issue_url, reviewer): """get pull request info""" top_comment = await gh.getitem(issue_url) pull_body = top_comment["body"] """ update top comment """ if reviewer in pull_body: before = emojis.encode(":x:") + " | @" + reviewer after = emojis.encode(":white_check_mark:") + " | @" + reviewer new_body = pull_body.replace(before, after) await gh.patch(issue_url, data={"body": new_body})
def url(message): bot.send_message( message.chat.id, emojis.encode(':small_blue_diamond:') + " Author: Misha Kaday.\n" + emojis.encode(':small_orange_diamond:') + " Email: [email protected]\n" + emojis.encode(':small_blue_diamond:') + " Telegram: @MyNin\n" + emojis.encode(':envelope_with_arrow:') + " I will be glad to hear suggestions.", ) return None
def calculateStockDifference(stockX, stockY): if (stockX == stockY): return emojis.encode("stayed the same. :loop:") elif (stockX < stockY): return emojis.encode("gone down " + str(round(((1.0 - (stockX / stockY)) * 100), 2)) + "%. :chart_with_downwards_trend:") else: return emojis.encode("gone up " + str(round((1.0 - (stockY / stockX)) * 100, 2)) + "%. :chart_with_upwards_trend:")
def on_callback_query(msg): query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query') sos = emojis.encode(":sos:") CD = emojis.encode(":minidisc:") chat_id = msg['message']['chat']['id'] name = msg['message']['from']['first_name'] click = ''.join(query_data) click = click.split(' ') bot.answerCallbackQuery(query_id) sites = ['https://www.youtube.com/', 'https://www.mercadolivre.com.br/', 'https://open.spotify.com/', 'https://pagseguro.uol.com.br/', 'https://www.netflix.com/br/', 'http://www.superflix.net/', 'https://www.thingiverse.com/explore/newest/3d-printing', 'https://komoda-eletro-eletronica.webnode.com/', 'https://ifttt.com/discover', 'https://blynk.io/en/getting-started'] if click[0] == 'go': bot.sendMessage(chat_id, f"https://www.google.com/search?q={click[1]}") bot.sendMessage(chat_id, 'Esta satisfeito com a pesquisa?') elif click[0] == 'wiki': bot.sendMessage(chat_id, f"https://pt.wikipedia.org/wiki/{click[1]}") elif query_data == 'L': bot.sendMessage(chat_id, "https://t.me/joinchat/Fj1EnkP5Kpfzs8IrrfPz2Q") elif query_data == 'SOS': bot.sendMessage(chat_id, 'Para pesquisar digite, ( hall pesquisar + o que deseja pesquisar) e ' 'aperte o botão de sua escolha!') bot.sendMessage(chat_id, "Digite (hall1 + nome) para receber os usuarios novos \nDigite hall2 " "para alertar usuarios sobre foto de perfil") bot.sendMessage(chat_id, text=sos) elif query_data == 'url': for i in sites: bot.sendMessage(chat_id, text=i) sleep(1.50) bot.sendMessage(chat_id, 'Por enquanto eu só conheço esses sites!') elif query_data == 'co': bot.sendMessage(chat_id, 'Conteúdo:', reply_markup=botao4()) elif query_data == 'M': bot.sendMessage(chat_id, '***OPÇÕES DO MENU CLIQUE***', reply_markup=botao2()) elif query_data == 'ha': bot.sendMessage(chat_id, 'https://anos-80.mp3cielo.com/') bot.sendMessage(chat_id, CD) elif query_data == 'mu': for i in audio[0:51]: bot.sendAudio(from_id, audio=i) bot.sendMessage(from_id, 'Por enquanto só enviarei esses!') bot.sendMessage(chat_id, f"Enviei no seu privado {name}") elif query_data == 'curs': bot.sendMessage(chat_id, f"Sem cursos no momento!") elif query_data == 'li': bot.sendMessage(chat_id, 'Ainda não tenho livros adicionados aqui!')
def on_callback_query(msg): query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query') sos = emojis.encode(":sos:") CD = emojis.encode(":minidisc:") chat_id = msg['message']['chat']['id'] click = ''.join(query_data) click = click.split(' ') bot.answerCallbackQuery(query_id) sites = ['https://www.youtube.com/', 'https://www.mercadolivre.com.br/', 'https://open.spotify.com/', 'https://komoda-eletro-eletronica.webnode.com/'] if click[0] == 'go': bot.sendMessage(chat_id, f"https://www.google.com/search?q={click[1]}") bot.sendMessage(chat_id, 'Esta satisfeito com a pesquisa?') elif click[0] == 'wiki': bot.sendMessage(chat_id, f"https://pt.wikipedia.org/wiki/{click[1]}") elif query_data == 'L': bot.sendMessage(chat_id, "https://t.me/joinchat/Fj1EnkP5Kpfzs8IrrfPz2Q") elif query_data == 'SOS': bot.sendMessage(chat_id, 'Para pesquisar digite, ( hall pesquisar + o que deseja pesquisar) e ' 'aperte o botão de sua escolha!') bot.sendMessage(chat_id, "Digite (hall1 + nome) para receber os usuarios novos \nDigite hall2 " "para alertar usuarios sobre foto de perfil") bot.sendMessage(chat_id, text=sos) elif query_data == 'url': for i in sites: bot.sendMessage(chat_id, text=i) sleep(1.50) bot.sendMessage(chat_id, 'Esses são os sites mais usados!') elif query_data == 'co': bot.sendMessage(chat_id, 'Conteúdo:', reply_markup=botao4()) elif query_data == 'M': bot.sendMessage(chat_id, '***OPÇÕES DO MENU CLIQUE***', reply_markup=botao2()) elif query_data == 'ha': bot.sendMessage(chat_id, 'https://anos-80.mp3cielo.com/') bot.sendMessage(chat_id, CD) elif query_data == 'mu': audio = abre_id('ID_music.txt') for i in audio[0:15]: bot.sendAudio(from_id, audio=i) bot.sendMessage(from_id, 'Por enquanto só enviarei esses!') bot.sendMessage(chat_id, f"Enviei no seu privado") elif query_data == 'curs': bot.sendMessage(chat_id, f"Sem cursos no momento! Procure nos arquivos do grupo que tem varios tutoriais") elif query_data == 'li': bot.sendMessage(chat_id, f"Sem HQs no momento!")
def command_weather(message): sent = MyBot.send_message( message.chat.id, emojis.encode( ":office: Masukkan pilihan kota \n:mag: Dengan format : Jakarta atau depok" )) MyBot.register_next_step_handler(sent, send_forecast)
def cancel_command(self, update: Update, context: CallbackContext) -> int: """Cancels and ends the conversation.""" reply_markup = self.tools.custom_keyboard() update.message.reply_text(encode(":thumbsup: Canceled!"), reply_markup=reply_markup) context.user_data.clear() return ConversationHandler.END
def start(self, update, context): reply_markup = self.tools.custom_keyboard() update.message.reply_text( encode(":arrow_down: Choose a function from the menu below"), reply_markup=reply_markup, )
def read_voice_cmd(): voice_text = '' print(emojis.encode('Listening...:speech_balloon:')) global error_occurrence try: with sr.Microphone() as source: audio = speech.listen(source=source, timeout=10, phrase_time_limit=5) voice_text = speech.recognize_google(audio) except sr.UnknownValueError: if error_occurrence == 0: play_sound(mp3_listening_problem_list) error_occurrence += 1 elif error_occurrence == 1: play_sound(mp3_struggling_list) error_occurrence += 1 except sr.RequestError as e: print('Network Error') except sr.WaitTimeoutError: if error_occurrence == 0: play_sound(mp3_listening_problem_list) error_occurrence += 1 elif error_occurrence == 1: play_sound(mp3_struggling_list) error_occurrence += 1 return voice_text
async def on_reaction_add(reaction, member): if bot.slide_message is None: return if reaction.message.id != bot.slide_message.id: return if member != bot.quizmaster: return if reaction.emoji == emojis.encode(":arrow_forward:"): bot.curr_slide += 1 bot.slide_message = await send_slide(reaction.message.channel, bot) elif reaction.emoji == emojis.encode(":arrow_backward:"): bot.curr_slide -= 1 bot.slide_message = await send_slide(reaction.message.channel, bot)
def deploy_rich(password, smtp_user, smtp_password, project): staging = False if project.find('staging.') == 0: staging = True project = project[8:] shell.execute( f'aws s3 cp s3://{config.BUCKET}/{project} {project} --storage-class STANDARD --recursive --profile {config.PROFILE} --force-glacier-transfer' ) shell.execute(f'tar xvf {project}/deployment.tar.gz') shell.execute(f'mv mapdata.mbtiles deployment/map/', no_exception=True) env = '' # TODO reuse installed credentials docker run {project_manager_1} env if password != 'secret': env = f'PASSWORD={password} ' if smtp_user and smtp_password: env = (f'{env}EMAIL_USER={smtp_user} ' f'EMAIL_PASSWORD={smtp_password} ' f'EMAIL_HOST=email-smtp.{config.REGION}.amazonaws.com ') dnsname = f'{project}.openremote.io' if staging: env = f'{env}DEPLOYMENT_NAME=staging.{project} ' else: env = f'{env}DEPLOYMENT_NAME={project} ' generate_password, password = _password(password, url=dnsname) if generate_password: env = f'{env}PASSWORD={password} ' shell.execute(f'{env}docker-compose up -d') if not config.DRY_RUN: print('\nStack deployed, waiting for startup to complete', end=' ') while _deploy_health(dnsname, 0) == 0: time.sleep(3) print('.', end='', flush=True) print(emojis.encode(':thumbsup:')) if config.VERBOSE is True: print(f'\nOpen https://{dnsname} and login with admin:{password}')
def incoming_sms(): body = str(request.values.get('Body', None)) number = request.values.get('From', None) resp = MessagingResponse() if not fetch(number): resp.message( emojis.encode( 'Hello!\nI\'m EMME!:ok_woman: How are you feeling today?')) post(number, body) return str(resp) print(number, body) try: r = json.loads(process(os.environ['iam_apikey'], body)) except: return '' li = r['keywords'] val = post_vals(li, body, number) if val > 0: resp.message(random.choice(responses_pos)) return str(resp) elif val <= 0: resp.message(random.choice(responses_neg)) return str(resp) else: return str(resp) return 'Just text me mate.'
def emoji_convert(string): pattern = re.compile(r'\s') words = pattern.split(string) result = '' for word in words: result += ' ' + emojis.encode(emojis_dict.get(word, word)) return result
def emoji_callback(update, context): chat_id = update.message.chat.id emojiset = g.get_emojis() for x in emojiset: x = f":{x}:" context.bot.send_message(chat_id=chat_id, text=emojis.encode(x)) time.sleep(0.1)
def press(press): if press == "Exit": chat.stop() if press == "Send": message = chat.getTextArea("t2") chat.clearTextArea("t2") chat.setTextArea("t1", "\n" + user + ": " + message) print(user + ": " + emojis.encode(message)) # Check if message is empty if message: # Encode the message then send it message = message.encode('utf-8') messageHeader = f"{len(message):<{HEADER_LENGTH}}".encode('utf-8') userSocket.send(messageHeader + message) else: try: while True: # Receive header header = userSocket.recv(HEADER_LENGTH) # Check if there is data present if not len(header): print('Server closed connection...') sys.exit() # Convert header to int value userLength = int(header.decode('utf-8').strip()) # Receive and decode username username = userSocket.recv(userLength).decode('utf-8') # Receive and decode message messageHeader = userSocket.recv(HEADER_LENGTH) messageLength = int(messageHeader.decode('utf-8').strip()) message = userSocket.recv(messageLength).decode('utf-8') # Print message chat.setTextArea("t1", "\n" + username + ": " + message) print(username + ": " + emojis.encode(message)) except IOError as e: # Check for exceptions if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK: print('Error: {}'.format(str(e))) sys.exit()
def start_loading() -> None: """ Draw loading icon """ this.loading_icon_win.erase() # refer to cheatsheet for more emojis https://www.webfx.com/tools/emoji-cheat-sheet/ this.loading_icon_win.addstr(0, 0, emojis.encode(':hourglass:'), curses.A_BLINK) this.loading_icon_win.refresh()
def modelCadena(cadena): spm.SentencePieceTrainer.train( '--input=tweets_clean.txt --model_prefix=m_word --model_type=word --vocab_size=2000 --normalization_rule_name=nfkc_cf' ) sp_word = spm.SentencePieceProcessor() sp_word.load('m_word.model') cleanCadena = cadena.strip() return (sp_word.encode_as_pieces(emojis.encode(cleanCadena)))
def __str__(self): """ Returns the symbolic representation of the card. """ if self.is_flipped: return self.symbol else: return emojis.encode(":black_circle:")
async def clues(ctx): if not bot.quiz_ongoing: reply = await create_colored_message("There's no ongoing quiz", swearing=bot.swearing) await ctx.send(reply) return if not bot.question_ongoing: reply = await create_colored_message("There's no ongoing question", swearing=bot.swearing) await ctx.send(reply) return reply = "```fix\nWant clues?```" message = await ctx.send(reply) await message.add_reaction(emojis.encode(":thumbsup:")) await message.add_reaction(emojis.encode(":thumbsdown:"))