Пример #1
0
def t_resumen_API(origin_dict=None):
    '''get the desired data'''
    target_dict = {}
    try:
        for k, v in RESUMEN_RENAME.iteritems():
            target_dict[v] = origin_dict['resumen'][k]
    except KeyError:
        log.error("Could not find required key %s in %s" % (k, origin_dict))
        raise Paso2015(__name__)

    # Calculate table percentage
    mp = get_percentage(target_dict, 'mi', 'mt')
    target_dict["mp"] = mp

    # Calculate voting percentage
    vp = get_percentage(target_dict, 'v', 'e')
    target_dict["vp"] = vp
    return target_dict
def t_resumen_API(origin_dict=None):
    '''get the desired data'''
    target_dict = {}
    try:
        for k, v in RESUMEN_RENAME.iteritems():
            target_dict[v] = origin_dict['resumen'][k]
    except KeyError:
        log.error("Could not find required key %s in %s" % (k, origin_dict))
        raise Paso2015(__name__)

    # Calculate table percentage
    mp = get_percentage(target_dict, 'mi', 'mt')
    target_dict["mp"] = mp

    # Calculate voting percentage
    vp = get_percentage(target_dict, 'v', 'e')
    target_dict["vp"] = vp
    return target_dict
Пример #3
0
def get_results_by_count_section_question(sectionClass, question, date, requestedBrand):
	logging.debug('datastore.py : get_results_by_count_section_question() : sectionClass')
	query = sectionClass.gql('')
	
	results = list()
	for data in query:
		logging.debug(data)
		if hasattr(data, question):
			results.append(getattr(data, question))

	counted = utils.count_unsorted_list_items(results)
	percentage = utils.get_percentage(counted)

	return [counted,percentage]
Пример #4
0
    def principle_selection_rates(self):
        """ This is pretty much a direct port from V1. It's still a hot mess.
        This should probably get a refactor prior to launch. """

        I = innovations_models.Assets()
        mep_dict = I.get_mutually_exclusive_principles()

        popularity_contest = {}
        for principle in mep_dict.keys():
            tup = mep_dict[principle]

            all_options = []
            for l in tup:
                all_options.extend(l)

            sample_set = utils.mdb.settlements.find({
                "principles": {
                    "$in": all_options
                }
            }).count()
            popularity_contest[principle] = {
                "sample_size": sample_set,
                "options": []
            }

            for option_list in tup:
                total = utils.mdb.settlements.find({
                    "principles": {
                        "$in": option_list
                    }
                }).count()
                option_pretty_name = option_list[0]
                popularity_contest[principle]["options"].append(
                    option_pretty_name)
                popularity_contest[principle][option_pretty_name] = {
                    "total": total,
                    "percentage": int(utils.get_percentage(total, sample_set)),
                }
        return popularity_contest
