async def money(self, context, *args): try: # using money on a target. if len(args) > 0: # retrieve the target ID from the whoever the user mentioned target_id = context.message.mentions[0].id target = Users(target_id) if target.find_user() == 0: await context.send("Target does not have account.") return # fetch_user returns a User object that matches an id provided discord_member_target = await self.client.fetch_user(target_id) # embed the money retrieved from get_user_money(), set thumbnail to 64x64 version of target's id em = discord.Embed(title="", colour=0x607D4A) em.add_field( name=discord_member_target.display_name, value=f"**:moneybag: ** {target.get_user_money()}", inline=True, ) thumb_url = ( f"https://cdn.discordapp.com/avatars/{discord_member_target.id}" f"/{discord_member_target.avatar}.webp?size=64") em.set_thumbnail(url=thumb_url) await context.send(context.author.mention, embed=em) # if they passed no parameter, get their own money else: # create user instance with their discord ID, check database for their money field user = Users(context.author.id) # embed the money retrieved from get_user_money(), set thumbnail to 64x64 version of user's id em = discord.Embed(title="", colour=0x607D4A) em.add_field( name=context.author.display_name, value=f"**:moneybag: ** {user.get_user_money()}", inline=True, ) thumb_url = ( f"https://cdn.discordapp.com/avatars/{context.author.id}" f"/{context.author.avatar}.webp?size=64") em.set_thumbnail(url=thumb_url) await context.send(context.author.mention, embed=em) # Added this exception for debugging purposes. except Exception as e: msg = f"Not ok! {e.__class__} occurred" log.debug(msg) await context.send( f"{context.author.mention}```ml\nuse =money like so: **=money** or **=money @user**" ) finally: # delete original message to reduce spam await context.message.delete()
async def ranks(self, context): # create instance of user who wants to view rankings user = Users(context.author.id) # retrieve top 15 ranked players rankings = user.get_user_ranks() # declare variables we will use as columns for the leaderboards name_field_column = "" win_loss_column = "" # set counter to properly display rank numbers counter = 1 # iterate through the top 15 ranked players and retrieve their specific stats for rank in rankings: # initiate each ranked player user = Users(str(rank[0])) # store their stats in temporary variables ( weapon_level, helmet_level, chest_level, boots_level, battles_lost, battles_won, total_winnings, ) = user.get_user_stats(0) # format money for commas total_winnings = f"{total_winnings:,}" # try to retrieve user's level, if failed, skip to next iteration try: user_level = user.get_user_level(0) except Exception as e: log.debug(f"[{type(e).__name__} {e}] - User not found.") continue # get the "member" discord object in order to retrieve the user's current discord name discordmember = await self.client.fetch_user(rank[0]) ranker_name = str(discordmember.name) # remove everything except alphanumerics from the user's current discord name ranker_name = re.sub(r"\W+", "", ranker_name) # format the 2 columns for the leaderboards name_field_column += f"{counter}. {ranker_name[:15]} \u200B \u200B (_lvl: {user_level}_ ) \u200B \u200B \n" win_loss_column += f"${total_winnings}/{battles_won}/{battles_lost}\n" counter += 1 # embed the ranking columns em = discord.Embed(title="", colour=0x607D4A) em.add_field(name="Top 15 Fighters", value=name_field_column, inline=True) em.add_field(name="Winnings/W/L", value=win_loss_column, inline=True) # set embedded thumbnail to an upwards trend chart em.set_thumbnail( url= "https://cdn.shopify.com/s/files/1/0185/5092/products/objects-0104_800x.png?v=1369543363" ) await context.send(embed=em)
async def profile_stats(self, context, *args): try: # using stats on a target. if len(args) > 0: # retrieve the target ID from the whoever the user mentioned target_id = context.message.mentions[0].id target = Users(target_id) if target.find_user() == 0: await context.send("Target does not have account.") return # fetch_user returns a User object that matches an id provided discord_member_target = await self.client.fetch_user(target_id) target_avatar_url = discord_member_target.avatar_url # embed the statistics retrieved from get_user_stats(), set thumbnail to target's id em = discord.Embed(title="", colour=0x607D4A) em.add_field( name=discord_member_target.display_name, value=target.get_user_stats(), inline=True, ) em.set_thumbnail(url=target_avatar_url) await context.send(context.author.mention, embed=em) # if they passed no parameter, or user was not found, get their own records else: # create user instance with their discord ID, check database for their level field user = Users(context.author.id) # embed the statistics retrieved from get_user_stats(), set thumbnail to user's id em = discord.Embed(title="", colour=0x607D4A) em.add_field( name=context.author.display_name, value=user.get_user_stats(), inline=True, ) em.set_thumbnail(url=context.author.avatar_url) await context.send(context.author.mention, embed=em) except Exception as e: msg = f"Not ok! {e.__class__} occurred" log.debug(msg) await context.send( f"{context.author.mention}```ml\nuse =profile like so: **=profile** or **=profile @user**" )
def __init__(self, User=Users()): root = Tk() root.title("Dash board") style = ttk.Style() style.theme_use("alt") image = PhotoImage(file="userimage.png") imageframe = ttk.Frame(root, width=10, height=10).grid(row=0, column=0) ttk.Label(imageframe, image=image).grid(row=0, column=0) container = ttk.Frame(root, width=800, height=600) container.grid(row=0, column=1) def DeleteaccountButtonfunction(): root.destroy() root.quit() from Deleteaccount import Deleteaccount next = Deleteaccount(User) DeleteaccountButton = ttk.Button( container, text=" Delete account ", command=DeleteaccountButtonfunction).pack() def ChangepasswordButtonfunction(): root.destroy() root.quit() after = Changepassword(User) ChangepasswordButton = ttk.Button( container, text="Change password", command=ChangepasswordButtonfunction).pack() root.mainloop()
def processUser(name, todayMonth): usersList = [] print(todayMonth) print(name) user_file = open('file/usersNew.txt', 'r') for ulist in user_file: list = ulist.split(',') savedate = list[5] savedateStr = savedate.split('-') dd = int(savedateStr[0]) mm = int(savedateStr[1]) yy = int(savedateStr[2]) print(mm) if list[0] == name and mm == todayMonth: goal = float(list[4]) #current month #saveCurrent = float(list[3]) saveTotal = searchHistoryforTotalSaving(list[0], list[6]) howmuchMore = goal - saveTotal howmuchMore = '%.2f' % howmuchMore monthly = 0.05 / 12 convert = monthly / 100 interest = saveTotal * convert i = '%.2f' % interest s = Users(list[0], list[1], list[2], list[3], list[4], list[5], list[6], list[7], howmuchMore, i, list[8]) usersList.append(s) return usersList
def loadSkarphedChildren(self): self.loadPublicKey() self.getMaintenanceMode() self.loadRendermode() if 'skarphed.users.view' in self.serverRights: self.users = Users(self) self.addChild(self.users) if 'skarphed.modules.install' in self.serverRights or 'skarphed.modules.uninstall' in self.serverRights: self.modules = Modules(self) self.addChild(self.modules) if 'skarphed.roles.view' in self.serverRights: self.roles = Roles(self) self.addChild(self.roles) if True: #'skarphed.sites.view' in self.serverRights self.sites = Sites(self) self.addChild(self.sites) if True: self.views = Views(self) self.addChild(self.views) if True: #'skarphed.template.modify' in self.serverRights self.template = Template(self) self.addChild(self.template) if True: #'skarphed.operation.modify' in self.serverRights self.operationManager = OperationManager(self) #TODO: restliche implementieren self.pokethread = PokeThread(self) self.pokethread.start()
def crea_usuarios(self): """Da de alta en ldap los usuarios que están en el listado""" lista = [] if self.esAlumnos: tipo = "student" else: tipo = "teacher" for usuario in self.usuarios: if not self.existsUsername(usuario['login']): if self.esAlumnos: if usuario['foto'] == 'false': foto = None else: foto = self.encode(usuario['foto']) else: foto = None surname = usuario['primer-apellido'] + ' ' + usuario[ 'segundo-apellido'] nuevo = Users(self.ldap_con, tipo, usuario['nombre'], surname.strip(), usuario['dni'], usuario['login'], usuario['passwd'], usuario['passwd'], '', '', foto) nuevo.add() lista.append((usuario['login'], True, usuario['passwd'])) else: lista.append((usuario['login'], False, '')) return lista
def __init__(self, User=Users()): root = Tk() root.title("Delete account") ttk.Label(root, text="Enter your password").pack() Passwordfield = Text(root, width=35, height=2) Passwordfield.pack() def Deletebuttonfunction(): if Passwordfield.get("1.0", tkinter.END) == User.Password: User.Deleteaccount() else: tkinter.messagebox.showinfo("Error", "Failed Try later") root.destroy() root.quit() Deletebutton = ttk.Button(root, text="Delete!", command=Deletebuttonfunction).pack() def Cancelbuttonfunction(): root.destroy() root.quit() next = Dashboard(User) Cancelbutton = ttk.Button(root, text="Cancel", command=Cancelbuttonfunction).pack() root.mainloop()
def __init__( self, database, settings, suppress_exceptions = False ): """ Create a new Root object with the given settings. @type database: controller.Database @param database: database to use for all controllers @type settings: dict @param settings: CherryPy-style settings @rtype: Root @return: newly constructed Root """ self.__database = database self.__settings = settings self.__users = Users( database, settings[u"luminotes.http_url"], settings[u"luminotes.https_url"], settings[u"luminotes.support_email"], settings[u"luminotes.payment_email"], settings[u"luminotes.rate_plans"], settings[u"luminotes.download_products"], ) self.__groups = Groups( database, self.__users ) self.__files = Files( database, self.__users, settings[u"luminotes.download_products"], settings[u"luminotes.web_server"], ) self.__notebooks = Notebooks( database, self.__users, self.__files, settings[ u"luminotes.https_url"] ) self.__forums = Forums( database, self.__notebooks, self.__users ) self.__blog = Forum( database, self.__notebooks, self.__users, u"blog" ) self.__suppress_exceptions = suppress_exceptions # used for unit tests
def __init__(self): self.__version__ = '3.1.3' logger_format = '%(asctime)s %(message)s' logging.basicConfig(format=logger_format, level=logging.INFO, datefmt="%H:%M:%S", filename='./logfile.log', filemode='w') logging.getLogger().addHandler(SysLogHandler(facility=SysLogHandler.LOG_DAEMON, address='/dev/log')) self._SIGKILL = False self.logging = logging self.config = DB('./config.json') self.network = Network(self) self.display = DisplayContent() self.detector = Detector() self.ultrasound = Ultrasound(self) self.temp = Temp() self.server = SimpleWebSocketServer('', 8069, WebSocketServer, self) self.cook = Cook(self) self.energy = Energy(self) self.history = History(self) self.audio = Audio(self) self.users = Users(self) self.automations = Automations(self) signal.signal(signal.SIGTERM, self.sig_handler) signal.signal(signal.SIGINT, self.sig_handler) self.log("Boot: v" + self.__version__)
def LoginButtonfunction(): User = Person() User.Username = UsernameField.get("1.0", END) User.Password = passwordField.get("1.0", END) if len(User.Username) - 1 != 0 and len(User.Password) - 1 != 0: Data = User.Login(User.Username, User.Password) if Data[0] and Data[1].Authorize: if not Data[1].Admin: User = Users() else: User = Admin() User.Username = Data[1].Username User.Password = Data[1].Password User.Folderpath = Data[1].Folderpath User.Authorize = Data[1].Authorize User.Admin = Data[1].Admin if not User.Admin: root.destroy() root.quit() from Dashboard import Dashboard next = Dashboard(User) else: pass # الى هيعمل ال admin else: tkinter.messagebox.showinfo(" Invalid Credintial", "User Doesnot exist thank you :)") root.destroy() root.quit() else: tkinter.messagebox.showinfo("Empty fields", "Do net leave any field empty ")
def init(): """ NOTE : initialize database """ My_db_class() # initialize Users Users()
async def give(self, context, *args): # will automatically go to exception if all arguments weren't supplied correctly try: receiver_string = args[0] amnt = int(args[1]) if amnt < 1: await context.send("Can’t GIFT DEBT!") return # create user instance with their discord ID, check database for their level field donator = Users(context.author.id) # set the receiver ID to whoever the donator mentioned receiver = Users(context.message.mentions[0].id) # check if receiver has account if receiver.find_user() == 0: await context.send( f"{context.author.mention} The target doesn't have an account." f"\nUse **=create** to make one.") return # check if donator has enough money for the donation # pass 0 to return integer version of money, see USERS.PY function if int(amnt) > donator.get_user_money(0): await context.send( f"{context.author.mention} You don't have enough money for that donation..." f" <a:pepehands:485869482602922021> ") return # pass the donation amount, pass the receiver user object, and pass the receiver's string name msg = context.author.mention + " " + donator.donate_money( int(amnt), receiver, receiver_string) # embed the donation message, put a heartwarming emoji size 64x64 as the thumbnail em = discord.Embed(title="", colour=0x607D4A) em.add_field(name="DONATION ALERT", value=msg, inline=True) em.set_thumbnail( url= "https://cdn.discordapp.com/emojis/526815183553822721.webp?size=64" ) await context.send(embed=em) await context.message.delete() except Exception as e: msg = f"Not ok! {e.__class__} occurred" log.debug(msg) await context.send( f"{context.author.mention}```ml\nuse =give like so: **=give @user X**" f" -- X being amnt of money to give```")
def send_start(_, message): start_text = "Привет! Этот бот отправляет тебе расписание перед парами!\n" \ "Так же можешь почитать `/help`" message.reply_text(start_text) u = Users() if u.check_user(message.chat.id) is False: u.reg_user(message.chat.username, message.chat.id, "user")
def start_message(message): user = users.get(message.chat.id) if not user: user = Users(message.chat.id) users[message.chat.id] = user bot.send_message(message.chat.id, 'Выбери сайт(ы), на который(ые) ты хочешь подписаться', reply_markup=key_board1) user.state = 1
def processUserDetails(): detailsList = [] user_file = open('file/accountDetails', 'r') for dlist in user_file: list = dlist.split(',') s = Users(list[0], list[1], list[2], float(list[3]), float(list[4])) detailsList.append(s) return detailsList
def __init__(self, User=Users()): root = tkinter.Tk() root.title("Change Account Password") style = ttk.Style() style.theme_use("alt") container = ttk.Frame(root, width=800, height=600) container.pack() ttk.Label(container, text="Current Password: "******"New-Password: "******"Re-entr-New-Password: "******"1.0", END) == User.Password and len( NewpasswordField.get( "1.0", END)) >= 9 and NewpasswordField.get( "1.0", END) == reenternewpasswordField.get( "1.0", END): try: User.Changepassword(NewpasswordField.get("1.0", END)) root.destroy() root.quit() from Dashboard import Dashboard next = Dashboard(User) except: tkinter.messagebox.showinfo("Error", "Operation failed try later") root.destroy() root.quit() else: tkinter.messagebox.showinfo("Invalid Passwords", "Passwords are Invalid") root.destroy() root.quit() LoginButton = ttk.Button(container, text="Submit", command=LoginButtonfunction).grid(row=3, column=0) def CancelButtonfunction(): root.destroy() root.quit() from Dashboard import Dashboard next = Dashboard(User) CancelButton = ttk.Button(container, text="Cancel", command=CancelButtonfunction).grid(row=3, column=1) root.mainloop()
def processUser(): usersList = [] user_file = open('file/users.txt', 'r') for ulist in user_file: list = ulist.split(',') s = Users(list[0], list[1], int(list[2])) usersList.append(s) return usersList
def loginUser(): userList = [] user_info = open("file/users.txt", "r") for i in user_info: info = i.split(",") u = Users(info[0], info[1], info[2]) userList.append(u) return userList
def send_every_day(): today = date.today() lessons = wrapper.date_wrapper(today.day) u = Users() users = u.get_users() for id, _, _ in users: try: app.send_message(id, lessons) except PeerIdInvalid: pass
async def register(self, context): # create new user instance with their discord ID to store in database new_user = Users(context.message.author.id) if new_user.find_user() == 1: await self.client.say('<:worrymag1:531214786646507540> You **already** have an account registered!') return em = discord.Embed(title="", colour=0x607d4a) em.add_field(name=context.message.author.display_name, value=new_user.add_user(), inline=True) em.set_thumbnail(url=context.message.author.avatar_url) await self.client.say(embed=em)
def send_announce(_, message): u = Users() users = u.get_users() admins = u.get_admins() if message.chat.id in admins: for id, username, _ in users: app.send_message(id, message.command[1]) else: try: app.send_message(message.chat.id, "У вас нет прав") except PeerIdInvalid: pass
def create_account(): data = request.get_json() username = data.get("username") password = data.get("password") password_hash = hash_password(password) new_user = Users(username=username, password_hash=password_hash) try: new_user.add_user() return jsonify({"created": "success"}) except IntegrityError: print("Account already exists!") return jsonify({"created": "failed"})
def __init__(self, base_url, username, password, verify_ssl=True): api_args = { "base_url": base_url, "username": username, "password": password, "verify_ssl": verify_ssl } self.queues = Queues(**api_args) self.users = Users(**api_args) self.organization_units = OrganizationUnits(**api_args) self.assets = Assets(**api_args) self.robots = Robots(**api_args) self.environments = Environments(**api_args)
def processUser(name, todayMonth, todayYear): usersList = [] print(todayMonth) print(todayYear) print(name) user_file = open('file/users.txt', 'r') for ulist in user_file: list = ulist.split(',') if list[0] == name and int(list[4]) == todayMonth and int( list[5]) == todayYear: s = Users(list[0], list[1], list[2], list[3], list[4], list[5]) usersList.append(s) return usersList
async def give(self, context, *args): # will automatically go to exception if all arguments weren't supplied correctly try: receiver_string = args[0] amnt = int(args[1]) if amnt < 1: await self.client.say("Can’t GIFT DEBT!") return # create user instance with their discord ID, check database for their level field donator = Users(context.message.author.id) # use regex to extract only numbers from "receiver_string" to get their discord ID, # ex: <@348195501025394688> to 348195501025394688 receiver = Users(re.findall("\d+", receiver_string)[0]) # check if receiver has account if receiver.find_user() == 0: await self.client.say(context.message.author.mention + " The target doesn't have an account." "\nUse **=create** to make one.") return # check if donator has enough money for the donation # pass 0 to return integer version of money, see USERS.PY function if int(amnt) > donator.get_user_money(0): await self.client.say(context.message.author.mention + " You don't have enough money for that donation..." " <a:pepehands:485869482602922021> ") return # pass the donation amount, pass the receiver user object, and pass the receiver's string name msg = context.message.author.mention + ' ' + donator.donate_money(int(amnt), receiver, receiver_string) # embed the donation message, put a heartwarming emoji size 64x64 as the thumbnail em = discord.Embed(title="", colour=0x607d4a) em.add_field(name="DONATION ALERT", value=msg, inline=True) em.set_thumbnail(url="https://cdn.discordapp.com/emojis/526815183553822721.webp?size=64") await self.client.say(embed=em) await self.client.delete_message(context.message) except: await self.client.say(context.message.author.mention + '```ml\nuse =give like so: **=give @user X** -- X being amnt of money to give```')
async def level(self, context, *args): # this 'try' will process if they want to check another player's level # it will only process if they passed that user as an argument try: # use regex to extract only numbers to get their discord ID, # ex: <@348195501025394688> to 348195501025394688 # create user instance with their target's discord ID, check database for their level field target_id = re.findall("\d+", args[0])[0] target = Users(target_id) if target.find_user() == 0: await self.client.say('Target does not have account.') return # get_member() returns the "member" object that matches an id provided discord_member_target = context.message.server.get_member(target_id) # embed the level retrieved from get_user_level(), set thumbnail to 64x64 version of target's id em = discord.Embed(title="", colour=0x607d4a) em.add_field(name=discord_member_target.display_name, value="**Level** " + target.get_user_level(), inline=True) thumb_url = "https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.webp?size=64".format(discord_member_target) em.set_thumbnail(url=thumb_url) await self.client.send_message(context.message.channel, context.message.author.mention, embed=em) # if they passed no parameter, get their own level except: # create user instance with their discord ID, check database for their level field user = Users(context.message.author.id) # embed the level retrieved from get_user_level(), set thumbnail to 64x64 version of user's id em = discord.Embed(title="", colour=0x607d4a) em.add_field(name=context.message.author.display_name, value="**Level** " + user.get_user_level(), inline=True) thumb_url = "https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.webp?size=64".format(context.message.author) em.set_thumbnail(url=thumb_url) await self.client.send_message(context.message.channel, context.message.author.mention, embed=em) # delete original message to reduce spam await self.client.delete_message(context.message)
async def enter_daily_tournament(self, context): # the bulk work of this feature is when the results are calculated from daily_maintenance.py # create instance of user who wants to enter the daily, server-specific colosseum tournament fighter = Users(context.message.author.id) # update their tourney_server_id entry to be the server they executed the command on msg = fighter.update_user_tourney_server_id( context.message.server.name, context.message.server.id) # embed the tourney registration confirmation message, set thumbnail to 40x40 of the respective server's icon em = discord.Embed(description=msg, colour=0x607d4a) thumb_url = "https://cdn.discordapp.com/icons/{0.id}/{0.icon}.webp?size=40".format( context.message.server) em.set_thumbnail(url=thumb_url) await self.client.say(embed=em)
def user(): user_id = request.args.get('id') email_address = request.args.get('email') fname = request.args.get('fname') lname = request.args.get('lname') password = request.args.get('password') if (user_id == None) and (email_address == None) and (fname == None) and ( lname == None) and (password == None): data = request.get_json(force=True) if request.method in {'GET', 'PUT', 'DELETE'}: user_id = data['user_id'] if request.method in {'PUT', 'POST'}: email_address = data['email_address'] fname = data['fname'] lname = data['lname'] password = data['password'] # Get a specific user based on user id if request.method == 'GET': user = session.query(Users).filter_by(user_id=user_id).one() return user_schema.jsonify(user) # Update a specific user based on user id and new information if request.method == 'PUT': editedUser = session.query(Users).filter_by(user_id=user_id).one() editedUser.email_address = email_address editedUser.fname = fname editedUser.lname = lname editedUser.password = password session.commit() return user_schema.jsonify(editedUser) # Create a new user if request.method == 'POST': newUser = Users(email_address, fname, lname, password) session.add(newUser) session.commit() return user_schema.jsonify(newUser) # Delete at existing user if request.method == 'DELETE': deletedUser = session.query(Users).filter_by(user_id=user_id).one() session.delete(deletedUser) session.commit() return user_schema.jsonify(deletedUser) return
async def adopt_pet(self, context): # create instance of the user who wishes to feed their pet pet_owner = Users(context.author.id) if pet_owner.find_pet() == 1: msg = await context.send("Failed! You already have a pet!") await asyncio.sleep(5) await msg.delete() return intro_msg = "Welcome to the **Pet Shelter**!\n\nPlease enter your desired pet name now:" # embed intro message, then overwrite the variable with the actual message object em = discord.Embed(description=intro_msg, colour=0x607D4A) em.set_thumbnail( url= "https://cdn.discordapp.com/emojis/746904102650249296.gif?size=128" ) await context.send(embed=em) # wait for user's pet name entry # helper to check if it's the author that it's responding. def is_author(m): return m.author == context.author and m.channel == context.channel pet_name = await self.client.wait_for("message", check=is_author, timeout=60) # remove everything except alphanumerics from the user's pet name entry pet_name = re.sub(r"\W+", "", pet_name.clean_content) # create an object to scan profanity pf = ProfanityFilter() # while the pet name entry has profanity, prompt user to re-enter a name while not pf.is_clean(pet_name): await context.send( "Pet name has profanity! Please enter a new one now:") # wait for user's new pet name entry pet_name = await self.client.wait_for("message", check=is_author, timeout=60) # remove everything except alphanumerics from the user's pet name entry pet_name = re.sub(r"\W+", "", pet_name.clean_content) adoption_msg = pet_owner.add_pet(pet_name[:15]) # embed confirmation message em = discord.Embed(description=adoption_msg, colour=0x607D4A) em.set_thumbnail( url="https://cdn.discordapp.com/emojis/563872560308289536.png?v=1") await context.send(embed=em)