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)
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 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.")
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 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}.")
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)
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 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
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 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}**.")
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 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}**.")
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}**." )
def get_user(user_id, **kwargs): """ Authentication: is_valid_session Authorization: target_user_is_session_user URL: <user_id>: Target user id Success (200): Returns requested user Fail (40X): """ user = User(user_id) return Response(json.dumps(user.serialize()), status=200)
async def setabout(self, ctx, *, string): _user = User(ctx.message.author.id) if _user.is_Registered is False: await self.bot.say(self.errors.USER_NOT_IN_DB) return if len(string) > 140: await self.bot.say(self.errors.ABOUT_LIMIT) return _user.set_about(string) await self.bot.say(self.msg.OPERATION_SUCCESSFUL)
async def opencrate(self, ctx, crate_id: str): 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 item = self.inventory.get_item(crate_id) if len(item) == 0: await self.bot.say(self.errors.ITEM_NOT_EXIST) return item_name = item[0][0] item_type = item[0][1] crate_key = item[0][4] if len(_user.get_user_item(item_name)) == 0: await self.bot.say(self.errors.ITEM_DONT_OWN) return if item_type is not 2: await self.bot.say(self.errors.NOT_CRATE) return if len(_user.get_user_item(crate_key)) == 0: await self.bot.say(self.errors.NO_KEY) return pool = [] for heading in crates: if heading == crate_id: for given in crates[heading]: pool = list(given['pool']) string = given['str'] draw = random.choice(pool) draw_str = str(draw) + string if draw is None: await self.bot.say(self.msg.CRATE_NONE) _user.delete_user_item(crate_key) _user.delete_user_item(item_name) else: await self.bot.say(self.msg.CRATE_WON.format(draw_str)) _user.add_money(draw) _user.delete_user_item(crate_key) _user.delete_user_item(item_name)
def register_user(self, sid, name): """Initialize a new user""" user = User(sid, name) self.current_user.add(user) return user
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))
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)
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 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)
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 __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
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)
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 loot(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 creds = random.randint(10, 99) probabilities = [True, False] choice = probabilities[random.randint(0, 1)] if choice: _user.add_money(creds) await self.bot.say(self.msg.LOOT_SUCCESSFUL.format(creds)) else: await self.bot.say(self.msg.LOOT_FAIL)
async def slots(self, ctx, bet: int = 50): if bet < 50: await self.bot.say(self.errors.BET_INSUF.format("50")) return 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 if _user.money < bet: await self.bot.say(self.errors.INSUF_MONEY) return if bet <= 100 and bet > 0: bet_win_ratio = 0.5 elif bet <=500 and bet > 100: bet_win_ratio = 1.25 elif bet <= 1000 and bet > 500: bet_win_ratio = 1.5 else: bet_win_ratio = 2.25 event = self.helpers.getSlotsScreen() await self.bot.say(event[0]) if event[1] == 3: win_value = int(1000000 * bet_win_ratio) await self.bot.say(f"🎇🎉🎊 | YOU WON **{win_value}** coins from the slot!") elif event[1] == 2: win_value = int(bet * bet_win_ratio) await self.bot.say(f"👏👌 | You won **{win_value}** coins from the slot!") elif event[1] == 1: win_value = bet await self.bot.say(f"👍 | You won back your bet.") else: win_value = -bet await self.bot.say(f"\n 😢 | You lost your bet.") _user.add_money(win_value)
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)
async def reward_user(self, bot, user_id): _user = User(user_id) if quizzes[user_id][1] == "easy": prize = 50 elif quizzes[user_id][1] == "medium": prize = 125 elif quizzes[user_id][1] == "hard": prize = 200 _user.add_money(prize) channel = discord.utils.get(self.bot.get_all_channels(), id=quizzes[user_id][2]) await bot.send_message( channel, f"✅ | You answered the question correctly! You received **{prize}** coins." )