コード例 #1
0
async def cmd_register(ctx):

	bot = ctx.bot
	args = ctx.args
	author = ctx.author
	config =  ctx.config

	alt = ctx.alt = bot.options.parse_alt(args)
	lang = bot.options.parse_lang(ctx, args)
	language = Player.get_language_info(lang)

	discord_ids = bot.options.parse_mentions(ctx, args)
	ally_codes = bot.options.parse_ally_codes(args)

	if not ally_codes and len(discord_ids) < 2:
		try:
			p = Player.objects.get(discord_id=author.id, alt=alt)
			if p.ally_code not in ally_codes:
				ally_codes.append(p.ally_code)

		except Player.DoesNotExist:
			pass

	if not ally_codes:
		return bot.errors.no_ally_code_specified(ctx)

	if args:
		return bot.errors.unknown_parameters(args)

	if len(ally_codes) == len(discord_ids) + 1 and author.id not in discord_ids:
		discord_ids.append(author.id)

	return await register_users(ctx, discord_ids, ally_codes)
コード例 #2
0
def get_available_languages(request):

    author = request.author
    config = request.config

    langs = [
        ' - **`%s`**: %s' % (lang_code, lang_name)
        for language, lang_code, lang_flag, lang_name in Player.LANGS
    ]
    langs.insert(0, 'Here is the list of supported languages:')

    try:
        player = Player.objects.get(discord_id=author.id)
        language = Player.get_language_info(player.language)
        langs.insert(
            0,
            'Your current language is **%s** %s' % (language[3], language[2]))
        langs.insert(1, config['separator'])

    except Player.DoesNotExist:
        pass

    return [{
        'title': 'Available Languages',
        'description': '%s' % '\n'.join(langs),
    }]
コード例 #3
0
def parse_opts_mentions(request):

    discord_ids = []
    args = request.args
    args_cpy = list(args)
    author = request.author
    for arg in args_cpy:

        discord_id = None

        m = re.search(r'^<@!?([0-9]+)>$', arg)
        if m:
            args.remove(arg)
            discord_ids.append(int(m.group(1)))

        elif arg.lower() in ['me', '@me']:
            args.remove(arg)
            discord_ids.append(author.id)

        else:
            p = Player.get_player_by_nick(arg)
            if p:
                args.remove(arg)
                discord_ids.append(p.discord_id)

    return list(set(discord_ids))
コード例 #4
0
    def parse_mentions(self, ctx, args):

        discord_ids = []
        author = ctx.author
        args_cpy = list(args)
        for arg in args_cpy:

            discord_id = None

            m = re.search(r'^<@!?([0-9]+)>$', arg)
            if m:
                args.remove(arg)
                discord_id = int(m.group(1))
                if discord_id not in discord_ids:
                    discord_ids.append(discord_id)

            elif arg.lower() in ['me', '@me']:
                args.remove(arg)
                if author.id not in discord_ids:
                    discord_ids.append(author.id)

            elif arg.startswith('@'):
                p = Player.get_player_by_nick(arg[1:])
                if p:
                    args.remove(arg)
                    if p.discord_id not in discord_ids:
                        discord_ids.append(p.discord_id)

        return discord_ids
コード例 #5
0
async def cmd_register(request):

    args = request.args
    author = request.author
    config = request.config

    lang = parse_opts_lang(request)
    language = Player.get_language_info(lang)

    discord_ids = parse_opts_mentions(request)
    ally_codes = parse_opts_ally_codes(request)

    if not ally_codes and len(discord_ids) < 2:
        try:
            p = Player.objects.get(discord_id=author.id)
            if p.ally_code not in ally_codes:
                ally_codes.append(p.ally_code)

        except Player.DoesNotExist:
            pass

    if not ally_codes:
        return error_no_ally_code_specified(config, author)

    if args:
        return error_unknown_parameters(args)

    if len(ally_codes
           ) == len(discord_ids) + 1 and author.id not in discord_ids:
        discord_ids.append(author.id)

    return await register_users(request, discord_ids, ally_codes)
