def add_district(l: list, area_id: int): try: for i in l: dist = District.create(district_name=i, area_id=area_id) dist.save() except Exception as e: logger.error(e)
async def _get_live_data(self, channel, channel_settings, minute): """ Obtains and returns the data of currencies requested """ try: valid_time = True if int(minute) != int(channel_settings["interval"]): if int(minute) % int(channel_settings["interval"]) != 0: valid_time = False except KeyError: pass except Exception as e: logger.error("Something went wrong with retrieving live data: {}" "".format(str(e))) valid_time = False finally: if not valid_time: return None if channel_settings["currencies"]: if channel_settings["purge"]: try: await self.bot.purge_from(channel, limit=100) except: pass return self.coin_market.get_current_multiple_currency( self.market_list, self.acronym_list, channel_settings["currencies"], channel_settings["fiat"])
async def display_server_settings(self, ctx): """ Displays server settings of cmds the admins have enabled """ try: try: ctx.message.channel.server except: await self._say_msg("Not a valid server to retrieve settings.") return msg = '' server_id = ctx.message.server.id if server_id not in self.server_data: await self._say_msg("No settings to display.") return elif len(self.server_data[server_id]) == 0: await self._say_msg("No settings to display.") return for setting in self.server_data[server_id]: setting_line = "{}\n".format(setting) msg += setting_line em = discord.Embed(title="Server Settings", description=msg, colour=0xFFFFFF) await self._say_msg(emb=em) except Exception as e: print("Failed to display server settings. See error.log.") logger.error("Exception: {}".format(str(e)))
async def _update_market(self): """ Loads all the cryptocurrencies that exist in the market @return - list of crypto-currencies """ try: retry_count = 0 market_stats = self.coin_market.fetch_coinmarket_stats() currency_data = self.coin_market.fetch_currency_data() while market_stats is None or currency_data is None: if retry_count >= 10: msg = ("Max retry attempts reached. Please make " "sure you're able to access coinmarketcap " "through their website, check if the coinmarketapi " "is down, and check if " "anything is blocking you from requesting " "data.") raise CoreFunctionalityException(msg) logger.warning("Retrying to get data..") if market_stats is None: market_stats = self.coin_market.fetch_coinmarket_stats() if currency_data is None: currency_data = self.coin_market.fetch_currency_data() retry_count += 1 await asyncio.sleep(5) market_dict = {} for currency in currency_data['data']: market_dict[currency['slug']] = currency await self._get_top_five(currency_data['data']) self.market_stats = market_stats self.market_list = market_dict except Exception as e: print("Failed to update market. See error.log.") logger.error("Exception: {}".format(str(e)))
async def _alert_user_(self): """ Checks and displays alerts that have met the condition of the cryptocurrency price """ try: raised_alerts = defaultdict(list) for user in self.alert_data: alert_list = self.alert_data[str(user)] for alert in alert_list: alert_currency = alert_list[alert]["currency"] operator_symbol = alert_list[alert]["operation"] alert_operator = self._translate_operation_( operator_symbol) alert_price = alert_list[alert]["price"] alert_fiat = alert_list[alert]["fiat"] if not self._check_alert_(alert_currency, operator_symbol, alert_price, alert_fiat): raised_alerts[user].append(alert) user_obj = await self.bot.get_user_info(user) await self.bot.send_message( user_obj, "Alert **{}**! " "**{}** is **{}** **{}** " "in **{}**" "".format(alert, alert_currency.title(), alert_operator, alert_price, alert_fiat)) if raised_alerts: for user in raised_alerts: for alert_num in raised_alerts[user]: self.alert_data[user].pop(str(alert_num)) self._save_alert_file_() except Exception as e: print("An error has occured. See error.log.") logger.error("Exception: {}".format(str(e)))
async def get_sub_currencies(self, ctx): """ Displays the currencies the channel in context is subbed too @param ctx - context of the command sent """ try: channel = str(ctx.message.channel.id) subscriber_list = self.subscriber_data if channel in subscriber_list: channel_settings = subscriber_list[channel] currency_list = channel_settings["currencies"] if len(currency_list) != 0: msg = "Currently this channel displays the following:\n" for currency in currency_list: msg += "__**{}**__\n".format(currency.title()) else: msg = "Channel does not have any currencies to display." await self.bot.say(msg) else: msg = "Channel was never subscribed." await self.bot.say(msg) except Forbidden: pass except Exception as e: print("An error has occured. See error.log.") logger.error("Exception: {}".format(str(e)))
async def toggle_commands(self, ctx, mode): """ Toggles the command mode on/off """ try: try: user_roles = ctx.message.author.roles except: await self._say_msg("Command must be used in a server.") return if CMB_ADMIN not in [role.name for role in user_roles]: await self._say_msg("Admin role '{}' is required for " "this command.".format(CMB_ADMIN)) return channel = ctx.message.channel.id try: server = self.bot.get_channel( channel).server # validate channel except: await self._say_msg("Not a valid server to toggle mode.") return if server.id not in self.server_data: self.server_data[server.id] = [mode] await self._say_msg("Server set '{}'.".format(mode)) elif mode in self.server_data[server.id]: self.server_data[server.id].remove(mode) await self._say_msg("'{}' has been taken off.".format(mode)) elif mode not in self.server_data[server.id]: self.server_data[server.id].append(mode) await self._say_msg("Server set '{}'.".format(mode)) self._save_server_file(self.server_data) self._update_server_data() except Exception as e: print("Failed to toggle {}. See error.log.".format(mode)) logger.error("Exception: {}".format(str(e)))
async def get_district_id(district_name): try: area = District.select().where( District.district_name.contains(district_name)).get() return area.id except Exception as e: logger.error(e)
async def violation_photo(message: Message, state=FSMContext): try: data = await state.get_data() lang = data.get('lang') photo = None if message.text == lang_list(lang, 'back_btn'): await state.finish() await main_menu(message, lang) elif message.text == lang_list(lang, 'skip') or not message.text: if message.photo: photo = message.photo[1].file_id if message.video: photo = message.video.file_id await add_viol(data.get('date'), data.get('city'), data.get('name'), data.get('info'), data.get('offender'), data.get('position'), photo, message.chat.id) await send_message(message.chat.id, lang_list(lang, 'violation_completed')) await main_menu(message, lang) await state.finish() else: await send_message(message.chat.id, lang_list(lang, 'violation_photo')) await States.photo.set() except Exception as e: print(e) logger.error(e)
async def remove_currency(self, ctx, currency): """ Removes a cryptocurrency from the subscriber settings @param ctx - context of the command sent @param currency - the cryptocurrency to remove """ try: if currency.upper() in self.acronym_list: currency = self.acronym_list[currency.upper()] if "Duplicate" in currency: await self.bot.say(currency) return channel = ctx.message.channel.id subscriber_list = self.subscriber_data if channel in subscriber_list: channel_settings = subscriber_list[channel] if currency in channel_settings["currencies"]: channel_settings["currencies"].remove(currency) self._save_subscriber_file(self.subscriber_data) await self.bot.say("``{}`` was successfully removed." "".format(currency.title())) else: await self.bot.say("``{}`` was never added or is invalid." "".format(currency.title())) else: await self.bot.say("The channel needs to be subscribed first.") except Forbidden: pass except CurrencyException as e: logger.error("CurrencyException: {}".format(str(e))) await self._say_error(e) except Exception as e: print("An error has occured. See error.log.") logger.error("Exception: {}".format(str(e)))
async def set_live_update_interval(self, ctx, rate): """ Sets the interval at which the bot should post updates to the channel. By default, it will be every 5 minutes. @param ctx - context of the command sent @param minutes - interval in minutes to send an update (only accepts multiples of 5) """ try: if rate not in self.supported_rates: await self.bot.say("The rate entered is not supported. " "Current intervals you can choose are:\n" "**default** - every 5 minutes\n" "**half** - every 30 minute mark\n" "**hourly** - every hour mark\n") return channel = ctx.message.channel.id if channel in self.subscriber_data: if rate == "hourly": self.subscriber_data[channel]["interval"] = "60" elif rate == "half": self.subscriber_data[channel]["interval"] = "30" else: self.subscriber_data[channel]["interval"] = "5" self._save_subscriber_file(self.subscriber_data) await self.bot.say("Interval is set to **{}**".format(rate)) else: await self.bot.say("Channel must be subscribed first.") except Exception as e: print("Unable to set live update interval. See error.log.") logger.error("Exception: {}".format(str(e)))
async def update_lang(chat_id, lang): try: user = Users.select().where(Users.id == int(chat_id)).get() user.lang = lang user.save() except Exception as e: logger.error(e)
def _load_acronyms(self): """ Loads all acronyms of existing crypto-coins out there @return - list of crypto-acronyms """ try: if self.market_list is None: raise Exception("Market list was not loaded.") acronym_list = {} duplicate_count = 0 for currency, data in self.market_list.items(): if data['symbol'] in acronym_list: duplicate_count += 1 if data['symbol'] not in acronym_list[data['symbol']]: acronym_list[data['symbol'] + str(1)] = acronym_list[data['symbol']] acronym_list[data['symbol']] = ("Duplicate acronyms " "found. Possible " "searches are:\n" "{}1 ({})\n".format(data['symbol'], acronym_list[data['symbol']])) dupe_acronym = re.search('\\d+', acronym_list[data['symbol']]) dupe_num = str(int(dupe_acronym.group(len(dupe_acronym.group()) - 1)) + 1) dupe_key = data['symbol'] + dupe_num acronym_list[dupe_key] = currency acronym_list[data['symbol']] = (acronym_list[data['symbol']] + "{} ({})".format(dupe_key, currency)) else: acronym_list[data['symbol']] = currency self.acronym_list = acronym_list except Exception as e: print("Failed to load cryptocurrency acronyms. See error.log.") logger.error("Exception: {}".format(str(e)))
def _check_invalid_sub_currencies(self): """ Check if currencies have become invalid If invalid, the currencies will be removed from the subscriber currency list """ try: remove_currencies = defaultdict(list) subscriber_list = self.subscriber_data for channel in subscriber_list: channel_settings = subscriber_list[channel] for currency in channel_settings["currencies"]: if self.market_list is not None: if currency not in self.market_list: remove_currencies[channel].append(currency) for channel in remove_currencies: for currency in remove_currencies[channel]: subscriber_list[channel]["currencies"].remove(currency) logger.error("Removed '{}' from channel {}".format( currency, channel)) if remove_currencies: self._save_subscriber_file(self.subscriber_data) except Exception as e: raise CurrencyException("Failed to validate sub " "currencies: {}".format(str(e)))
async def vote(message: Message, state=FSMContext): try: data = await state.get_data() lang = data.get('lang') number = data.get('number') if message.text == lang_list(lang, 'back_btn'): await state.finish() await main_menu(message, lang) elif message.photo: if number is None: await add_photo(message.chat.id, message.photo[1].file_id, 1) await state.update_data(number=2) await States.vote.set() elif number == 2: await add_photo(message.chat.id, message.photo[1].file_id, 2) await state.finish() await send_message(message.chat.id, lang_list(lang, 'ty_for_vote')) await main_menu(message, lang) else: markup = types.ReplyKeyboardMarkup(resize_keyboard=True) markup.add(lang_list(lang, 'back_btn')) await send_message(message.chat.id, lang_list(lang, 'voted_photo'), reply_markup=markup) await States.vote.set() except Exception as e: logger.error(e)
async def prefix(ctx, prefix: str): """ Customizes the prefix for the server An example for this command would be: "$prefix !" @param ctx - context of the command @param prefix - new prefix for the channel """ try: if not _check_permission(ctx): return try: server = str(ctx.message.server.id) except: await bot.say("Failed to create a prefix for the server. " "Please make sure this channel is within a " "valid server.") return prefix_list[server] = prefix save_prefix_file(prefix_list) msg = "`{}` prefix has been set for bot commands.".format(prefix) await bot.say(msg) except Exception as e: print("An error has occured. See error.log.") logger.error("Exception: {}".format(str(e)))
async def on_ready(): try: bot.load_extension(COG_MANAGER) except Exception as e: error_msg = 'Failed to load cog manager\n{}: {}'.format(type(e).__name__, e) print(error_msg) logger.error(error_msg)
async def add_subscriber(self, ctx, fiat): """ Adds channel to the live update subscriber list in subscribers.json @param ctx - context of the command sent @param fiat - desired fiat currency (i.e. 'EUR', 'USD') """ try: ucase_fiat = self.coin_market.fiat_check(fiat) channel = str(ctx.message.channel.id) subscriber_list = self.subscriber_data try: self.bot.get_channel(channel).server # validate channel except: await self.bot.say( "Failed to add channel as a subscriber. " " Please make sure this channel is within a " "valid server.") return if channel not in subscriber_list: subscriber_list[channel] = {} channel_settings = subscriber_list[channel] channel_settings["purge"] = False channel_settings["fiat"] = ucase_fiat channel_settings["currencies"] = [] self._save_subscriber_file() await self._update_game_status_() await self.bot.say("Channel has succcesfully subscribed. Now " "add some currencies with `$addc` to begin " "receiving updates.") else: await self.bot.say("Channel is already subscribed.") except Exception as e: print("An error has occured. See error.log.") logger.error("Exception: {}".format(str(e)))
async def get_sub_currencies(self, ctx): """ Displays the currencies the channel in context is subbed too @param ctx - context of the command sent """ try: channel = ctx.message.channel.id subscriber_list = self.subscriber_data if channel in subscriber_list: channel_settings = subscriber_list[channel] currency_list = channel_settings["currencies"] if len(currency_list) != 0: msg = "" for currency in currency_list: msg += "__**{}**__\n".format(currency.title()) color = 0x00FF00 else: msg = "Channel does not have any currencies to display." color = 0xD14836 else: msg = "Channel was never subscribed." color = 0xD14836 try: em = discord.Embed(title="Subscriber Currencies", description=msg, colour=color) await self.bot.say(embed=em) except: pass except Forbidden: pass except Exception as e: print("An error has occured. See error.log.") logger.error("Exception: {}".format(str(e)))
def list_of_poll_by_status(): try: poll = Poll.select().where(Poll.status == 0) return poll except Exception as e: print(e) logger.error(e)
async def remove_alert(self, ctx, alert_num): """ Removes an alert from the user's list of alerts @param ctx - context of the command sent @param alert_num - number of the specific alert to remove """ try: user_id = ctx.message.author.id user_list = self.alert_data alert_list = user_list[user_id] if alert_num in alert_list: removed_alert = alert_num alert_setting = alert_list[alert_num] alert_currency = alert_setting["currency"] alert_operation = self._translate_operation( alert_setting["operation"]) if "unit" in alert_setting: if "btc" in alert_setting["unit"]: alert_btc = alert_setting["unit"]["btc"] if alert_btc.endswith('.'): alert_btc = alert_btc.replace('.', '') alert_value = "{} BTC".format(alert_btc) elif "percent" in alert_setting: alert_percent = alert_setting["percent"] if alert_percent.endswith('.'): alert_percent = alert_percent.replace('.', '') alert_value = "{}%".format(alert_percent) if "hour" == alert_setting["percent_change"]: alert_value += " (1H)" elif "day" == alert_setting["percent_change"]: alert_value += " (24H)" elif "week" == alert_setting["percent_change"]: alert_value += " (7D)" else: alert_value = alert_setting["price"] alert_fiat = alert_setting["fiat"] alert_list.pop(str(alert_num)) self._save_alert_file(self.alert_data) msg = ("Alert **{}** where **{}** is **{}** **{}** " "".format(removed_alert, alert_currency.title(), alert_operation, alert_value)) if "price" in alert_setting: msg += "**{}** ".format(alert_fiat) msg += "was successfully removed." await self._say_msg(msg) else: await self._say_msg( "The number you've entered does not exist " "in the alert list. Use `$geta` to receive " "a list of ongoing alerts.") except Forbidden: pass except CurrencyException as e: logger.error("CurrencyException: {}".format(str(e))) await self._say_msg(str(e)) except Exception as e: print("Failed to remove alert. See error.log.") logger.error("Exception: {}".format(str(e)))
async def add_viol(date, city, name_victim, info, offender, position, photo, chat_id): try: vio = Violation.create(date=date, city=city, name_victim=name_victim, info=info, offender=offender, position=position, photo=photo, chat_id=chat_id) vio.save() except Exception as e: logger.error(e) print(e)
async def on_ready(): try: await bot.change_presence(game=discord.Game(name="Use pc!help.")) bot.load_extension(COG_MANAGER) except Exception as e: error_msg = 'Failed to load cog manager\n{}: {}'.format(type(e).__name__, e) print(error_msg) logger.error(error_msg)
async def calculate_prepump(self): """ Calculates cryptocoin to another cryptocoin and displays it @param currency1 - currency to convert from @param currency2 - currency to convert to @param currency_amt - amount of currency coins """ try: acronym1 = '' acronym2 = '' currency1 = 'oax' currency2 = 'eth' currency_amt = 1 target_amt = 1 await self.bot.say("Pump will begin in 5 minutes") await asyncio.sleep(240) await self.bot.say("Pump will begin in 1 minute") await asyncio.sleep(60) if currency1.upper() in self.acronym_list: acronym1 = currency1.upper() currency1 = self.acronym_list[currency1.upper()] else: acronym1 = self.market_list[currency1]["symbol"] if currency2.upper() in self.acronym_list: acronym2 = currency2.upper() currency2 = self.acronym_list[currency2.upper()] else: acronym2 = self.market_list[currency2]["symbol"] price_btc1 = float(self.market_list[currency1]['price_btc']) price_btc2 = float(self.market_list[currency2]['price_btc']) btc_amt = float("{:.8f}".format(currency_amt * price_btc1)) converted_amt = "{:.8f}".format(btc_amt / price_btc2).rstrip('0') currency_amt = "{:.8f}".format(currency_amt).rstrip('0') targetprice = "{:.8f}".format( (1 + target_amt) * btc_amt / price_btc2).rstrip('0') if currency_amt.endswith('.'): currency_amt = currency_amt.replace('.', '') result = "Starting Price = **{} {}** || Target Price = **{} {}** (+**{}**%)".format( converted_amt, currency2.title(), targetprice, currency2.title(), target_amt * 100) em = discord.Embed(title="PUMP COIN = ({})".format(acronym1), description=result, colour=0xFF9900) await self.bot.say(embed=em) except Forbidden: pass except Exception as e: await self.bot.say( "Command failed. Make sure the arguments are valid.") print("An error has occured. See error.log.") logger.error("Exception: {}".format(str(e)))
def _update_server_data(self): try: self.cmc.update(server_data=self.server_data) self.alert.update(server_data=self.server_data) self.subscriber.update(server_data=self.server_data) self.misc.update(server_data=self.server_data) except Exception as e: print("Failed to update server data. See error.log.") logger.error("Exception: {}".format(str(e)))
async def update_phone(chat_id, phone_number, name): try: user = Users.select().where(Users.id == int(chat_id)).get() user.phone_number = phone_number user.name = name user.save() except Exception as e: print(e) logger.error(e)
async def display_update_page(self): """ Links the update page URL """ try: msg = "https://github.com/kodycode/CoinMarketDiscordBot/wiki/Updates" await self.bot.say(msg) except Exception as e: print("An error has occured. See error.log.") logger.error("Exception: {}".format(str(e)))
async def display_bot_profile(self): """ Displays the bot profile URL """ try: msg = "https://discordbots.org/bot/353373501274456065" await self.bot.say(msg) except Exception as e: print("An error has occured. See error.log.") logger.error("Exception: {}".format(str(e)))
async def update_game_status(self): """ Updates the game status of the bot """ try: game_status = discord.Game(name="$updates to see log") await self.bot.change_presence(game=game_status) except Exception as e: print("Failed to update game status. See error.log.") logger.error("Exception: {}".format(str(e)))
async def count_of_reg_users(): try: users = Users.select() l = [] for i in users: if i.phone_number is not None: l.append(l) return len(l) except Exception as e: logger.error(e)