Пример #5
0
Modes: 
        1. Play as the human being you are
        2. Sit idle while 2 robots play the game 10000 times,
           no output whill be shown bu you will receive
           stats at the end for how well the dealer did.
           Super fun...""")

user_choice = input("Select option 1 or 2: ")
while user_choice not in ['1', '2']:
    user_choice = input("Only option 1 or 2 allowed: ")

if user_choice == '1':
    clear_screen()
    game = OverUnder(Human())
    game.play()
else:
    game = OverUnder(Robot())
    game.play()
    winner_list = []
    total_rounds = 10000
    for _ in range(total_rounds):
        winner_list.append(game.play())
        game.reset()

    dealer_wins = winner_list.count("Dealer")
    print("Dealer wins: {0}".format(dealer_wins))
    print("Player wins: {0}".format(total_rounds - dealer_wins))
    print("\nDealer won {0} games from {1} with a {2:.2f}% win percentage!".
          format(dealer_wins, total_rounds,
                 get_percentage(total_rounds, dealer_wins)))
Пример #6
0
async def on_message(message):

    # TODO: Make a call for the server object here

    if message.author.id == client.user.id:
        return

    elif bot.initializing:
        # If people call while the objects are being handled, which might just not happen
        await client.send_message(message.channel, "Currently re-initializing, please try again later.")

    elif message.content.startswith("%team"):

        if message.content[6:] == "":
            # User didn't put in anything. Note that we might want to find a way to clarify the roles that do exist.
            await client.send_message(message.channel,
                                      "Usage is `%team [team name]`.")
            return

            # First things first, determine if it's a PM or not.
            # We need to get the server object that the member wants a role in. If not PM, it's ez.

        if not message.channel.is_private:  # Not a PM.

            server_obj = bot.servers[message.server.id]

            # Run checks to see if the message should go through or not

            whitelist = await server_obj.check_whitelist(message)
            pm_prefs = int(server_obj.pm_config)

            if pm_prefs == 1:  # Server owner has required roles be set by PMs.
                await client.send_message(message.channel, "The server moderators have required that roles be set by PM.")
                return
            elif whitelist is not None:  # The channel was not in the whitelist.
                await client.send_message(message.channel, whitelist)
                return

            member = message.author
            server = message.server

        else:  # Sent in a private message, so things might get tricky.
            servers_shared = []
            for server in client.servers:
                for member in server.members:
                    if member.id == message.author.id:
                        servers_shared.append(member.server)
            if len(servers_shared) == 0:
                await client.send_message(message.channel, "Something is wrong. We don't appear to share any servers.")
                return

            elif len(servers_shared) == 1:
                server = servers_shared[0]
            else:  # Time for issues
                base_message = "Oops, looks like I share more than one server with you. Which server would you like to set your role in? Reply with the digit of the server.\n"
                i = 1

                for svr in servers_shared:
                    base_message += "{0}: {1.name}\n".format(i, svr)
                    i += 1

                await client.send_message(message.channel, base_message)

                server_selection = await utils.get_message(client, message, i, base_message)
                if server_selection > i:
                    await client.send_message(message.channel, "That number was too large, try %team again.")
                    return
                else:
                    try:
                        server = servers_shared[(int(server_selection) - 1)]
                    except IndexError:
                        await client.send_message(message.channel, "That number was too large, try %team again.")
                        return
                    # TODO: Fix possibility of IndexError

            member = discord.utils.get(server.members, id=message.author.id)
            try:
                server_obj = bot.servers[server.id]
            except KeyError:  # Datafile is missing or something, it's not there.
                await client.send_message(message.channel, "The server datafile appears to be nonexistent for some reason.")
                return

        # Now, actually handle and process the roles.

        entered_team = message.content[6:]
        role = discord.utils.get(server.roles, name=entered_team)
        allowed_roles = server_obj.roles  # allowed_roles used to be team_list
        if server_obj.exclusive == "0":
            # Needs to be an exclusive if (not elif) because it has a chance at not returning anything
            for r in member.roles:
                if r.name in allowed_roles:
                    # If a role in the user's list of roles matches one of those we're checking
                    # or if the server has exclusive roles enabled
                    await client.send_message(message.channel,
                                              "You already have a team role. If you want to switch, message a moderator.")
                    return
        if (server_obj.check_role(entered_team)) & (role is None):
            # Role does not exist on the server, but is in the team_list, so the server just isn't configured properly.
            await client.send_message(message.channel,
                                      "The role you're trying to add existed at some point, but does not anymore, or has since been renamed.")
            # TODO: Consider using IDs in self.roles for this very reason

        elif (not server_obj.check_role(entered_team)) or (role is None):
            # If the role wasn't found by discord.utils.get() or is a role that we don't want to add, such as it not
            # being in the roles list:
            await client.send_message(message.channel, "Role isn't addable; " + server_obj.list_roles())

        elif role in member.roles:
            # If they already have the role
            await client.send_message(message.channel, "You already have this role. If you want to change, message a moderator.")

        else:
            try:
                await client.add_roles(member, role)
                await client.send_message(message.channel, "Successfully added role `{0}`.".format(role.name))
            except discord.Forbidden:
                # Something's wrong with permissions or the role hierarchy.
                await client.send_message(message.channel, "I don't have the `Manage Roles` permission, or the role you want me to assign is located above my own.\nRoles need to be located beneath my highest role in order for me to be able to assign them.")
            except discord.HTTPException:
                # Some random HTTP Exception, usually unpredictable.
                await client.send_message(message.channel, "Something went wrong, please try again.")

    # From here on out, don't let commands work in a PM.

    elif message.channel.is_private:
        return

    # Checks the Pokemon GO Wiki for information

    elif message.content.startswith("%wiki "):
        content = message.content.replace('%wiki ', '')
        page = wiki.pages[content].resolve_redirect()

        if not page.exists:
            await client.send_message(message.channel, "{} :warning: Couldn't find a page on **{}**".format(message.author.mention, content))
        else:
            await client.send_message(message.channel, "{} :candy: Found **{}**:\nhttp://{}/wiki/{}_".format(message.author.mention, page.name, wiki_base, page.name.replace(" ", "_")))

    # Bot info message, listing things such as the creator and link to github

    elif message.content.startswith("%botinfo"):
        await client.send_message(message.channel, bot.info_message)

    # List of commands

    elif message.content.startswith("%help") or message.content.startswith("%commands"):
        await client.send_message(message.channel, help_message)

    # Commands to (un)whitelist channels. Can only be run by someone with `Manage Server`.

    elif message.content.startswith("%whitelist"):
        if utils.check_perms(message):

            server_obj = bot.servers[message.server.id]

            if message.channel.id in server_obj.channel_whitelist:
                await client.send_message(message.channel, "This channel is already whitelisted.")
            else:

                with open("server_data/{0}.json".format(message.server.id), "r", encoding="utf-8") as tmp:
                    temp_data = json.load(tmp)
                    temp_data["team_ch_wl"].append(message.channel.id)
                with open("server_data/{0}.json".format(message.server.id), "w", encoding="utf-8") as tmp:
                    json.dump(temp_data, tmp)
                await client.send_message(message.channel, "Channel successfully whitelisted.")

    elif message.content.startswith("%unwhitelist"):
        if utils.check_perms(message):
            server_obj = bot.servers[message.server.id]
            if message.channel.id in server_obj.channel_whitelist:
                with open("server_data/{0}.json".format(message.server.id), "r", encoding="utf-8") as tmp:
                    temp_data = json.load(tmp)
                    temp_data["team_ch_wl"].remove(message.channel.id)
                with open("server_data/{0}.json".format(message.server.id), "w", encoding="utf-8") as tmp:
                    json.dump(temp_data, tmp)
                await client.send_message(message.channel, "Channel successfully removed from the whitelist.")
            else:
                await client.send_message(message.channel, "This channel is not whitelisted.")

    # Adjust server PM preferences

    elif message.content.startswith('%pm'):
        if not utils.check_perms(message):
            await client.send_message(message.channel,
                                      "This command is accessible by users with the `Manage Server` permission.")
            return
        else:
            flag = message.content.split()[1]
            flag_prefs = {
                "optional": "0",
                "required": "1",
            }
            if flag not in flag_prefs:
                await client.send_message(message.channel, "`%pm [required/optional]` (server owner only): Optional is default, allowing role setting in server and PMs; required disables setting roles in the server; disabled disables setting roles in PMs.")
                return
            server_obj = bot.servers[message.server.id]
            server_obj.pm_config = flag_prefs[flag]
            server_obj.export_to_file()
            await client.send_message(message.channel, "Server PM preferences now set to {0}.".format(flag))

    elif message.content.startswith("%role_config"):
        if not utils.check_perms(message):
            await client.send_message(message.channel,
                                      "This command is accessible by users with the `Manage Server` permission.")
            return
        else:
            flag = message.content.split()[1]
            flag_prefs = {
                "exclusive": "0",
                "multiple": "1",
            }
            if flag not in flag_prefs:
                await client.send_message(message.channel,
                                          "%role_\config [exclusive/multiple]__*: Setting to exclusive (default) only allows one role to be set per user. Setting to multiple allows users to set as many roles as they want.")
                return
            server_obj = bot.servers[message.server.id]
            server_obj.exclusive = flag_prefs[flag]
            server_obj.export_to_file()
            await client.send_message(message.channel, "Server role preferences now set to {0}.".format(flag))

    # Small command listing information on the server itself.

    elif message.content.startswith('%server_info'):
        members = (i for i in message.server.members)
        member_count = sum(1 for _ in members)
        await client.send_message(message.channel, server_info_message.format(message.server, member_count))

    elif message.content.startswith("%server_config"):
        server_obj = bot.servers[message.server.id]
        await client.send_message(message.channel, server_obj.generate_config_msg())

    # Generate an oauth link so people can add it to their own servers.

    elif message.content.startswith('%invite'):
        oauth_url = discord.utils.oauth_url(auth["client_id"], utils.required_perms)
        await client.send_message(message.channel, "Add me to a server by clicking this link: {}".format(oauth_url))

    # Create roles in server.

    elif message.content.startswith("%create_roles"):
        if utils.check_perms(message):

            # First, check to make sure the server doesn't already have the roles.

            server_obj = bot.servers[message.server.id]

            for role in message.server.roles:
                if role.name in server_obj.base_roles:
                    await client.send_message(
                        message.channel, "One or more default Pokemon GO team roles that I can use already exist on this server. Role creating aborted.")
                    return

            # That passed, create the roles using blank templates.

            # !!!
            # THESE ROLES HAVE TO BE AT LEAST BELOW THE ROLE THAT THE BOT HAS, OR ELSE IT CAN'T ASSIGN THEM DUE TO
            # ROLE HIERARCHY
            # Hopefully, creating the roles at position 0 and up should fix this.

            try:
                await client.send_message(message.channel, "Creating roles...")
                await client.create_role(message.server, name="Mystic", color=discord.Color.blue(),
                                         permissions=utils.team_perms, position=0)
                sleep(1)  # Rate limiting purposes
                await client.create_role(message.server, name="Instinct", color=discord.Color.gold(),
                                         permissions=utils.team_perms, position=1)
                sleep(1)
                await client.create_role(message.server, name="Valor", color=discord.Color.red(),
                                         permissions=utils.team_perms, position=2)
                await client.send_message(message.channel, "Blank roles successfully added.")
                server_obj.init_default_roles(message)
            except discord.Forbidden:
                await client.send_message(message.channel, "I don't have the `Manage Roles` permission.")
                return

    # Create a custom role for the server.

    elif message.content.startswith("%enable_role"):
        if utils.check_perms(message):
            server_obj = bot.get_server(server=message.server)
            role = server_obj.add_custom_role(message)
            if role is not None:
                await client.send_message(message.channel, "Role `{}` can now be added with %team.".format(role.name))
            else:
                await client.send_message(message.channel, "Couldn't find that role.")

    elif message.content.startswith("%disable_role"):
        if utils.check_perms(message):
            server_obj = bot.get_server(server=message.server)
            if server_obj.remove_custom_role(message):
                await client.send_message(message.channel, "Role `{}` now can *not* be added with %team.".format(message.content[14:]))
            else:
                await client.send_message(message.channel, "Role `{}` was already not assignable.".format(message.content[14:]))

    # Team stats in the server. Only for pokemon go servers

    elif message.content.startswith('%stats'):

        server_obj = bot.servers[message.server.id]
        if not server_obj.exists_default_roles():
            await client.send_message(message.channel, "This command requires Pokemon GO roles, which don't exist on this server.")

        role_stats = {
            "Mystic": 0,
            "Valor": 0,
            "Instinct": 0,
        }
        total = 0

        for member in message.server.members:
            for role in member.roles:
                if role.name in role_stats:
                    role_stats[role.name] += 1
                    total += 1

        msg = messages.stats_message.format(
            message.server.name,
            role_stats["Mystic"],
            role_stats["Valor"],
            role_stats["Instinct"],
            utils.get_percentage(role_stats["Mystic"], total),
            utils.get_percentage(role_stats["Valor"], total),
            utils.get_percentage(role_stats["Instinct"], total)
        )

        await client.send_message(message.channel, msg)

    # Evaluate an input. Only for bot owner.

    elif message.content.startswith('%eval'):
        if bot.sudo(message):
            await client.send_message(message.channel, eval(message.content[6:]))

    # Set bot status, or "game" it's currently playing.
    # A blank message removes the status

    elif message.content.startswith('%status'):
        if bot.sudo(message):
            if message.content[8:] != "":
                game_name = message.content[8:]
            else:
                game_name = None
            await client.change_status(game=discord.Game(name=game_name))

    # !!!!!!!!
    # SENDS A MESSAGE TO EVERY SERVER CONNECTED TO THE BOT. NOT AN ECHO COMMAND.
    # NOT TO BE TAKEN LIGHTLY, AND I RECOMMEND YOU DON'T USE @everyone IN THE MESSAGE UNLESS YOU WANT HATE MAIL

    elif message.content.startswith("%announce"):
        if bot.sudo(message):
            for server_id, server in bot.servers.items():
                default_channel = discord.utils.get(server.obj.channels, is_default=True)
                await client.send_message(default_channel, message.content[10:])
                sleep(0.5)  # To be nice on the api
Пример #7
0
def action_get_survey_by_date_and_brand(date, brand):
	
	memcacheKey = 'survey:results:'+str(date.isoformat())	
	memcacheResult = memcache.get(memcacheKey, namespace=brand)
	if memcacheResult is not None:
		logging.debug('Returning processed Survey results from MEMCACHE')
		return memcacheResult
	else:
		logging.debug('Returning processed Survey results from DATASTORE')
		surveys = datastore.get_surveys_by_date_and_brand(date, brand)	
		
		surveyProps = configparsers.loadPropertyFile('survey_'+brand)
	
		sections = dict()
		surveyResults = list()
		# Prepare an object with the Datastore data
		# for each survey

		"""
			[ST]TODO:
		 		Refactor all of this to use the db.query_descendants() method against the Survey model instance received
		 		This will catch pre-PolyModel Survey instances in the Datastore, and saves iterating over all Survey model instance
		 		properties looking for Survey Sections that are classes, and then getting their properties, etc, etc.

		 		Otherwise we end up collecting Survey model instances that have no connected Section model instances :(
		"""
		for survey in surveys:
			# for each section within the survey
			for surveyAttr in survey.properties():
				#logging.debug('actions.py : action_get_survey_by_date_and_brand() : surveyAttr')
				#logging.debug(surveyAttr)
				section = getattr(survey, surveyAttr)

				#logging.debug('actions.py : action_get_survey_by_date_and_brand() : section')
				#logging.debug(type(section))

				# [ST]TODO: Ugly patch for pre-PolyModel Surveys
				if type(section) is list and surveyAttr == '_class' and len(section) <= 1:
					logging.debug('We have a broken Razorfish Survey connection')
					child_sections = db.query_descendants(survey)
					for child in child_sections:
						logging.debug(child)
				else:
					logging.debug('We have found a Razorfish Survey')

				# If the Section Model has properties, and it exists in the Survey Properties ConfigParser file (e.g. is not the User model)...
				if section is not None and hasattr(section, 'properties') and surveyProps.has_section(section.kind()):
					# If we have not yet created a dict entry for this section, then do so
					
					if surveyAttr not in sections:
						sections[surveyAttr] = dict()
						sections[surveyAttr]['id'] = surveyAttr
						sections[surveyAttr]['created'] = survey.created
						sections[surveyAttr]['index'] = surveyProps.get(section.kind(), 'index')
						sections[surveyAttr]['name'] = surveyProps.get(section.kind(), 'name')
						sections[surveyAttr]['results'] = dict()
						surveyResults.append(sections[surveyAttr])

					# for question name and value in the section
					for question, prop in section.properties().items():
						if type(prop) == db.IntegerProperty:
							answer = getattr(section, question)
							# If we have not yet created a dict entry for this question in this section, then do so
							if question not in sections[surveyAttr]['results']:
								sections[surveyAttr]['results'][question] = dict()
								sections[surveyAttr]['results'][question]['id'] = question
								sections[surveyAttr]['results'][question]['name'] = prop.verbose_name
								sections[surveyAttr]['results'][question]['raw'] = list()
								sections[surveyAttr]['results'][question]['count'] = dict()
								sections[surveyAttr]['results'][question]['percentage'] = dict()
								sections[surveyAttr]['results'][question]['options_length'] = len(prop.choices)
								sections[surveyAttr]['results'][question]['type'] = 'multi'
							# Add the answer to the question list
							sections[surveyAttr]['results'][question]['raw'].append(answer)
						if type(prop) == db.TextProperty:
							answer = getattr(section, question)
							
							# If we have not yet created a dict entry for this question in this section, then do so
							if question not in sections[surveyAttr]['results']:
								sections[surveyAttr]['results'][question] = dict()
								sections[surveyAttr]['results'][question]['id'] = question
								sections[surveyAttr]['results'][question]['name'] = prop.verbose_name
								sections[surveyAttr]['results'][question]['answers'] = list()
								sections[surveyAttr]['results'][question]['type'] = 'single'
							
							# IF an answer exists, include this as a tuple with the User model object as the first argument and the answer Text value as the second argument
							if answer != '':	
								sections[surveyAttr]['results'][question]['answers'].append({'user':getattr(survey, 'user_id'), 'answer':answer, 'date':survey.created})
						
		for section, questionSet in sections.items():
			for question, data in questionSet['results'].items():
				# If we have a multiple choice question we need to process the results
				
				if data.has_key('raw') and type(data['raw']) is list:
					base = {}
					base[1]=0
					base[2]=0
					base[3]=0
					base[4]=0
					base[5]=0
					counted = utils.count_unsorted_list_items(data['raw'])				
					data['count'] = dict(base.items() + counted.items())
					sorted(data['count'], reverse=False)
					data['percentage'] = utils.get_percentage(data['count'])
		
		finalResult = sorted(surveyResults, key=itemgetter('index'), reverse=False)
		if len(finalResult) > 0:
			memcache.set(key=memcacheKey, value=finalResult, time=300, namespace=brand)
		return finalResult
Пример #8
0
def action_get_survey_sections_by_brand(brand):
	try:
		memcache_key = 'survey:sections:'+str(brand)	
		memcache_result = memcache.get(memcache_key, namespace=brand)
		if memcache_result is not None:
			logging.debug('action_get_survey_sections_by_brand() : Returning processed Survey Section results from MEMCACHE')
			return memcache_result
		else:
			logging.debug('action_get_survey_sections_by_brand() : Returning processed Survey Section results from DATASTORE')
			# Get the Surveys from the Datastore by Brand
			surveys = datastore.get_surveys_by_brand(brand)	
			# Load the Survey Properties, for Content iteration in the HTML Template
			surveyProps = configparsers.loadPropertyFile('survey_'+brand)

			# Create an empty dict for Survey Sections
			sections = dict()
			# Create an empty list for all section results
			section_results = list()
			# For each Survey in the Datastore Query result
			for survey in surveys:
				# Get the Survey descendats
				survey_descendants = db.query_descendants(survey)
				
				for descendant in survey_descendants:
					# Set the Sections dict key to be the Kind (lowercase)
					_id = descendant.kind().lower()
					# Create a Section dict
					if _id not in sections:
						sections[_id] = dict(
							id=_id,
							created=survey.created,
							index=surveyProps.get(descendant.kind(), 'index'),
							name=surveyProps.get(descendant.kind(), 'name'),
							results = dict()
						)
						section_results.append(sections[_id])

					# for question name and value in the descendant section
					for question, prop in descendant.properties().items():
						# If the Property is of type Integer (Long returned from Datastore, actually)
						if type(prop) == db.IntegerProperty:
							answer = getattr(descendant, question)
							
							# If we have not yet created a dict entry for this question in this section, then do so
							if question not in sections[_id]['results']:
								sections[_id]['results'][question] = dict(
									id=question,
									name=prop.verbose_name,
									raw=list(),
									count=dict(),
									percentage=dict(),
									options_length=len(prop.choices),
									type='multi'
								)

							# Add the answer to the question list
							sections[_id]['results'][question]['raw'].append(answer)
							
						# If the Property is of type Text:
						if type(prop) == db.TextProperty:
							answer = getattr(descendant, question)
							
							# If we have not yet created a dict entry for this question in this section, then do so
							if question not in sections[_id]['results']:
								sections[_id]['results'][question] = dict(
									id=question,
									name=prop.verbose_name,
									answers=list(),
									type='single'
								)
							
							# If an answer exists, include this as a tuple with the User model object as the first argument and the answer Text value as the second argument
							if answer != '':	
								sections[_id]['results'][question]['answers'].append({
								'user':getattr(survey, 'user_id'),
								'answer':answer,
								'date':survey.created
							})

				
			# Once we have iterated through all resuts, we need further processing.
			# This calculates the percentages of answers for multiple choice questions
			for section, questionSet in sections.items():
				for question, data in questionSet['results'].items():
					# If we have a multiple choice question we need to process the results
					#logging.debug(question)
					#logging.debug(data)
					if data.has_key('raw') and type(data['raw']) is list:
						base = {}
						if brand == 'razorfish':
							base[0]=0
							base[1]=0
							base[2]=0
							base[3]=0
							base[4]=0
							base[5]=0
						elif brand == 'mcdonalds':
							base[0]=0
							base[1]=0
							base[2]=0
							base[3]=0
							base[4]=0
							
						counted = utils.count_unsorted_list_items(data['raw'])
						#logging.debug('counted')
						#logging.debug(counted)
						data['count'] = dict(base.items() + counted.items())
						sorted(data['count'], reverse=False)
						data['percentage'] = utils.get_percentage(data['count'])
			
			# Finally, we sort our Section Results list, using the index of the section as the sort key
			section_results = sorted(section_results, key=itemgetter('index'), reverse=False)
			
			# Add the result to Memcache, to expire in 5 minutes
			if len(section_results) > 0:
				memcache_stored = memcache.set(memcache_key, value=section_results, time=360, namespace=brand)
			return section_results
	except Exception, e:
		logging.error(type(e))
		logging.error(e)
		raise e
Пример #9
0
async def on_message(message):

    # TODO: Make a call for the server object here

    if message.author.id == client.user.id:
        return

    elif bot.initializing:
        # If people call while the objects are being handled, which might just not happen
        await client.send_message(
            message.channel, "Currently initializing, please try again later.")

    elif message.content.startswith("%team"):

        if message.content[6:] == "":
            # User didn't put in anything. Note that we might want to find a way to clarify the roles that do exist.
            await client.send_message(message.channel,
                                      "Usage is `%team [team name]`.")
            return

        # First things first, determine if it's a PM or not.
        # We need to get the server object that the member wants a role in. If not PM, it's ez.

        if not message.channel.is_private:  # Not a PM.

            server_obj = bot.servers[message.server.id]

            # Run checks to see if the message should go through or not

            whitelist_message = await server_obj.check_whitelist(message)
            pm_prefs = int(server_obj.pm_config)

            if pm_prefs == 1:  # Server owner has required roles be set by PMs.
                await client.send_message(
                    message.channel,
                    "The server moderators have required that roles be set by PM."
                )
                return
            elif whitelist_message is not None:  # The channel was not in the whitelist.
                await client.send_message(message.channel, whitelist_message)
                return

            member = message.author
            server = message.server

        else:  # Sent in a private message, so things might get tricky.

            server = await bot.get_server_from_pm(message)

            member = discord.utils.get(server.members, id=message.author.id)
            try:
                server_obj = bot.servers[server.id]
            except KeyError:  # Datafile is missing or something, it's not there.
                await client.send_message(
                    message.channel,
                    "The server datafile appears to be nonexistent for some reason."
                )
                return

        # Now, actually handle and process the roles.

        entered_team = message.content[6:]
        role = discord.utils.get(server.roles, name=entered_team)
        allowed_roles = server_obj.roles  # allowed_roles used to be team_list
        if server_obj.exclusive == "0":
            # Needs to be an exclusive if (not elif) because it has a chance at not returning anything
            for r in member.roles:
                if r.name in allowed_roles:
                    # If a role in the user's list of roles matches one of those we're checking
                    # or if the server has exclusive roles enabled
                    await client.send_message(
                        message.channel,
                        "You already have a team role. If you want to switch, message a moderator."
                    )
                    return
        if (server_obj.check_role(entered_team)) & (role is None):
            # Role does not exist on the server, but is in the team_list, so the server just isn't configured properly.
            await client.send_message(
                message.channel,
                "The role you're trying to add existed at some point, but does not anymore, or has since been renamed."
            )
            # TODO: Consider using IDs in self.roles for this very reason

        elif (not server_obj.check_role(entered_team)) or (role is None):
            # If the role wasn't found by discord.utils.get() or is a role that we don't want to add, such as it not
            # being in the roles list:
            await client.send_message(
                message.channel,
                "Role isn't addable; " + server_obj.list_roles())

        elif role in member.roles:
            # If they already have the role
            await client.send_message(
                message.channel,
                "You already have this role. If you want to change, message a moderator."
            )

        else:
            try:
                await client.add_roles(member, role)
                await client.send_message(
                    message.channel,
                    "Successfully added role `{0}`.".format(role.name))
            except discord.Forbidden:
                # Something's wrong with permissions or the role hierarchy.
                await client.send_message(
                    message.channel,
                    "I don't have the `Manage Roles` permission, or the role you want me to assign is located above my own.\nRoles need to be located beneath my highest role in order for me to be able to assign them."
                )
            except discord.HTTPException:
                # Some random HTTP Exception, usually unpredictable.
                await client.send_message(
                    message.channel, "Something went wrong, please try again.")

    elif message.content.startswith("%leaveteam"):
        if message.content[6:] == "":
            # User didn't put in anything. Note that we might want to find a way to clarify the roles that do exist.
            await client.send_message(message.channel,
                                      "Usage is `%leaveteam [team name]`.")
            return
        if not message.channel.is_private:
            server_obj = bot.servers[message.server.id]

            # Run checks to see if the message should go through or not

            whitelist_message = await server_obj.check_whitelist(message)
            pm_prefs = int(server_obj.pm_config)

            if pm_prefs == 1:  # Server owner has required roles be set by PMs.
                await client.send_message(
                    message.channel,
                    "The server moderators have required that roles be managed by PM."
                )
                return
            elif whitelist_message is not None:  # The channel was not in the whitelist.
                await client.send_message(message.channel, whitelist_message)
                return

            member = message.author
            server = message.server

        else:
            server = await bot.get_server_from_pm(message)
            if server is None:
                return
            else:
                member = server.get_member(message.author.id)
                server_obj = bot.servers[server.id]

        entered_team = message.content[11:]
        role = discord.utils.get(server.roles, name=entered_team)

        if server_obj.user_ctrl == "0":
            await client.send_message(
                message.channel,
                "Removing roles with %leaveteam is disabled in this server.")
            return
        elif role is None:
            await client.send_message(message.channel,
                                      "That role does not exist.")
            return
        elif (role.name not in server_obj.roles) & (role in member.roles):
            await client.send_message(
                message.channel,
                "Cannot remove that role, you can only remove roles with %leaveteam that I can add with %team."
            )
        elif role not in member.roles:
            await client.send_message(message.channel,
                                      "You don't have that role.")
        else:
            await client.remove_roles(member, role)
            await client.send_message(
                message.channel,
                "Role {0.name} removed successfully.".format(role))

    # From here on out, don't let commands work in a PM.

    elif message.channel.is_private:
        return

    # Checks the Pokemon GO Wiki for information

    elif message.content.startswith("%wiki "):
        content = message.content.replace('%wiki ', '')
        page = wiki.pages[content].resolve_redirect()

        if not page.exists:
            await client.send_message(
                message.channel,
                "{} :warning: Couldn't find a page on **{}**".format(
                    message.author.mention, content))
        else:
            await client.send_message(
                message.channel,
                "{} :candy: Found **{}**:\nhttp://{}/wiki/{}_".format(
                    message.author.mention, page.name, wiki_base,
                    page.name.replace(" ", "_")))

    # Bot info message, listing things such as the creator and link to github

    elif message.content.startswith("%botinfo"):
        await client.send_message(message.channel, bot.info_message)

    # List of commands

    elif message.content.startswith("%help") or message.content.startswith(
            "%commands"):
        await client.send_message(message.channel, help_message)

    # Commands to (un)whitelist channels. Can only be run by someone with `Manage Server`.

    elif message.content.startswith('%whitelist'):
        if utils.check_perms(message):

            server_obj = bot.servers[message.server.id]

            if message.channel.id in server_obj.channel_whitelist:
                await client.send_message(
                    message.channel, "This channel is already whitelisted.")
            else:
                server_obj.add_to_whitelist(message)
                await client.send_message(message.channel,
                                          "Channel successfully whitelisted.")

    elif message.content.startswith("%unwhitelist"):
        if utils.check_perms(message):
            server_obj = bot.servers[message.server.id]
            if message.channel.id not in server_obj.channel_whitelist:
                await client.send_message(
                    message.channel,
                    "This channel is already not whitelisted.")
            else:
                server_obj.remove_from_whitelist(message)
                await client.send_message(
                    message.channel,
                    "Channel successfully removed from the whitelist.")

    # Adjust server PM preferences

    elif message.content.startswith('%pm'):
        if not utils.check_perms(message):
            await client.send_message(
                message.channel,
                "This command is accessible by users with the `Manage Server` permission."
            )
            return
        else:
            flag = message.content.split()[1]
            if flag not in utils.flags["pm"]:
                await client.send_message(
                    message.channel,
                    "`%pm [required/optional]` (server owner only): Optional is default, allowing role setting in server and PMs; required disables setting roles in the server; disabled disables setting roles in PMs."
                )
                return
            server_obj = bot.servers[message.server.id]
            server_obj.pm_config = utils.flags["pm"][flag]
            server_obj.export_to_file()
            await client.send_message(
                message.channel,
                "Server PM preferences now set to {0}.".format(flag))

    elif message.content.startswith("%role_config"):
        if not utils.check_perms(message):
            await client.send_message(
                message.channel,
                "This command is only accessible by users with the `Manage Server` permission."
            )
            return
        else:
            flag = message.content.split()[1]
            if flag not in utils.flags["role"]:
                await client.send_message(
                    message.channel,
                    "%role_\config [exclusive/multiple]: Setting to exclusive (default) only allows one role to be set per user. Setting to multiple allows users to set as many roles as they want."
                )
                return
            server_obj = bot.servers[message.server.id]
            server_obj.exclusive = utils.flags["role"][flag]
            server_obj.export_to_file()
            await client.send_message(
                message.channel,
                "Server role preferences now set to {0}.".format(flag))

    elif message.content.startswith(
            "%leave_config"):  # Consider changing this name
        if not utils.check_perms(message):
            await client.send_message(
                message.channel,
                "This command is only accessible by users with the `Manage Server` permission."
            )
        else:
            flag = message.content.split()[1]
            if flag not in utils.flags["ctrl"]:
                await client.send_message(
                    message.channel,
                    "%leave_config [enabled/disabled]: Setting to disabled (default) prevents users from removing roles with %leaveteam. Enabled lets users use %leaveteam to remove a %team-assignable role."
                )
                return
            server_obj = bot.servers[message.server.id]
            server_obj.user_ctrl = utils.flags["ctrl"][flag]
            server_obj.export_to_file()
            await client.send_message(message.channel,
                                      "`%leaveteam` is now {0}.".format(flag))

    # Small command listing information on the server itself.

    elif message.content.startswith('%server_info'):
        members = (i for i in message.server.members)
        member_count = sum(1 for _ in members)
        await client.send_message(
            message.channel,
            server_info_message.format(message.server, member_count))

    elif message.content.startswith("%server_config"):
        server_obj = bot.servers[message.server.id]
        await client.send_message(message.channel,
                                  server_obj.generate_config_msg())

    # Generate an oauth link so people can add it to their own servers.

    elif message.content.startswith('%invite'):
        oauth_url = discord.utils.oauth_url(auth["client_id"],
                                            utils.required_perms)
        await client.send_message(
            message.channel,
            "Add me to a server by clicking this link: {}".format(oauth_url))

    # Create roles in server.

    elif message.content.startswith("%create_roles"):
        if utils.check_perms(message):

            # First, check to make sure the server doesn't already have the roles.

            server_obj = bot.servers[message.server.id]

            for role in message.server.roles:
                if role.name in server_obj.base_roles:
                    await client.send_message(
                        message.channel,
                        "One or more default Pokemon GO team roles that I can use already exist on this server. Role creating aborted."
                    )
                    return

            # That passed, create the roles using blank templates.

            # !!!
            # THESE ROLES HAVE TO BE AT LEAST BELOW THE ROLE THAT THE BOT HAS, OR ELSE IT CAN'T ASSIGN THEM DUE TO
            # ROLE HIERARCHY
            # Hopefully, creating the roles at position 0 and up should fix this.

            try:
                await client.send_message(message.channel, "Creating roles...")
                await client.create_role(message.server,
                                         name="Mystic",
                                         color=discord.Color.blue(),
                                         permissions=utils.team_perms,
                                         position=0)
                sleep(1)  # Rate limiting purposes
                await client.create_role(message.server,
                                         name="Instinct",
                                         color=discord.Color.gold(),
                                         permissions=utils.team_perms,
                                         position=1)
                sleep(1)
                await client.create_role(message.server,
                                         name="Valor",
                                         color=discord.Color.red(),
                                         permissions=utils.team_perms,
                                         position=2)
                await client.send_message(message.channel,
                                          "Blank roles successfully added.")
                server_obj.init_default_roles(message)
                log.info("Created default roles in {0.name}".format(
                    message.server))
            except discord.Forbidden:
                await client.send_message(
                    message.channel,
                    "I don't have the `Manage Roles` permission.")
                return

    # Create a custom role for the server.

    elif message.content.startswith("%enable_role"):
        if utils.check_perms(message):
            server_obj = bot.get_server(server=message.server)
            role = server_obj.add_custom_role(message)
            if role is not None:
                await client.send_message(
                    message.channel,
                    "Role `{}` can now be added with %team.".format(role.name))
            else:
                await client.send_message(message.channel,
                                          "Couldn't find that role.")

    elif message.content.startswith("%disable_role"):
        if utils.check_perms(message):
            server_obj = bot.get_server(server=message.server)
            if server_obj.remove_custom_role(message):
                await client.send_message(
                    message.channel,
                    "Role `{}` now can *not* be added with %team.".format(
                        message.content[14:]))
            else:
                await client.send_message(
                    message.channel,
                    "Role `{}` was already not assignable.".format(
                        message.content[14:]))

    # Team stats in the server. Only for pokemon go servers

    elif message.content.startswith('%stats'):

        server_obj = bot.servers[message.server.id]
        if not server_obj.exists_default_roles():
            await client.send_message(
                message.channel,
                "This command requires Pokemon GO roles, which don't exist on this server."
            )

        role_stats = {
            "Mystic": 0,
            "Valor": 0,
            "Instinct": 0,
        }
        total = 0

        for member in message.server.members:
            for role in member.roles:
                if role.name in role_stats:
                    role_stats[role.name] += 1
                    total += 1

        msg = messages.stats_message.format(
            message.server.name, role_stats["Mystic"], role_stats["Valor"],
            role_stats["Instinct"],
            utils.get_percentage(role_stats["Mystic"], total),
            utils.get_percentage(role_stats["Valor"], total),
            utils.get_percentage(role_stats["Instinct"], total))

        await client.send_message(message.channel, msg)

    # Evaluate an input. Only for bot owner.

    elif message.content.startswith('%eval'):
        if bot.sudo(message):
            eval_result = eval(message.content[6:])
            log.info("Eval executed; Command: {}; Result: {}".format(
                message.content, eval_result))
            await client.send_message(message.channel, eval_result)

    # Set bot status, or "game" it's currently playing.
    # A blank message removes the status

    elif message.content.startswith('%status'):
        if bot.sudo(message):
            if message.content[8:] != "":
                game_name = message.content[8:]
            else:
                game_name = None
            await client.change_status(game=discord.Game(name=game_name))

    # !!!!!!!!
    # SENDS A MESSAGE TO EVERY SERVER CONNECTED TO THE BOT. NOT AN ECHO COMMAND.
    # NOT TO BE TAKEN LIGHTLY, AND I RECOMMEND YOU DON'T USE @everyone IN THE MESSAGE UNLESS YOU WANT HATE MAIL

    elif message.content.startswith("%announce"):
        if bot.sudo(message):
            log.warning("%announce was used!")
            for server_id, server in bot.servers.items():
                default_channel = discord.utils.get(server.obj.channels,
                                                    is_default=True)
                await client.send_message(default_channel,
                                          message.content[10:])
                sleep(0.5)  # To be nice on the api