コード例 #6
0
def cmd_me(ctx):

    bot = ctx.bot
    args = ctx.args
    author = ctx.author
    config = ctx.config

    ctx.alt = bot.options.parse_alt(args)
    selected_players, error = bot.options.parse_players(ctx, args)
    if error:
        return error

    if args:
        return bot.errors.unknown_parameters(args)

    lines = []
    for player in selected_players:

        author_str = 'Ally code of **<@%s>**' % player.discord_id
        ally_code_full_str = '%s is **`%s`**.' % (
            author_str, Player.format_ally_code(player.ally_code))
        lines.append(ally_code_full_str)
        lines.append('')

        language = Player.get_language_info(player.language)
        lines.append('Your language is set to **%s** %s.' %
                     (language[3], language[2]))
        lines.append('Please type **`%slanguage`** to change your language.' %
                     config['prefix'])
        lines.append('')

        timezone = player.timezone or 'Europe/London'
        lines.append('Your timezone is set to **%s**.' % timezone)
        lines.append('Please type **`%stimezone`** to change your timezone.' %
                     config['prefix'])
        lines.append('')

    lines_str = '\n'.join(lines)
    return [{
        'title': '',
        'description': 'Hello <@%s>,\n\n%s\n' % (author.id, lines_str),
    }]
コード例 #7
0
    def parse_language(self, args):

        args_cpy = list(args)
        for arg in args_cpy:

            argl = arg.lower()
            language = Player.get_language_info(argl)
            if language is not None:
                args.remove(arg)
                return language

        return None
コード例 #8
0
def parse_opts_language(request):

    args = request.args
    args_cpy = list(args)
    for arg in args_cpy:

        argl = arg.lower()
        language = Player.get_language_info(argl)
        if language is not None:
            args.remove(arg)
            return language

    return None
コード例 #9
0
async def register_users(ctx, discord_ids, ally_codes):

	alt = ctx.alt
	bot = ctx.bot
	args = ctx.args
	author = ctx.author
	config = ctx.config

	if len(discord_ids) != len(ally_codes):
		return bot.errors.register_mismatch(ctx, discord_ids, ally_codes)

	lang = bot.options.parse_lang(ctx, args)
	language = Player.get_language_info(lang)

	players = await bot.client.players(ally_codes=ally_codes)
	if not players:
		return bot.errors.invalid_ally_codes(ally_codes)

	players = { x['allyCode']: x for x in players }

	lines = []
	for discord_id, ally_code in zip(discord_ids, ally_codes):

		jplayer = players[ally_code]

		db_player, created = Player.objects.get_or_create(discord_id=discord_id, alt=alt)

		author_str = 'Ally code of **<@%s>**' % discord_id
		ally_code_str = Player.format_ally_code(ally_code)
		ally_code_full_str = '%s is **`%s`**.' % (author_str, ally_code_str)
		if db_player.ally_code and db_player.ally_code != ally_code:
			ally_code_full_str = '%s has changed from **`%s`** to **`%s`**.' % (author_str, db_player.get_ally_code(), ally_code_str)
		db_player.ally_code   = ally_code
		db_player.timezone    = 'Europe/London'
		db_player.player_id   = jplayer['id']
		db_player.player_name = jplayer['name']
		await fill_user_info(config, bot, db_player)

		db_player.save()

		registered_str = 'Player **%s** already registered!' % db_player.player_name
		if created:
			registered_str = 'Registration successful for **%s**!' % db_player.player_name

		lines.append(registered_str)
		lines.append(ally_code_full_str)
		lines.append('')

		#language = Player.get_language_info(db_player.language)
		#lines.append('Your language is set to **%s** %s.' % (language[3], language[2]))
		#lines.append('Please type **`%slanguage`** to change your language.' % config['prefix'])
		#lines.append('')

		#timezone = db_player.timezone or 'Europe/London'
		#lines.append('Your timezone is set to **%s**.' % timezone)
		#lines.append('Please type **`%stimezone`** to change your timezone.' % config['prefix'])
		#lines.append('')

	lines_str = '\n'.join(lines)

	return [{
		'title': 'Register',
		'description': 'Hello <@%s>,\n\n%s' % (author.id, lines_str),
	}]
