async def r(ctx, arg): newlist = [] final = "\n" if arg.find("-"): newlist = sorted(requestAll(), key=itemgetter('cases'), reverse=True) cinco = newlist[:abs(int(splittedMsg[1]))] for i in cinco: if i["countryInfo"]["iso2"]: final += flag.flag(i["countryInfo"]["iso2"]) + " " + \ str(i["country"]) + ": " + str(i["cases"]) + "\n" else: final += "NA " + \ str(i["country"]) + ": " + str(i["cases"]) + "\n" else: newlist = sorted(requestAll(), key=itemgetter('cases'), reverse=False) cinco = newlist[:abs(int(splittedMsg[1]))] for i in cinco: if i["countryInfo"]["iso2"]: final += flag.flag(i["countryInfo"]["iso2"]) + " " + \ str(i["country"]) + ": " + str(i["cases"]) + "\n" else: final += "NA " + \ str(i["country"]) + ": " + str(i["cases"]) + "\n" ctx.send("*Covid 19 cases ranking per country*" + final, parse_mode='Markdown')
def set_locale(bot, ctx): if len(ctx.args) == 0: kbd = [] for locales in chunks(list(octobot.localization.AVAILABLE_LOCALES), 4): kbd_line = [] for locale in locales: l = Locale.parse(locale) try: emoji = flag.flag(l.territory) except AttributeError: emoji = flag.flag(locale) kbd_line.append( telegram.InlineKeyboardButton( text=emoji + l.display_name, callback_data=f"locale_set:{locale}")) kbd.append(kbd_line) ctx.reply("Available languages:", reply_markup=telegram.InlineKeyboardMarkup(kbd)) else: try: octobot.localization.set_chat_locale(ctx.chat.id, ctx.args[0]) except ValueError: ctx.reply(f"Invalid language {ctx.args[0]}.") else: ctx.reply( ctx.localize('Language "{locale}" set').format( locale=Locale.parse(ctx.args[0]).display_name))
def get_team_info(update, context): args = context.args try: name = ' '.join(x for x in args) if name == '': context.bot.send_message(chat_id=update.effective_chat.id, text='Oops, it seams your query is wrong') return team = team_about(name) if team is None: context.bot.send_message(chat_id=update.effective_chat.id, text='Oops, it seams your query is wrong') return except: context.bot.send_message(chat_id=update.effective_chat.id, text='Oops, it seams your query is wrong') return if team.logo is not None: try: context.bot.send_photo(chat_id=update.effective_chat.id, photo=team.logo) except: pass string = f'<b><code>{team.name}</code></b>\n' string += f"<i>Wins: {team.wins}, Losses: {team.losses}\n<b>W/L: {round(team.index, 2)}</b></i>\n" if team.country is not None: if team.country[0] == 'Europe': string += 'Country: 🇪🇺\n' else: try: string += "Country: {}\n".format( flag.flag( pycountry.countries.search_fuzzy(team.country[0] + ' ' + team.country[1]) [0].alpha_2)) except: try: string += "Country: {}\n".format( flag.flag( pycountry.countries.search_fuzzy( team.country[0])[0].alpha_2)) except: string += f'Country: {team.country[0]}\n' if team.coach is not None: string += "Coach: <b><code>{}</code></b>\n".format(team.coach) if team.captain is not None: string += "Captain: <b><code>{}</code></b>\n".format(team.captain) if len(team.players) == 0: string += 'Currently no active players' else: string += "Players:\n" for player in team.players: string += "<b><code>{}</code></b>\n".format(player) context.bot.send_message(chat_id=update.effective_chat.id, text=string, parse_mode='HTML')
def get_player_info(update, context): args = context.args try: name = ' '.join(x for x in args) if name == '': context.bot.send_message(chat_id=update.effective_chat.id, text='Oops, it seams your query is wrong') return player = get_player(name) if player is None: context.bot.send_message(chat_id=update.effective_chat.id, text='Oops, it seams your query is wrong') return except: context.bot.send_message(chat_id=update.effective_chat.id, text='Oops, it seams your query is wrong') return if player.photo is not None: context.bot.send_photo(chat_id=update.effective_chat.id, photo=player.photo) string = f'Name: <b><code>{player.name}</code></b>' if player.romanized is not None: string += f"(<i>{player.romanized}</i>)\n" else: string += '\n' string += f'Nickname: <b><code>{player.nick}</code></b>\n' if player.age is not None: string += f'Age: <i>{player.age}</i>\n' if player.country is not None: if player.country[0] == 'Europe': string += 'Country: 🇪 🇺 \n' else: try: string += "Country: {}\n".format( flag.flag( pycountry.countries.search_fuzzy( player.country[0] + ' ' + player.country[1])[0].alpha_2)) except: try: string += "Country: {}\n".format( flag.flag( pycountry.countries.search_fuzzy( player.country[0])[0].alpha_2)) except: string += f'Country: {player.country[0]}\n' string += 'Teams played for:\n' i = 0 for team in player.teams: i += 1 string += f'<b><code>{team}</code></b>{emoji.emojize(":star:", use_aliases=True) if i == len(player.teams) else ""}\n' context.bot.send_message(chat_id=update.effective_chat.id, text=string, parse_mode='HTML')
def map_country_code_to_flag(country_code: str) -> str: ''' Maps a country code to a corresponding emoji flag: truly modern. The function returns a blank, white flag if the country code doesn't exist in the iso3166 database. Keyword arguments: country_code (str): country code to return the flag for Returns: emoji_flag (str): the flag for the country code ''' if len(country_code) == 3: try: # try converting alpha-3 to alpha-2 alpha2 = iso3166.countries_by_alpha3[country_code].alpha2 except KeyError: return "🏳" else: # some codes may already be in alpha2 alpha2 = country_code # emoji flag corresponding to alpha-2 code emoji_flag = flag.flag(alpha2) # avoid sending some non-existent dynamically constructed garbage if len(emoji_flag) == 2: return emoji_flag logging.warning( f"Got non-existent country flag: alpha3={country_code} alpha2={alpha2}" ) return "🏳"
def get_emoji_country(territory): """ Gets an emoji for the country""" try: return flag.flag(convert(names=[territory], to="ISO2")) except ValueError: return ""
def get_clicks(): if BITLY_ACCESS_TOKEN == '': print "Missing Access Token" sys.exit(0) group_guid = BITLY_GROUP_GUID if group_guid == '': group_guid = get_default_group() click_data = get_group_countries(group_guid) city_data = get_group_cities(group_guid) total = 0 additional_metrics = {} for metric in click_data.get('metrics', []): total += metric['clicks'] icon = flag(metric['value']).encode('utf-8') additional_metrics[metric['value']] = "{} {} {}".format(icon, metric['clicks'], plural_or_singular(metric['clicks'])) print "{} | templateImage={}".format(total, CLICK_ICON) for country, metric in additional_metrics.items(): print "---" print metric for city_metric in city_data.get('metrics', []): if city_metric['country'] == country: print "- {}: {}".format(city_metric['city'], city_metric['clicks'])
def __init__(self, embed_colour, rank_info): """ AwesomenautsRank init Parameters ---------- embed_colour : int colour of embed rank_info : dict dictionary containing all attributes as string (except country_flag) """ self.player_name = rank_info.get('player_name', '') self.rank = int(rank_info.get('rank', 0)) self.games_played_current_season = int( rank_info.get('games_played_current_season', 0)) self.games_played_all_time = int( rank_info.get('games_played_all_time', 0)) self.win_percentage = float(rank_info.get('win_percentage', 0)) self.rating = int(rank_info.get('rating', 0)) self.league = rank_info.get('league', '') self.league_img_url = rank_info.get('league_img_url', '') self.favourite_naut = rank_info.get('favourite_naut', '') self.favourite_naut_img_url = rank_info.get('favourite_naut_img_url', '') self.country = rank_info.get('country', '') self.steam_profile_url = rank_info.get('steam_profile_url', '') if self.country: country = pycountry.countries.search_fuzzy(self.country)[0] self.country_flag = flag.flag(country.alpha_2) else: self.country_flag = '' self.embed = self.create_awesomenauts_rank_embed(embed_colour)
def status_query(index): if len(engine.shards) == 0: abort(404) # ask server try: host = engine.shards[index] except IndexError: abort(404) data = dict() data['countryCode'] = None data['status'] = None data['flag'] = None # query server location (if possible) ip = host.split('://')[1].split(':')[0] country = engine.getCountryFromIp(ip) data['flag'] = flag.flag(country) if country not in ['?', 'unknown' ] else '' # query server status try: html = requests.get(host + '/vtt/status', timeout=3) data['status'] = html.text except requests.exceptions.ReadTimeout as e: engine.logging.error('Server {0} seems to be offline'.format(host)) except requests.exceptions.ConnectionError as e: engine.logging.error('Server {0} seems to be offline'.format(host)) return data
def get_country_name_and_flag(phone): try: country = phone_country(phone) return flag.flag(country) + country except: None return flag.flagize(":MX: MX")
def country_info_csv_as_md(country_info_path): # Load tracking csv df = pd.read_csv(country_info_path) # Process columns df.loc[:, "second_dose"] = df.loc[:, "second_dose"].apply( lambda x: "✅" if x == 1 else "❌") df.loc[:, "data_source_url"] = df.loc[:, "data_source_url"].apply( lambda x: f"[{x}]({x})") # Rename + Reorder columns df = df.rename( columns={ "country": "Country", "data_source_url": "Source", "second_dose": "2-Dose", "last_update": "Last update", }) # Add flag flags = df["country_iso"].apply(lambda x: flag.flag(x)) df.loc[:, "Country"] = flags + " " + df.loc[:, "Country"] # Reorder columns df = df[["Country", "Source", "2-Dose", "Last update"]] df = df.sort_values("Last update", ascending=False) # Get markdown table_md = df.to_markdown(index=False) return table_md
def index_get(): cities = City.query.order_by(City.datetime.desc()).all() weather_data = [] for city in cities: r = get_weather_data(city.name) weather = { 'city': city.name, 'country': r['sys']['country'], 'flag': flag.flag(r['sys']['country']), 'temperature': r['main']['temp'], 'description': (r['weather'][0]['description']).title(), 'pressure': r['main']['pressure'], 'icon': r['weather'][0]['icon'], 'lon': r['coord']['lon'], 'lat': r['coord']['lat'], 'humidity': r['main']['humidity'], 'sunrise': r['sys']['sunrise'], 'sunset': r['sys']['sunset'], 'offset': r['timezone'], 'tz_sunrise': (datetime.utcfromtimestamp(int(r['sys']['sunrise']))+timedelta(seconds=r['timezone'])) .strftime('%Y-%m-%d %H:%M:%S'), 'tz_sunset': (datetime.utcfromtimestamp(int(r['sys']['sunset'])) + timedelta(seconds=r['timezone'])) .strftime('%Y-%m-%d %H:%M:%S'), 'wind_speed': r['wind']['speed'] } weather_data.append(weather) print(r) return render_template('weather.html', weather_data=weather_data)
async def covid(event): try: if event.pattern_match.group(1) == '': country = 'TR' else: country = event.pattern_match.group(1) bayrak = flag.flag(country) worldData = get('https://coronavirus-19-api.herokuapp.com/all').json() countryData = get( 'https://coronavirus-19-api.herokuapp.com/countries/' + pytz.country_names[country]).json() except: await event.edit(LANG['SOME_ERRORS']) return sonuclar = ( f"** {LANG['DATA']}**\n" + f"\n**{LANG['EARTH']}**\n" + f"**{LANG['CASE']}** `{worldData['cases']}`\n" + f"**{LANG['DEATH']}** `{worldData['deaths']}`\n" + f"**{LANG['HEAL']}** `{worldData['recovered']}`\n" + f"\n**{pytz.country_names[country]}**\n" + f"**{bayrak} {LANG['TR_ALL_CASES']}** `{countryData['cases']}`\n" + f"**{bayrak} {LANG['TR_CASES']}** `{countryData['todayCases']}`\n" + f"**{bayrak} {LANG['TR_CASE']}** `{countryData['active']}`\n" + f"**{bayrak} {LANG['TR_ALL_DEATHS']}** `{countryData['deaths']}`\n" + f"**{bayrak} {LANG['TR_DEATHS']}** `{countryData['todayDeaths']}`\n" + f"**{bayrak} {LANG['TR_HEAL']}** `{countryData['recovered']}`\n" + f"**{bayrak} Test Sayısı:** `{countryData['totalTests']}`") await event.edit(sonuclar)
def country_flag(code): if code is None: return '' try: value = flag.flag(code) except: # invalid code value = '' return value
def __init__(self, bot: commands.Bot): super(Translate, self).__init__(bot, __file__) self.translator = deepl.Translator( auth_key=Config.translate_deepl_api_key) self.supp_list = [ t.code for t in self.translator.get_target_languages() ] self.flag_to_code = { (flag.flag(c) if not "-" in c else flag.flag(c.split("-")[1])): c for c in self.supp_list } self.flag_to_code = {**self.flag_to_code, **special_flags} self.guilds_usage = {} if not self.clear_usage_task.is_running(): self.clear_usage_task.start()
async def airing_anim(message: Message): """ Get Airing Detail of Anime """ query = message.input_str if not query: await message.err("NameError: 'query' not defined") return vars_ = {"search": query, "asHtml": True, "type": "ANIME"} if query.isdigit(): vars_ = {"id": int(query), "asHtml": True, "type": "ANIME"} result = await return_json_senpai(ANIME_QUERY, vars_) error = result.get("errors") if error: await CLOG.log(f"**ANILIST RETURNED FOLLOWING ERROR:**\n\n`{error}`") error_sts = error[0].get("message") await message.err(f"[{error_sts}]") return data = result["data"]["Media"] # Airing Details mid = data.get("id") romaji = data["title"]["romaji"] english = data["title"]["english"] native = data["title"]["native"] status = data.get("status") episodes = data.get("episodes") country = data.get("countryOfOrigin") c_flag = cflag.flag(country) source = data.get("source") coverImg = data.get("coverImage")["extraLarge"] genres = data.get("genres") genre = genres[0] if len(genres) != 1: genre = ", ".join(genres) score = data.get("averageScore") air_on = None if data["nextAiringEpisode"]: nextAir = data["nextAiringEpisode"]["airingAt"] episode = data["nextAiringEpisode"]["episode"] air_on = make_it_rw(nextAir, True) title_ = english or romaji out = f"[{c_flag}] **{native}** \n (`{title_}`)" out += f"\n\n**ID:** `{mid}`" out += f"\n**Status:** `{status}`\n" out += f"**Source:** `{source}`\n" out += f"**Score:** `{score}`\n" out += f"**Genres:** `{genre}`\n" if air_on: out += f"**Airing Episode:** `[{episode}/{episodes}]`\n" out += f"\n`{air_on}`" if len(out) > 1024: await message.edit(out) return await message.reply_photo(coverImg, caption=out) await message.delete()
async def manga_arch(message: Message): """ Search Manga Info """ query = message.input_str if not query: await message.err("NameError: 'query' not defined") return vars_ = {"search": query, "asHtml": True} result = await return_json_senpai(MANGA_QUERY, vars_) error = result.get("errors") if error: await CLOG.log(f"**ANILIST RETURNED FOLLOWING ERROR:**\n\n`{error}`") error_sts = error[0].get("message") await message.err(f"[{error_sts}]") return data = result["data"]["Media"] # Data of all fields in returned json # pylint: disable=possibly-unused-variable idm = data.get("id") romaji = data["title"]["romaji"] english = data["title"]["english"] native = data["title"]["native"] status = data.get("status") synopsis = data.get("description") description = synopsis[:500] if len(synopsis) > 500: description += "..." volumes = data.get("volumes") chapters = data.get("chapters") score = data.get("averageScore") url = data.get("siteUrl") format_ = data.get("format") country = data.get("countryOfOrigin") source = data.get("source") c_flag = cflag.flag(country) name = f"""[{c_flag}]**{romaji}** __{english}__ {native}""" if english==None: name = f"""[{c_flag}]**{romaji}** {native}""" finals_ = f"{name}\n\n" finals_ += f"➤ **ID:** `{idm}`\n" finals_ += f"➤ **STATUS:** `{status}`\n" finals_ += f"➤ **VOLUMES:** `{volumes}`\n" finals_ += f"➤ **CHAPTERS:** `{chapters}`\n" finals_ += f"➤ **SCORE:** `{score}`\n" finals_ += f"➤ **FORMAT:** `{format_}`\n" finals_ += f"➤ **SOURCE:** `{source}`\n\n" finals_ += f"Description: `{description}`\n\n" finals_ += f"For more info <a href='{url}'>click here</a>" pic = f"https://img.anili.st/media/{idm}" await message.reply_photo(pic, caption=finals_) await message.delete()
async def airing_anim(message: Message): """ Get Airing Detail of Anime """ query = message.input_str if not query: await message.err("NameError: 'query' not defined") return vars_ = {'search': query, 'asHtml': True, 'type': "ANIME"} if query.isdigit(): vars_ = {'id': int(query), 'asHtml': True, 'type': "ANIME"} result = await return_json_senpai(ANIME_QUERY, vars_) error = result.get('errors') if error: await CLOG.log(f"**ANILIST RETURNED FOLLOWING ERROR:**\n\n`{error}`") error_sts = error[0].get('message') await message.err(f"[{error_sts}]") return data = result['data']['Media'] # Airing Details mid = data.get('id') romaji = data['title']['romaji'] english = data['title']['english'] native = data['title']['native'] status = data.get('status') episodes = data.get('episodes') country = data.get('countryOfOrigin') c_flag = cflag.flag(country) source = data.get('source') coverImg = data.get('coverImage')['extraLarge'] genres = data.get('genres') genre = genres[0] if len(genres) != 1: genre = ", ".join(genres) score = data.get('averageScore') air_on = None if data['nextAiringEpisode']: nextAir = data['nextAiringEpisode']['airingAt'] episode = data['nextAiringEpisode']['episode'] air_on = make_it_rw(nextAir, True) title_ = english or romaji out = f"[{c_flag}] **{native}** \n (`{title_}`)" out += f"\n\n**ID:** `{mid}`" out += f"\n**Status:** `{status}`\n" out += f"**Source:** `{source}`\n" out += f"**Score:** `{score}`\n" out += f"**Genres:** `{genre}`\n" if air_on: out += f"**Airing Episode:** `[{episode}/{episodes}]`\n" out += f"\n`{air_on}`" if len(out) > 1024: await message.edit(out) return await message.reply_photo(coverImg, caption=out) await message.delete()
def get_day(country): iso = "" date = get_key(country) data = {"message": "Country not found"} if date is not None: for i in countries: if country.title() == i.name: iso += i.alpha_2 data = {"Day": date, "Unicode flag": flag.flag(iso)} return jsonify(data), 200 else: return jsonify(data), 404
def __init__(self, engine, parent, name, color, is_gm): PlayerCache.instance_count += 1 self.engine = engine self.parent = parent # parent cache object self.name = name self.color = color self.uuid = uuid.uuid4().hex # used for HTML DOM id self.selected = list() self.index = parent.getNextId() # used for ordering players in the UI self.is_gm = is_gm # whether this player is the GM or not self.timeid = time.time( ) # NOTE: currently not used but could be useful later self.greenlet = None # fetch country flag from ip self.ip = self.engine.getClientIp(request) self.country = self.engine.getCountryFromIp(self.ip) # ? = localhost, 'unknown' = unittest self.flag = flag.flag( self.country) if self.country not in ['?', 'unknown'] else '' # add login to stats login_data = [ self.is_gm, time.time(), self.country, self.ip, PlayerCache.instance_count ] self.engine.logging.stats(json.dumps(login_data)) self.lock = lock.RLock() self.socket = None self.dispatch_map = { 'PING': self.parent.onPing, 'ROLL': self.parent.onRoll, 'SELECT': self.parent.onSelect, 'RANGE': self.parent.onRange, 'ORDER': self.parent.onOrder, 'UPDATE': self.parent.onUpdateToken, 'CREATE': self.parent.onCreateToken, 'CLONE': self.parent.onCloneToken, 'DELETE': self.parent.onDeleteToken, 'BEACON': self.parent.onBeacon, 'MUSIC': self.parent.onMusic, 'GM-CREATE': self.parent.onCreateScene, 'GM-MOVE': self.parent.onMoveScene, 'GM-ACTIVATE': self.parent.onActivateScene, 'GM-CLONE': self.parent.onCloneScene, 'GM-DELETE': self.parent.onDeleteScene }
async def setlanguage(self, ctx): """Set what language you want to use for your packs. """ languages = { "gb": "English", "es": "Español", "fr": "Français", "de": "Deutsch", "ru": "русский", "ua": "Українська", "nl": "Nederlands", "pt": "Português" } supported = "**Already supported:**" for language in self.bot.cah_packs: supported += f"\n:flag_{language}: {languages.get(language, 'Unknown')}" soon = "||**Coming Soon:**" for language, name in languages.items(): if language not in self.bot.cah_packs: soon += f"\n:flag_{language}: {name}" language = self.languages.read_key(ctx.guild.id) if ctx.guild else None title = f"{self.bot.emotes['choice']} All available languages:" if language is not None: title += f" (You currently have your language set to :flag_{language}:)" if ctx.channel.permissions_for(ctx.author).manage_guild: menu = input.Menu(self.bot, callbacks=False) # Create our reaction menu for language in self.bot.cah_packs: menu.add(flag.flag(language)) msg = await ctx.send( supported + "\n\n" + soon + "||\n\n*Select a flag below (or say it in chat) to set it as the default " "language for this server*", title=title) try: emote = flag.dflagize(await menu(msg, ctx.author))[1:-1].lower() self.languages.save_key(ctx.guild.id, emote) await ctx.send("We've successfully changed your language", title=f":flag_{emote}: Language changed") except asyncio.TimeoutError: pass finally: with contextlib.suppress(discord.NotFound): await msg.delete() else: await ctx.send(supported + "\n\n" + soon + "||", title=title)
async def _guess_flag(self, ctx): rand_country = random.choice(list(self.flags.keys())) await ctx.channel.send(f'Devine le drapeau de {rand_country.title()}') msg = None try: msg = await self._wait_response(ctx.author, ctx.channel, timeout=15) except asyncio.TimeoutError: await ctx.channel.send(f'Tu n\'as que 15 secondes pour répondre! Dommage') return flag_emoji = flag.flag(self.flags[rand_country][0]) if flag_emoji in msg.content: self.scores.add_score(ctx.author.id, 10) await ctx.channel.send(f'Bien joué le drapeau de {rand_country.title()} est bien {flag_emoji}!') else: await ctx.channel.send(f'Et nan! Le drapeau de {rand_country.title()} est {flag_emoji}!')
def pre_proc_df(df): df['Start'] = pd.to_datetime(df['Start date'], format='%Y-%m-%d', errors='coerce') df['Finish'] = pd.to_datetime(df['End date'], format='%Y-%m-%d', errors='coerce') df = df.dropna(subset=['Start', 'Finish']) df_china_us = df[df['Country'].isin(['United States', 'China'])] df_other = df[~df['Country'].isin(['United States', 'China'])].sort_values( ['Finish'], ascending=False) df_other = df_other.groupby('Country').agg({ 'Start': 'min', 'Finish': 'max', 'Place': lambda x: (str(len(x)) + ' places' if len(x) > 1 else x), 'Level': 'first', 'Confirmed': 'first', 'update': 'first', 'url': 'first' }).reset_index() # print(df_other) df = pd.concat((df_china_us, df_other), sort=False) df.loc[df['Finish'] > (pd.datetime.now() + pd.offsets.Day(60)), 'Finish'] = np.nan df['Duration'] = df['Finish'] - df['Start'] df['Name'] = np.where(df['Level'] == 'National', df['Country'], df['Country'] + ' (' + df['Place'] + ')') df['CC'] = df['Country'].apply( lambda x: pycountry.countries.search_fuzzy(x)[0].alpha_2) df['CCE'] = df['CC'].apply(lambda x: flag.flag(x)) df['Complete'] = df['Finish'] <= pd.datetime.now() df['update_status'] = '' # df = df.sort_values(['Start', 'Country', 'Duration'], ascending=[False, False, True]).reset_index() # df = df.sort_values(['Finish', 'Country', 'Duration'], ascending=[True, True, True]).reset_index() df = df.sort_values(['Country', 'Place', 'Duration'], ascending=[True, True, True]).reset_index() return df
def formatTranslation(self, translation, target): """ Common decoration of translated messages transation = the result of translate() target = reminder of which target language was asked (does not appear in the response of translate()) """ text = translation['translations'][0]['translation'].strip() try: # Note : translation['detected_language'] is the detected source language, if guessed country = self.languageToCountry(target) lang_emoji = flag.flag(country) except ValueError: log.debug("Error looking for flag %s", target, exc_info=True) lang_emoji = "🏳️🌈" answer = "%s %s" % (text, lang_emoji) return i18n.t('all_messages', message=answer)
def country_api_links_as_md(country_info_path, api_url): # Load tracking csv df = pd.read_csv(country_info_path) df = df.sort_values("country") # Prettify country + flag flags = df["country_iso"].apply(lambda x: flag.flag(x)) df.loc[:, "Country"] = flags + " " + df.loc[:, "country"] # Build df url_base = f"{api_url}/{{mode}}/country_by_iso/{{iso}}.json" df["All data"] = df.country_iso.apply(lambda x: "[link]({url})".format( url=url_base.format(mode="all", iso=x))) df["Latest data"] = df.country_iso.apply(lambda x: "[link]({url})".format( url=url_base.format(mode="latest", iso=x))) df = df[["Country", "All data", "Latest data"]] # Get markdown return df.to_markdown(index=False)
def warning(measurement, min, max): """ Generate warning if measurement outside min and max range is detected. """ setflag = flag() if (measurement < min): setflag.giveWarning = True setflag.abortFlight = False setflag.actuatePressureRelease = False return setflag if (measurement > max): setflag.giveWarning = True setflag.abortFlight = False setflag.actuatePressureRelease = True return setflag else: setflag.giveWarning = False setflag.abortFlight = False setflag.actuatePressureRelease = False return setflag
def send_statistics(message): if message.text.upper() == 'ALL': response = requests.get('https://corona.lmao.ninja/v2/all') else: response = requests.get('https://corona.lmao.ninja/v2/countries/' + message.text) if response.status_code == 200: content = json.loads(response.text) country_info = '🌎 *Worldwide*' if message.text.upper() == 'ALL' else flag.flag(content["countryInfo"]["iso2"]) + ' *' + content["country"] + '* ' bot.send_message( message.chat.id, country_info + '\n' + '_Total cases:_ *' + str(content["cases"]) + '* 😷\n' + '_Cases today:_ *' + str(content["todayCases"]) + '* 🚑\n' + '_Active:_ *' + str(content["active"]) + ' 🤒*\n' + '_Critical:_ *' + str(content["critical"]) + ' 🤢*\n' + '_Total deaths:_ *' + str(content["deaths"]) + ' ⚰*\n' + '_Deaths today:_ *' + str(content["todayDeaths"]) + ' ⚰*\n' + '_Total recovered:_ *' + str(content["recovered"]) + '* 💊\n', parse_mode= 'Markdown' ) else: bot.send_message(message.chat.id, 'Country not found')
def add_more_info(self): for country in self.countries: name = country['country'] iso_code = country['countryInfo']['iso2'] # make names better if name in name_map: country['country'] = name_map[name] # in the json from corona-stats.online sometimes there is null # where should just be 0 for x in ('cases', 'deaths', 'todayCases', 'todayDeaths'): if country[x] == None: # give a warning just in case print(country, '\nchanging None to 0') country[x] = 0 # replace links to pics by emoji flags country['countryInfo']['flag'] = flag(iso_code) self.add_ratios(country) self.add_ratios(self.world)
def main(screen): flag1=flag.flag() flag1.draw(screen)
async def get_ani(vars_): result = await return_json_senpai(ANIME_QUERY, vars_) error = result.get("errors") if error: await CLOG.log(f"**ANILIST RETURNED FOLLOWING ERROR:**\n\n`{error}`") error_sts = error[0].get("message") return [f"[{error_sts}]"] data = result["data"]["Media"] # Data of all fields in returned json # pylint: disable=possibly-unused-variable idm = data.get("id") idmal = data.get("idMal") romaji = data["title"]["romaji"] english = data["title"]["english"] native = data["title"]["native"] formats = data.get("format") status = data.get("status") episodes = data.get("episodes") synopsis = data.get("description") duration = data.get("duration") country = data.get("countryOfOrigin") c_flag = cflag.flag(country) source = data.get("source") prqlsql = data.get("relations").get('edges') bannerImg = data.get("bannerImage") s_date = data.get("startDate") adult = data.get("isAdult") trailer_link = "N/A" if data["title"]["english"] is not None: name = f'''[{c_flag}]**{romaji}** __{english}__ {native}''' else: name = f'''[{c_flag}]**{romaji}** {native}''' prql, prql_id, sql, sql_id = "", "None", "", "None" for i in prqlsql: if i['relationType']=="PREQUEL": pname = i["node"]["title"]["english"] if i["node"]["title"]["english"] is not None else i["node"]["title"]["romaji"] prql += f"**PREQUEL:** `{pname}`\n" prql_id = f"{i['node']['id']}" break for i in prqlsql: if i['relationType']=="SEQUEL": sname = i["node"]["title"]["english"] if i["node"]["title"]["english"] is not None else i["node"]["title"]["romaji"] sql += f"**SEQUEL:** `{sname}`\n" sql_id = f"{i['node']['id']}" break additional = f"{prql}{sql}" dura = f"\n➤ **DURATION:** `{duration} min/ep`" if duration!=None else "" charlist = [] for char in data["characters"]["nodes"]: charlist.append(f" •{char['name']['full']}") chrctrs = "\n" chrctrs += ("\n").join(charlist[:10]) chrctrsls = f"\n➤ **CHARACTERS:** `{chrctrs}`" if len(charlist)!=0 else "" air_on = None if data["nextAiringEpisode"]: nextAir = data["nextAiringEpisode"]["airingAt"] air_on = make_it_rw(nextAir) eps = data['nextAiringEpisode']['episode'] ep_ = list(str(eps)) x = ep_.pop() th = "th" if len(ep_)>=1: if ep_.pop()!="1": th = pos_no(x) else: th = pos_no(x) air_on += f" | {eps}{th} eps" if air_on==None: eps_ = f" | {episodes} eps" if episodes!=None else "" status_air = f"➤ <b>STATUS:</b> `{status}{eps_}`" else: status_air = f"➤ <b>STATUS:</b> `{status}`\n➤ <b>NEXT AIRING:</b> `{air_on}`" if data["trailer"] and data["trailer"]["site"] == "youtube": trailer_link = f"[Trailer](https://youtu.be/{data['trailer']['id']})" html_char = "" for character in data["characters"]["nodes"]: html_ = "" html_ += "<br>" html_ += f"""<a href="{character['siteUrl']}">""" html_ += f"""<img src="{character['image']['large']}"/></a>""" html_ += "<br>" html_ += f"<h3>{character['name']['full']}</h3>" html_ += f"<em>{c_flag} {character['name']['native']}</em><br>" html_ += f"<b>Character ID</b>: {character['id']}<br>" html_ += ( f"<h4>About Character and Role:</h4>{character.get('description', 'N/A')}" ) html_char += f"{html_}<br><br>" studios = "".join("<a href='{}'>• {}</a> ".format(studio["siteUrl"], studio["name"]) for studio in data["studios"]["nodes"]) url = data.get("siteUrl") title_img = f"https://img.anili.st/media/{idm}" # Telegraph Post mejik html_pc = "" html_pc += f"<img src='{title_img}' title={romaji}/>" html_pc += f"<h1>[{c_flag}] {native}</h1>" html_pc += "<h3>Synopsis:</h3>" html_pc += synopsis html_pc += "<br>" if html_char: html_pc += "<h2>Main Characters:</h2>" html_pc += html_char html_pc += "<br><br>" html_pc += "<h3>More Info:</h3>" html_pc += f"<b>Started On:</b> {s_date['day']}/{s_date['month']}/{s_date['year']}" html_pc += f"<br><b>Studios:</b> {studios}<br>" html_pc += f"<a href='https://myanimelist.net/anime/{idmal}'>View on MAL</a>" html_pc += f"<a href='{url}'> View on anilist.co</a>" html_pc += f"<img src='{bannerImg}'/>" title_h = english or romaji synopsis_link = post_to_tp(title_h, html_pc) try: finals_ = ANIME_TEMPLATE.format(**locals()) except KeyError as kys: return [f"{kys}"] return title_img, finals_, prql_id, sql_id, adult, romaji, idm
async def msg(event): if event.fwd_from: return input_str = event.pattern_match.group(1) lol = input_str country = CountryInfo(lol) try: a = country.info() except: await event.reply("Country Not Avaiable Currently") name = a.get("name") bb = a.get("altSpellings") hu = "".join(f"{p}, " for p in bb) area = a.get("area") hell = a.get("borders") borders = "".join(f"{fk}, " for fk in hell) WhAt = a.get("callingCodes") call = "".join(f"{what} " for what in WhAt) capital = a.get("capital") fker = a.get("currencies") currencies = "".join(f"{FKer}, " for FKer in fker) HmM = a.get("demonym") geo = a.get("geoJSON") pablo = geo.get("features") Pablo = pablo[0] PAblo = Pablo.get("geometry") EsCoBaR = PAblo.get("type") iso = "" iSo = a.get("ISO") for hitler in iSo: po = iSo.get(hitler) iso += f"{po}, " fla = iSo.get("alpha2") nox = fla.upper() okie = flag.flag(nox) languages = a.get("languages") lMAO = "".join(f"{lmao}, " for lmao in languages) nonive = a.get("nativeName") waste = a.get("population") reg = a.get("region") sub = a.get("subregion") tik = a.get("timezones") tom = "".join(f"{jerry}, " for jerry in tik) GOT = a.get("tld") lanester = "".join(f"{targaryen}, " for targaryen in GOT) wiki = a.get("wiki") caption = f"""<b><u>Information Gathered Successfully</b></u> <b> Country Name:- {name} Alternative Spellings:- {hu} Country Area:- {area} square kilometers Borders:- {borders} Calling Codes:- {call} Country's Capital:- {capital} Country's currency:- {currencies} Country's Flag:- {okie} Demonym:- {HmM} Country Type:- {EsCoBaR} ISO Names:- {iso} Languages:- {lMAO} Native Name:- {nonive} population:- {waste} Region:- {reg} Sub Region:- {sub} Time Zones:- {tom} Top Level Domain:- {lanester} wikipedia:- {wiki}</b> Gathered By Shasa.</b> """ await borg.send_message( event.chat_id, caption, parse_mode="HTML", ) await event.delete()
f = open(filep, 'a') f.write(MASSAGE) f.close() break time.sleep(10) except: pass user = et.use('ht') user.prepare('/data/pyquant/ht.json') user.keepalive() account_flag = flag.flag() limit = zxb_limit.zxb_limit(-2.31) #添加trade if ed.is_tradetime_now(): file_name = '/home/way/signal/chicang' file_name1 = '/home/way/signal/zhenfu' # with open(file_name) as f: # yiyue = str(f.readlines()[0]) m = multiprocessing.Process(target=account_info,args=(account_flag,)) m.start() if account_flag.read_flag() == 2: chiyou_feed = feed.feed('chicang') chicang_trade = trade.trade(chiyou_feed.load(), user) print('chiyou') p=multiprocessing.Process(target=chiyou, args=(chicang_trade, limit))
import config import auth import song import songsloader import threading import flag cfg = config.config() with open('problems.info', 'r') as f: info = f.read() print(info) auth.try_auth(cfg) songlist = list() flg = flag.flag() songsupd = threading.Thread(group=None, target=songsloader.loadsongs, name='Songsloader', args=[cfg, songlist, flg], daemon=False) songsupd.start()