async def deregister(self, ctx: commands.Context): record = Record(discordid=ctx.author.id) try: guild = self.bot.get_guild(constants.SERVERID) member = discord.utils.get(guild.members, id=ctx.author.id) roleName = await self.bot.controller.getRoleForUser( Record(discordid=ctx.author.id)) role = discord.utils.get( guild.roles, name=roleName.lower() if roleName is not None else None) await self.bot.controller.deregister(record) try: await member.remove_roles(role) await ctx.channel.send("Successfully deregistered.") await self.bot.controller.dbInstance.commit() except discord.errors.Forbidden: await self.bot.controller.dbInstance.rollback() await ctx.channel.send( "Unable to deregister because the bot doesn't have sufficient permissions to give roles. Contact: {}" .format(constants.ADMIN_USER)) except DeregisterException as e: getLogger(__name__).warning(str(e)) await ctx.channel.send("Your Discord ID has not been registered.") except Exception as e: getLogger(__name__).error(str(e)) await ctx.channel.send( "There is an error with the bot. Contact admin: {}".format( constants.ADMIN_USER))
async def register(self, user: Record): if not (await self.isEmailValid(user.email)): raise InvalidEmailException() userExists = await self.userNameExists(Record(discordid=user.discordid)) emailExists = await self.emailExists(Record(email=user.email)) if userExists: isPendingSenderUser = await self.isPending(Record(discordid=user.discordid)) strPendingSender = "pending" if isPendingSenderUser else "registered" if emailExists: isPendingEmailUser = await self.isPending(Record(email=user.email)) strPendingEmailUser = "******" if isPendingEmailUser else "registered" if isPendingSenderUser and isPendingEmailUser: #delete both the record which shares the discord id (and is pending) and the other record which shares the email (and is pending) await self.dbInstance.deleteRecord(Record(discordid=user.discordid)) await self.dbInstance.deleteRecord(Record(email=user.email)) try: await self.helperInsertRecord(user) except EmailException as e: await self.dbInstance.rollback() raise e await self.dbInstance.commit() raise UsernameExistsException(f"Register error: Discord ID {user.discordid} exists, state '{strPendingSender}' | email {user.email} exists, state '{strPendingEmailUser}'", True, isPendingSenderUser, isPendingEmailUser) else: #user exists, but email record doesn't exist if isPendingSenderUser: await self.dbInstance.deleteRecord(Record(discordid=user.discordid)) try: await self.helperInsertRecord(user) except EmailException as e: await self.dbInstance.rollback() raise e await self.dbInstance.commit() raise UsernameExistsException(f"Register error: Discord ID {user.discordid} exists, state '{strPendingSender}' | email {user.email} doesn't exist", False, isPendingSenderUser, None) else: #user doesn't exist isPendingEmailUser = await self.isPending(Record(email=user.email)) strPendingEmailUser = "******" if isPendingEmailUser else "registered" if emailExists: if isPendingEmailUser: await self.dbInstance.deleteRecord(Record(email=user.email)) try: await self.helperInsertRecord(user) except EmailException as e: await self.dbInstance.rollback() raise e await self.dbInstance.commit() raise UsernameNonExistentException(f"Register error: Discord ID {user.discordid} doesn't exists | email {user.email} exists", True, isPendingEmailUser) else: #user doesn't exist, email doesn't exist. Everything is fine try: await self.helperInsertRecord(user) except EmailException as e: await self.dbInstance.rollback() raise e await self.dbInstance.commit()
def setUp(self): self.user_id = 1 self.exercise_name = "Arnold Press" self.username = "******" created_on = get_timestamp() record_repository.save_workout_as_record( Record(self.exercise_name, 12, 3, self.username, created_on))
async def helperInsertRecord(self, user: Record): token = tokengenerator.getToken() user.token = token await self.dbInstance.insertRecord(user) try: await emailhandler.sendToken([user.email], token) except Exception as e: raise EmailException(e)
async def getRecords(self, record: Record): #Discordid, Email, Token, Time, Type, Status tmp = await self.dbInstance.getRecords(record) ret = [] for x in tmp: discordid, email, token, time, _type, status = x r = Record(discordid=discordid, email=email, token=token, time=time, _type=_type, status=status) ret.append(r) await self.dbInstance.commit() return ret
def save_workout(self, exercise, sets, reps, username): """Tallentaa suoritetun harjoituksen suorituksena Attributes: exercise: Kuvaa suoritetun harjoituksen nimettä sets: Kuvaa sarjojen määrää reps: Kuvaa toistojen määrää reps: Kuvaa käyttäjätunnusta """ created_on = get_timestamp() result = self._record_repo.save_workout_as_record( Record(exercise, sets, reps, username, created_on)) return result
async def register(self, ctx: commands.Context, _type: str, email: str): _type = getFromListCaseIgnored(_type, constants.REGISTERED_ROLE_NAMES) if _type is None: raise commands.errors.BadArgument( "Bad register command argument: invalid role name.") record = Record(discordid=ctx.author.id, email=email, _type=_type) try: await self.bot.controller.register(record) await ctx.channel.send("Email sent!") except InvalidEmailException as e: getLogger(__name__).warning(str(e)) await ctx.channel.send( "Email {} doesn't meet our requirements.\nCheck the server registration rules." .format(email)) except UsernameExistsException as e: getLogger(__name__).warning(str(e)) firstScenarioToResend = e.emailExists and e.emailUserPending and e.senderUserPending secondScenarioToResend = not e.emailExists and e.senderUserPending if not e.senderUserPending: await ctx.channel.send("You have already registered!") if firstScenarioToResend or secondScenarioToResend: await ctx.channel.send( "Email sent!\nWarning: you have already tried registering this Discord ID. The old token is now invalid." ) except UsernameNonExistentException as e: getLogger(__name__).warning(str(e)) if e.emailExists: if e.emailUserPending: #This email was pending registration from another user. Hijacking the email... await ctx.channel.send("Email sent!") else: await ctx.channel.send( "This email belongs to a registered account.") except EmailException as e: getLogger(__name__).warning(str(e)) await ctx.channel.send( "An error occurred while attempting to send the email.\nTry again later or contact {}." .format(constants.ADMIN_USER)) except Exception as e: getLogger(__name__).error(str(e)) await ctx.channel.send( "There is an error with the bot. Contact admin: {}".format( constants.ADMIN_USER))
async def validate(self, ctx: commands.Context, token: str): record = Record(discordid=ctx.author.id, token=token) try: guild = self.bot.get_guild(constants.SERVERID) member = discord.utils.get(guild.members, id=ctx.author.id) roleName = await self.bot.controller.getRoleForUser( Record(discordid=ctx.author.id)) role = discord.utils.get(guild.roles, name=roleName) await self.bot.controller.validate(record) try: await member.add_roles(role) await ctx.channel.send( "Your account has been successfully validated.") await self.bot.controller.dbInstance.commit() except discord.errors.Forbidden: await self.bot.controller.dbInstance.rollback() await ctx.channel.send( "Unable to validate because the bot doesn't have sufficient permissions to give roles. Contact: {}" .format(constants.ADMIN_USER)) except ValidationException as e: getLogger(__name__).error(str(e)) await ctx.channel.send("Validation failed.")
def update_record(self, phone_number: str, new_record: Record): if phone_number != new_record.phone_number and self._key_exists( new_record.phone_number): raise ValueError("phone number already exists. Try new one.") query = """update Record set first_name = ?, last_name = ?, phone_number = ?, birth_date = ? where phone_number = ? """ self.db.execute( query, new_record.to_tuple() + (phone_number, ), )
def extractRecord(text): """ Extracts from code a record object, which contain such information as tag, type, name of variable abd its description. @param {string} text. @return {jsCodeParser.record.Record} Record """ tag = __extractTag(text) position = text.find(tag) + len(tag) text = text[position:] recordMap = { 'type': { 'extractor': __extractType, 'value': '' }, 'name': { 'extractor': __extractName, 'value': '' }, 'description': { 'extractor': __extractDescription, 'value': '' } } while text: for key in ['type', 'name', 'description']: extractor = recordMap[key]['extractor'] value = extractor(text, tag) if value: recordMap[key]['value'] = value position = text.find(value) + len(value) text = text[position:] text = text.strip('. ') typeExpression = recordMap['type']['value'] name = recordMap['name']['value'] description = recordMap['description']['value'] return Record(tag, typeExpression, name, description)
def get_record(self, phone_number: str) -> Record: result = f"select first_name, last_name, phone_number, birth_date date from Record where phone_number like '{phone_number}'" data = self.db.execute(result).fetchone() return Record(*data)
def add_record(self, record: Record): data = record.to_tuple() self.db.execute(f"""insert into Record values ('{data[0]}', '{data[1]}', '{data[2]}', '{data[3]}')""") self.connection.commit()
def _make_record(self) -> Record: record = Record(self.f_name_line.text(), self.l_name_line.text(), self.number_line.text(), self.dateEdit.date()) return record
async def emailExists(self, record: Record) -> bool: return await self.exists(Record(email=record.email))
async def userNameExists(self, record: Record) -> bool: return await self.exists(Record(discordid=record.discordid))
def test_save_workout_as_record(self): created_on = get_timestamp() result = record_repository.save_workout_as_record( Record("test", 12, 3, "test123", created_on)) self.assertEqual(result, True)