コード例 #10
0
def parse_opts_players(request,
                       min_allies=1,
                       max_allies=-1,
                       expected_allies=1,
                       exclude_author=False,
                       language='eng_us'):

    args = request.args
    author = request.author
    channel = request.channel
    config = request.config

    discord_ids = parse_opts_mentions(request)
    ally_codes = parse_opts_ally_codes(request)

    players = []
    unregistered = []
    for discord_id in discord_ids:

        try:
            p = Player.objects.get(discord_id=discord_id)

            if p not in players:
                players.append(p)

            if p.ally_code not in ally_codes:
                ally_codes.append(p.ally_code)

        except Player.DoesNotExist:
            unregistered.append(discord_id)

    if unregistered:
        return None, error_ally_codes_not_registered(config, unregistered)

    if exclude_author is False:

        if (not discord_ids and not ally_codes) or len(
                ally_codes) < min_allies or len(ally_codes) < expected_allies:
            try:
                p = Player.objects.get(discord_id=author.id)

                if p not in players:
                    players.insert(0, p)

                if p.ally_code not in ally_codes:
                    ally_codes.insert(0, p.ally_code)

            except Player.DoesNotExist:
                pass

    elif not ally_codes:
        return [], None

    if not ally_codes:
        return None, error_no_ally_code_specified(config, author)

    if len(ally_codes) < min_allies:
        return None, error_not_enough_ally_codes_specified(
            ally_codes, min_allies)

    if len(ally_codes) > max_allies and max_allies != -1:
        return None, error_too_many_ally_codes_specified(
            ally_codes, max_allies)

    for ally_code in ally_codes:

        queryset = Player.objects.filter(ally_code=ally_code)
        if queryset.count() > 0:
            player = queryset.first()
        else:
            player = Player(ally_code=ally_code)

        if player not in players:
            players.append(player)

        if player.banned:
            guild = channel.guild
            guild_id = hasattr(guild, 'id') and guild.id or None
            origin = '[%s <@%s>][#%s <@%s>][%s <@%s>]' % (
                guild, guild_id, channel, channel.id, author, author.id)
            logger = logging.getLogger('opts')
            logger.log(
                logging.INFO,
                '%s: Detected usage of blacklisted allycode: %s' %
                (origin, player.ally_code))

    return players, None
コード例 #11
0
async def register_users(request, discord_ids, ally_codes):

    author = request.author
    config = request.config

    if len(discord_ids) != len(ally_codes):
        return error_register_mismatch(config, author, discord_ids, ally_codes)

    lang = parse_opts_lang(request)
    language = Player.get_language_info(lang)

    players = await fetch_players(config, {
        'allycodes': ally_codes,
        'project': {
            'name': 1,
            'allyCode': 1,
        },
    })

    lines = []
    for discord_id, ally_code in zip(discord_ids, ally_codes):

        db_player, created = Player.objects.get_or_create(
            discord_id=discord_id)

        author_str = 'Ally code of **<@%s>**' % discord_id
        ally_code_str = Player.format_ally_code(ally_code)
        ally_code_full_str = '%s is **`%s`**.' % (author_str, ally_code_str)
        if db_player.ally_code and db_player.ally_code != ally_code:
            ally_code_full_str = '%s has changed from **`%s`** to **`%s`**.' % (
                author_str, db_player.get_ally_code(), ally_code_str)
        db_player.ally_code = ally_code
        db_player.game_nick = players[ally_code]['name']
        db_player.timezone = 'Europe/London'
        await fill_user_info(config, db_player)

        db_player.save()

        registered_str = 'Player **%s** already registered!' % db_player.game_nick
        if created:
            registered_str = 'Registration successful for **%s**!' % db_player.game_nick

        lines.append(registered_str)
        lines.append(ally_code_full_str)
        lines.append('')

        #language = Player.get_language_info(db_player.language)
        #lines.append('Your language is set to **%s** %s.' % (language[3], language[2]))
        #lines.append('Please type **`%slanguage`** to change your language.' % config['prefix'])
        #lines.append('')

        #timezone = db_player.timezone or 'Europe/London'
        #lines.append('Your timezone is set to **%s**.' % timezone)
        #lines.append('Please type **`%stimezone`** to change your timezone.' % config['prefix'])
        #lines.append('')

    lines_str = '\n'.join(lines)

    return [{
        'title': 'Register',
        'description': 'Hello <@%s>,\n\n%s' % (author.id, lines_str),
    }]
