async def profile(self, ctx, user: discord.Member = None): if user is None: user = ctx.message.author _user = User(user.id) else: _user = User(user.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return if len(user.avatar_url) == 0: avatar_url = user.default_avatar_url else: avatar_url = user.avatar_url if _user.equipped_background is None: bg = "default" else: bg = _user.equipped_background self.helpers.profile_generate(avatar_url, user.name, user.discriminator, _user.money, _user.reputation, _user.about, _user.level, bg, _user.equipped_badge) await self.bot.send_file(ctx.message.channel, 'externals/img/temp/outcome.png')
async def givecoins(self, ctx, user: discord.Member, value: int): _giver = User(ctx.message.author.id) _receiver = User(user.id) if _giver.is_Registered is False or _receiver.is_Registered is False: await self.bot.say(self.errors.SPEC_NOT_IN_DB) return if _giver.money < value: await self.bot.say(self.errors.INSUF_MONEY) return if value <= 0: await self.bot.say(self.errors.ZERO_GIVE) return if user == ctx.message.author: await self.bot.say(self.errors.COIN_GIVE_SELF) return rng = random.randint(1000, 9999) embed = discord.Embed( title="Please verify that this is right", description=f"Type **{rng}** to confirm. (Expires 20 seconds)", color=self.themes.MAIN_COL, timestamp=ctx.message.timestamp) embed.add_field(name="Giving Coins Too:", value=user.mention) embed.add_field(name="Amount to be Transfered:", value=str(value), inline=False) embed.add_field(name="Your Current Coins:", value=str(_giver.money), inline=False) embed.add_field(name="Your Coins After Transaction:", value=str(_giver.money - value), inline=False) await self.bot.say(embed=embed) msg = await self.bot.wait_for_message(author=ctx.message.author, content=str(rng), timeout=20.00) if msg is None: await self.bot.say("❌ | Confirmation timed out, please try again.") return _giver.add_money(-value) _receiver.add_money(value) await self.bot.say(self.msg.OPERATION_SUCCESSFUL)
async def myitems(self, ctx): _user = User(ctx.message.author.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return items = _user.user_items user_items = [] for item_id in items: _item = Item(item_id) conc = f"`{_item.name}` | ID: `{item_id}`" user_items.append(conc) msg = "" for i in user_items: msg += f"{i}\n" if len(msg) == 0: msg = f"No items in your inventory. Buy some items at `{self.configs.PREFIX}shop`!" embed = discord.Embed(description="This is your backpack! 🎒", color=self.themes.MAIN_COL) embed.set_author(name=f"{ctx.message.author.name}'s Inventory", icon_url=ctx.message.author.avatar_url) embed.add_field(name="Inventory", value=msg) embed.set_footer( text=f"Use {self.configs.PREFIX}equip <Item_ID> to equip an item.") await self.bot.say(embed=embed)
def test_posting_messages(self): # get location, username, msg, and expiration time from client location = {'latitude': 43.0100431, 'longitude': -78.8012356} username = "******" msg = "this is a neo4j test post" place_id = "ChIJwe_oGNJz04kRDxhd61f1WiQ" # get current time for time of post es = timezone("US/Eastern") exp_time = str((datetime.now().astimezone(es) + timedelta(days=7))) # add username and password to database to signup pwd = "admin" email = "*****@*****.**" fn = "Darren" ln = "Matthew" password_hash = authenticate.generate_hash(username, pwd) user = User(username, fn, ln, email, password_hash) # test adding user self.assertTrue(neo4j.add_user(user)) # post a message with the above information post_id = neo4j.post_message(username, location, msg, exp_time, place_id) print(post_id) self.assertNotEqual(post_id, None) #delete user self.assertTrue(neo4j.delete_user(username, password_hash))
async def gamble(self, ctx, bet: int = 50): author = ctx.message.author _user = User(author.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return if _user.money < bet: await self.bot.say(self.errors.INSUF_MONEY) return if bet < 50: await self.bot.say(self.errors.BET_INSUF.format("50")) return probabilities = [True, False] draw = random.choice(probabilities) ratio = [0.25, 0.5, 0.75] rate = random.choice(ratio) if draw: value = random.randint(1, int(bet * rate)) await self.bot.say(self.msg.GAMBLE_WON.format(bet, value)) else: value = -bet await self.bot.say(self.msg.GAMBLE_LOSE.format(bet)) _user.add_money(value)
async def fish(self, ctx): author = ctx.message.author _user = User(author.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return win = [True, False] if random.choice(win): pool = ['🦈', '🐡', '🐠', '🐟'] draw = random.choice(pool) if draw == pool[0]: prize = random.randint(50, 75) fish = pool[0] elif draw == pool[1]: prize = random.randint(10, 30) fish = pool[1] elif draw == pool[2]: prize = random.randint(50, 100) fish = pool[2] elif draw == pool[3]: prize = random.randint(1, 60) fish = pool[3] _user.add_money(prize) await self.bot.say(f"🎣 | You caught a fish `{fish}` and sold it for `{prize}` coins!") else: await self.bot.say("😢 | You only caught some piece of shi- junks in the ocean.")
def create_session(**kwargs): """ Authentication: is_allowed_by_all Authorization: None URL: None Body (Required): 'email' 'password' Body (Optional): None Body (Not Allowed): None Success (200): Returns created session Fail (40X): """ email = get_request_data('email') password = encrypt(get_request_data('password')) user = User() user.load_by_email(email) if user.id and password and user.password == password: session = Session({'user_id': user.id}) session.save() return Response(json.dumps(session.serialize()), status=200) else: return Response(json.dumps({'error': 'unable to authenticate'}), status=401)
def register_user(self, sid, name): """Initialize a new user""" user = User(sid, name) self.current_user.add(user) return user
async def purgebadge(self, ctx, user: discord.Member, badge): _user = User(user.id) _item = Item(badge) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return if _item.exists is False: await self.bot.say(self.errors.ITEM_NOT_EXIST) return if _item.kind != 3: await self.bot.say("❌ | Item is not a badge.") return try: if len(_user.get_user_badge(badge)) == 0: await self.bot.say(self.errors.ITEM_DONT_OWN) return except: pass _user.purge_user_badge(badge) await self.bot.say(f"You purged **{_item.name}** from {user.mention}.")
async def grantbadge(self, ctx, user: discord.Member, badge): _user = User(user.id) _item = Item(badge) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return if _item.exists is False: await self.bot.say(self.errors.ITEM_NOT_EXIST) return if _item.kind != 3: await self.bot.say("❌ | Item is not a badge.") return try: if badge == _user.get_user_badge(badge)[0][1]: await self.bot.say(self.errors.ALREADY_OWNED) return except: pass _user.store_badge(badge) await self.bot.say( f"You gave {user.mention} the badge **{_item.name}**.")
async def stats(self, ctx, user: discord.Member = None): if user is None: user = ctx.message.author _user = User(user.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return level = _user.level experience = _user.experience next_lvl_exp = 25 * level * level - 25 * level embed = discord.Embed(title="User Stats 👨💼", description=f"Statistics of **{user.name}**", color=self.themes.MAIN_COL) embed.add_field(name="Level", value=level, inline=False) embed.add_field(name="Experience", value=f"{experience} / {next_lvl_exp}", inline=False) embed.add_field(name="Exp To Next Level", value=next_lvl_exp - experience, inline=False) embed.add_field(name="Total Warnings", value=_user.warnings, inline=False) embed.set_author(name=user.name, icon_url=user.avatar_url) await self.bot.say(embed=embed)
def update_user(user_id, **kwargs): """ Authentication: is_valid_session Authorization: target_user_is_session_user URL: <user_id>: Target user id Body (Required): None Body (Optional): 'email' 'password' Body (Not Allowed): None Success (200): Returns updated user Fail (40X): """ try: user = User(get_request_data()) user.id = user_id if user.password: user.password = encrypt(user.password) user.save() except (AttributeError, RequiredAttributes, EmailExists) as e: return Response(json.dumps({'error': str(e)}), status=400) return Response(json.dumps(user.serialize()), status=200)
def create_user(**kwargs): """ Authentication: is_allowed_by_all Authorization: None URL: None Body (Required): 'email' 'password' Body (Optional): None Success (200): Returns created user Fail (40X): """ try: user = User(get_request_data()) if user.password: user.password = encrypt(user.password) user.save() except (AttributeError, RequiredAttributes, EmailExists) as e: return Response(json.dumps({'error': str(e)}), status=400) return Response(json.dumps(user.serialize()), status=200)
def auth(): # USED FOR SIGN IN if request.method == 'GET': username = request.args.get('username') password = request.args.get('password') if not authenticate.verify_user(username, password): return str(False) login_user(UserSession(username)) # check if username and password exist return str(authenticate.verify_user(username, password)) # USED FOR SIGN UP else: # POST # get information from client username = request.json['username'] password = request.json['password'] first_name = request.json['firstname'] last_name = request.json['lastname'] email = request.json['email'] birthday = request.json['birthday'] hometown = request.json['hometown'] # generate new hash password_hash = authenticate.generate_hash(username, password) user = User(username, first_name, last_name, email, password_hash, birthday, hometown) return str(neo4j.add_user(user))
async def sell(self, ctx, item_id): _item = Item(item_id) _user = User(ctx.message.author.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return if _item.exists is False: await self.bot.say(self.errors.ITEM_NOT_EXIST) return if len(_user.get_user_item(item_id)) == 0: await self.bot.say(self.errors.ITEM_DONT_OWN) return if _item.kind == 3: await self.bot.say("❌ | Badges cannot be sold.") cost = _item.cost give_back = cost * 0.20 _user.delete_user_item(item_id) _user.add_money(int(give_back)) await self.bot.say(self.msg.SELL_STR.format(int(give_back)))
async def unequip(self, ctx, item_id): _item = Item(item_id) _user = User(ctx.message.author.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return if _item.exists is False: await self.bot.say(self.errors.ITEM_NOT_EXIST) return if len(_user.get_user_item(item_id)) == 0 and len( _user.get_user_badge(item_id)) == 0: await self.bot.say(self.errors.ITEM_DONT_OWN) return try: if _user.get_user_item(item_id)[0][2] == 0: await self.bot.say(self.errors.NOT_EQUIPPED) return except: if _user.get_user_badge(item_id)[0][2] == 0: await self.bot.say(self.errors.NOT_EQUIPPED) return if _item.kind == 3: _user.unequip_badge(item_id) else: _user.unequip_item(item_id) await self.bot.say(self.msg.ITEM_UNEQUIPPED)
def test_rating_messages(self): # for creating a post to like location = {'latitude': 43.0100431, 'longitude': -78.8012356} username = "******" msg = "this is a rating test post" place_id = "ChIJwe_oGNJz04kRDxhd61f1WiQ" es = timezone("US/Eastern") time = str(datetime.now().astimezone(es) + timedelta(days=7)) # for liking rel = "LIKED" #add user to database first pwd = "admin" email = "*****@*****.**" fn = "Darren" ln = "Matthew" password_hash = authenticate.generate_hash(username, pwd) user = User(username, fn, ln, email, password_hash) self.assertTrue(neo4j.add_user(user)) # create a test post to add a like to post_id = neo4j.post_message(username, location, msg, time, place_id) # add like to the post success = neo4j.rate_post(post_id, rel, username) # delete test post neo4j.delete_post(post_id) # delete user neo4j.delete_user(username, password_hash) self.assertTrue(success)
async def ticketbuy(self, ctx, first: int, second: int, bet: int = 50): global current_pool author_id = ctx.message.author.id server_id = ctx.message.server.id _user = User(author_id) _server = Server(server_id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return if _user.money < bet: await self.bot.say(self.errors.INSUF_MONEY) return if _server.is_Registered is False: await self.bot.say(self.errors.SRV_NOT_IN_DB) return if _server.cmd_channel is None: await self.bot.say("❌ | Please register a commands spam channel.") return if bet < 50: await self.bot.say("❌ | Minimum bet is 50 coins!") return if first > 30 or second > 30: await self.bot.say( "❌ | Numbers allowed are only in the range 1-30.") return user_draw = [] user_draw.append(first) user_draw.append(second) try: _checker = server_bets[server_id] except: server_bets[server_id] = {} _user.add_money(-bet) if len(server_bets[server_id]) == 0: server_bets[server_id] = {author_id: user_draw} await self.bot.say( f"🎰 | You bought a ticket to the lottery with the numbers `{first}` and `{second}` respectively." ) await self.startlottery(ctx, bet * 3) else: if author_id in server_bets[server_id]: await self.bot.say(self.errors.TICKET_DUPLICATE) return else: await self.bot.say( f"🎰 | You bought a ticket to the lottery with the numbers `{first}` and `{second}` respectively." ) server_bets[server_id][author_id] = user_draw current_pool[ctx.message.server.id] += bet
def __get_user_objects_list(self): for obj in self.users_list: self.__user_list.append( User(obj['id'], obj['first_name'], obj['last_name'], obj['gender'], obj['dob'], obj['email'], obj['phone'], obj['website'], obj['address'], obj['status'])) return self.__user_list
async def drawresults(self, ctx, cmd_channel): global current_pool global draw global server_bets lottery_draw = [random.randint(1, 30), random.randint(1, 30)] if len(server_bets) == 0: count = 0 else: user_bets = server_bets[ctx.message.server.id] winner = [] for user in user_bets: if lottery_draw == user_bets[user]: winner.append(user) count = len(winner) if count == 0: string = f"No one won the `{current_pool[ctx.message.server.id]}` coins in the lottery!" elif count == 1: string = f"<@{winner[0]}> is the sole winner of `{current_pool[ctx.message.server.id]}` coins!" User(winner[0]).add_money(current_pool[ctx.message.server.id]) elif count > 1: pool = int(current_pool[ctx.message.server.id] / count) winners = "" for user in winner: winners += f"<@{user}> " User(user).add_money(pool) string = f"{winners} won the lottery and will receive `{pool}` coins each!" try: draw.pop(ctx.message.server.id) except: pass current_pool.pop(ctx.message.server.id) server_bets.pop(ctx.message.server.id) win = discord.Embed( title="🎰 Lotto Draw 🎰", description= f"Draw Results: `{lottery_draw[0]}` `{lottery_draw[1]}`", color=self.themes.MAIN_COL) win.add_field(name="🎊 Winner(s)", value=string, inline=False) await self.bot.send_message(cmd_channel, embed=win)
def prediccion_alq(): st.header('¿A cuanto debería alquilar mi depa?') st.write('''Para saber a cuanto deberias alquilar tu propiedad, hemos creado un modelo basado en mas de 10,000 registros existentes. Esto te va a permitir tener una idea de como valoriza el mercado tu casa/depa!. Pero para eso tenemos que saber un poco del mismo :) ''') distrito = st.selectbox('¿En que distrito se encuentra?',User().distritos) m2 = st.number_input('¿Cuantos m² totales tiene?',value = 0,min_value = 0,step =1) m2_techados = st.number_input('¿Cuantos de estos m² son techados?',value = 0,min_value = 0,step = 1) if m2 < m2_techados: st.warning('Los m² totales tienen que ser iguales o mayores que los m² techados ') else: parqueo = st.number_input('Cantidad de estacionamientos',value = 0,min_value = 0,step = 1) dormitorios = st.number_input('Numero de dormitorios',value = 0,min_value = 0,step = 1) antiguedad = st.number_input('Antigüedad (en años) del edificio/casa',value = 0,min_value = 0,step = 1) parque = st.radio('¿Tiene un parque cerca? Puede ser interno o no',('Si','No')) if parque == 'Si': parque = 1 else: parque = 0 tipo = st.radio('Casa o Departamento',('Casa','Departamento')) cant_pisos = st.selectbox('¿Cuántos pisos tiene?',[1,2,3,4,5]) if tipo == 'Casa': piso = 1 elif tipo == 'Departamento': piso = st.slider('Que piso se encuentra',1,25) prediccion = User().compute(m2 = m2, m2_techados = m2_techados,parking = parqueo,dorms = dormitorios, antiguedad = antiguedad,park_near = parque,floor = piso, mantenimiento = 0, cant_pisos = cant_pisos,type = tipo, distrito = distrito) upper_lim = round(np.exp(prediccion[0] + 0.2774),0) lower_lim = round(np.exp(prediccion[0])) st.markdown(f'''<h1 style='text-align: center; color: red;'>Lo podrias alquilar entre: S/ {int(lower_lim)} y {int(upper_lim)}</h1>''',unsafe_allow_html=True)
async def registeruser(self, ctx, user: discord.Member): _member = User(user.id) if _member.is_Registered: await self.bot.say(self.errors.USER_IN_DB) return _member.append_user await self.bot.say(self.msg.OPERATION_SUCCESSFUL)
async def setlevel(self, ctx, user: discord.Member, level: int): _user = User(user.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return _user.set_level(level) await self.bot.say(f"You set {user.mention}'s level to **{level}**.")
def test_user_list(): user = User(id="1854", first_name="C", last_name="Ext_Pmt_01", gender="male", dob="1935-07-18", email="*****@*****.**", phone="(561) 326-6099 x6922", website="http://kuhn.net/cumque-quisquam-illum-necessitatibus-ut-laborum-placeat", address="694 Cronin Shore\nDionfurt, IL 55781-1993", status="inactive") users = Users() users.get_users() assert users.check_user(user, users.users_list) is True
async def daily(self, ctx): _user = User(ctx.message.author.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return _user.add_money(200) await self.bot.say(self.msg.DAILY_RECEIVED.format(200))
async def grantcoins(self, ctx, user: discord.Member, coins: int): _user = User(user.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return _user.add_money(coins) await self.bot.say(f"You have given **{user.name}** `{coins}` coins.")
async def grantexp(self, ctx, user: discord.Member, exp: int): _user = User(user.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return _user.add_experience(exp) await self.bot.say( f"You have given **{user.name}** `{exp}` experience points.")
async def setexp(self, ctx, user: discord.Member, exp: int): _user = User(user.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return _user.set_experience(exp) await self.bot.say(f"You set {user.mention}'s experience to **{exp}**." )
async def setwarnings(self, ctx, user: discord.Member, warnings: int): _user = User(user.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return _user.set_warnings(warnings) await self.bot.say( f"You set {user.mention}'s warnings to **{warnings}**.")
def test1_user_signup(self): user = neo4j.get_user(self.uname) if user == self.uname: #delete user if already exists neo4j.delete_user(self.uname, self.password_hash) user = User(self.uname, self.fn, self.ln, self.email, self.password_hash, self.brd, self.hometown) # test adding user self.assertTrue(neo4j.add_user(user))