コード例 #12
0
	async def on_message_handler(self, request):

		from swgohhelp import SwgohHelpException

		author = request.author
		channel = request.channel
		command = request.command
		config = request.config

		if Player.is_banned(author):
			msgs = error_user_banned(config, author)
			for msg in msgs:
				embeds = new_embeds(msg)
				for embed in embeds:
					status, error = await self.sendmsg(channel, message='', embed=embed)
					if not status:
						print('Could not print to channel %s: %s (XX)' % (channel, error))
			return

		if channel is None:
			return

		try:
			for cmd in COMMANDS:
				if command in cmd['aliases']:

					if inspect.iscoroutinefunction(cmd['function']):
						msgs = await cmd['function'](request)
					else:
						msgs = cmd['function'](request)

					for msg in msgs:
						embeds = new_embeds(msg)
						for embed in embeds:
							status, error = await self.sendmsg(channel, message='', embed=embed)
							if not status:
								print('Could not print to channel %s: %s (2)' % (channel, error))
					break

			else:
				if 'reply-unknown' in config and config['reply-unknown'] is True:

					embeds = new_embeds({
						'title': 'Error: Unknown Command',
						'color': 'red',
						'description': 'No such command: `%s`.\nPlease type `%shelp` to get information about available commands.' % (command, config['prefix']),
					})

					for embed in embeds:
						status, error = await self.sendmsg(channel, message='', embed=embed)
						if not status:
							print('Could not print to channel %s: %s (3)' % (channel, error))

		except SwgohHelpException as swgohError:

			data = swgohError.data
			embeds = new_embeds({
				'title': swgohError.title,
				'color': 'red',
				'description': '**%s:** %s' % (data['error'], data['error_description']),
			})

			for embed in embeds:
				status, error = await self.sendmsg(channel, message='', embed=embed)
				if not status:
					print('Could not print to channel %s: %s (3.5)' % (channel, error))

		except Exception as err:
			print("Error in on_message_handler...")
			print(traceback.format_exc())

			if 'crash' in config and config['crash']:
				status, error = await self.sendmsg(channel, message=config['crash'])
				if not status:
					print('Could not print to channel %s: %s (4)' % (channel, error))

			embeds = new_embeds({
				'title': 'Unexpected Error',
				'color': 'red',
				'description': str(err),
			})

			for embed in embeds:
				status, error = await self.sendmsg(channel, message='', embed=embed)
				if not status:
					print('Could not print to channel %s: %s (5)' % (channel, error))
コード例 #13
0
	async def on_message_handler(self, request):

		author = request.author
		channel = request.channel
		command = request.command
		config = request.config
		message = request.message

		if Player.is_banned(author):
			msgs = self.errors.user_banned(request)
			for msg in msgs:
				await self.embed.send(channel, msg)

			return

		if channel is None:
			await self.process_commands(message)
			return

		try:
			for cmd in COMMANDS:
				if command in cmd['aliases']:

					if cmd['need_api'] and request.from_user:
						await self.add_reaction(message, EMOJI_HOURGLASS)

					if inspect.iscoroutinefunction(cmd['function']):
						msgs = await cmd['function'](request)
					else:
						msgs = cmd['function'](request)

					if cmd['need_api'] and request.from_user:
						await self.add_reaction(message, EMOJI_THUMBSUP)

					for msg in msgs:
						await self.embed.send(channel, msg)

					break

			else:
				if 'reply-unknown' in config and config['reply-unknown'] is True:

					await self.embed.send(channel, {
						'title': 'Error: Unknown Command',
						'color': 'red',
						'description': 'No such command: `%s`.\nPlease type `%shelp` to get information about available commands.' % (command, config['prefix']),
					})


				await self.process_commands(message)

		except Exception as err:
			print('Error in on_message_handler...')
			print(traceback.format_exc())

			if 'crash' in config and config['crash']:
				status, error = await self.sendmsg(channel, message=config['crash'])
				if not status:
					self.logger.error('Could not print to channel %s: %s (4)' % (channel, error))

			await self.embed.send(channel, {
				'title': 'Unexpected Error',
				'color': 'red',
				'description': str(err),
			})