Пример #1
0
def get_root_rwr_servers_status():
    """Check the status of the RWR root servers."""
    from models import RwrRootServer, RwrRootServerStatus, Variable
    from disco.api.client import APIClient as DiscordAPIClient
    from flask import url_for
    from rwrs import db
    import rwr.constants
    import helpers
    import arrow

    click.echo('Pinging servers')

    hosts_to_ping = [server['host'] for group in rwr.constants.ROOT_RWR_SERVERS for server in group['servers']]
    rwr_root_servers = RwrRootServer.query.filter(RwrRootServer.host.in_(hosts_to_ping)).all()
    rwr_root_servers_by_host = {rwr_root_server.host: rwr_root_server for rwr_root_server in rwr_root_servers}
    servers_down_count_then = sum([1 for rwr_root_server in rwr_root_servers if rwr_root_server.status == RwrRootServerStatus.DOWN])
    servers_down_count_now = 0

    for host in hosts_to_ping:
        click.echo(host, nl=False)

        is_server_up = helpers.ping(host)

        if is_server_up:
            click.secho(' Up', fg='green')
        else:
            click.secho(' Down', fg='red')

            servers_down_count_now += 1

        if host not in rwr_root_servers_by_host:
            rwr_root_server = RwrRootServer()
            rwr_root_server.host = host
        else:
            rwr_root_server = rwr_root_servers_by_host[host]

        rwr_root_server.status = RwrRootServerStatus.UP if is_server_up else RwrRootServerStatus.DOWN

        db.session.add(rwr_root_server)

    Variable.set_value('last_root_rwr_servers_check', arrow.utcnow().floor('minute'))

    click.echo('Persisting to database')

    db.session.commit()

    message = None

    if servers_down_count_then == 0 and servers_down_count_now > 0:
        with app.app_context():
            message = ':warning: Online multiplayer is having issues right now. Are the devs aware? If not, poke **pasik** or **JackMayol**. Some details here: {}'.format(url_for('online_multiplayer_status', _external=True))
    elif servers_down_count_then > 0 and servers_down_count_now == 0:
        message = ':white_check_mark: Outage update: online multiplayer is back up and running!'

    if message:
        click.echo('Sending Discord bot message')

        discord_api_client = DiscordAPIClient(app.config['DISCORD_BOT_TOKEN'])
        discord_api_client.channels_messages_create(app.config['DISCORD_BOT_CHANNEL_ID'], message)

    click.secho('Done', fg='green')
Пример #2
0
class DiscordInterface:
    TOKEN = None  # FIXME a long token from Discord

    # the next two should be big decimal numbers; in Discord, you can right
    # click and Copy ID to get them
    GUILD = 'FIXME'
    HINT_CHANNEL = 'FIXME'

    # You also need to enable the "Server Members Intent" under the "Privileged
    # Gateway Intents" section of the "Bot" page of your application from the
    # Discord Developer Portal. Or you can comment out the code that
    # initializes `self.avatars` below.

    def __init__(self):
        self.client = None
        self.avatars = None
        if self.TOKEN and not settings.IS_TEST:
            self.client = APIClient(self.TOKEN)

    def get_avatars(self):
        if self.avatars is None:
            self.avatars = {}
            if self.client is not None:
                members = self.client.guilds_members_list(self.GUILD).values()
                for member in members:
                    self.avatars[member.user.username] = member.user.avatar_url
                for member in members:
                    self.avatars[member.name] = member.user.avatar_url
        return self.avatars

    # If you get an error code 50001 when trying to create a message, even
    # though you're sure your bot has all the permissions, it might be because
    # you need to "connect to and identify with a gateway at least once"??
    # https://discord.com/developers/docs/resources/channel#create-message

    # I spent like four hours trying to find weird asynchronous ways to do this
    # right before each time I send a message, but it seems maybe you actually
    # just need to do this once and your bot can create messages forever?
    # disco.py's Client (not APIClient) wraps an APIClient and a GatewayClient,
    # the latter of which does this. So I believe you can fix this by running a
    # script like the following *once* on your local machine (it will, as
    # advertised, run forever; just kill it after a few seconds)?

    # from gevent import monkey
    # monkey.patch_all()
    # from disco.client import Client, ClientConfig
    # Client(ClientConfig({'token': TOKEN})).run_forever()

    def update_hint(self, hint):
        HintsConsumer.send_to_all(
            json.dumps({
                'id':
                hint.id,
                'content':
                render_to_string('hint_list_entry.html', {
                    'hint': hint,
                    'now': timezone.localtime()
                })
            }))
        embed = MessageEmbed()
        embed.author.url = hint.full_url()
        if hint.claimed_datetime:
            embed.color = 0xdddddd
            embed.timestamp = hint.claimed_datetime.isoformat()
            embed.author.name = 'Claimed by {}'.format(hint.claimer)
            if hint.claimer in self.get_avatars():
                embed.author.icon_url = self.get_avatars()[hint.claimer]
            debug = 'claimed by {}'.format(hint.claimer)
        else:
            embed.color = 0xff00ff
            embed.author.name = 'U N C L A I M E D'
            claim_url = hint.full_url(claim=True)
            embed.title = 'Claim: ' + claim_url
            embed.url = claim_url
            debug = 'unclaimed'

        if self.client is None:
            message = hint.long_discord_message()
            logger.info('Hint, {}: {}\n{}'.format(debug, hint, message))
            logger.info('Embed: {}'.format(embed.to_dict()))
        elif hint.discord_id:
            try:
                self.client.channels_messages_modify(self.HINT_CHANNEL,
                                                     hint.discord_id,
                                                     embed=embed)
            except Exception:
                dispatch_general_alert(
                    'Discord API failure: modify\n{}'.format(
                        traceback.format_exc()))
        else:
            message = hint.long_discord_message()
            try:
                discord_id = self.client.channels_messages_create(
                    self.HINT_CHANNEL, message, embed=embed).id
            except Exception:
                dispatch_general_alert(
                    'Discord API failure: create\n{}'.format(
                        traceback.format_exc()))
                return
            hint.discord_id = discord_id
            hint.save(update_fields=('discord_id', ))

    def clear_hint(self, hint):
        HintsConsumer.send_to_all(json.dumps({'id': hint.id}))
        if self.client is None:
            logger.info('Hint done: {}'.format(hint))
        elif hint.discord_id:
            # try:
            #     self.client.channels_messages_delete(
            #         self.HINT_CHANNEL, hint.discord_id)
            # except Exception:
            #     dispatch_general_alert('Discord API failure: delete\n{}'.format(
            #         traceback.format_exc()))
            # hint.discord_id = ''
            # hint.save(update_fields=('discord_id',))

            # what DPPH did instead of deleting messages:
            # (nb. I tried to make these colors color-blind friendly)

            embed = MessageEmbed()
            if hint.status == 'ANS':
                embed.color = 0xaaffaa
            elif hint.status == 'REF':
                embed.color = 0xcc6600
            # nothing for obsolete

            embed.author.name = '{} by {}'.format(hint.status, hint.claimer)
            embed.author.url = hint.full_url()
            embed.description = hint.response[:250]
            if hint.claimer in self.get_avatars():
                embed.author.icon_url = self.get_avatars()[hint.claimer]
            debug = 'claimed by {}'.format(hint.claimer)
            try:
                self.client.channels_messages_modify(
                    self.HINT_CHANNEL,
                    hint.discord_id,
                    content=hint.short_discord_message(),
                    embed=embed)
            except Exception:
                dispatch_general_alert(
                    'Discord API failure: modify\n{}'.format(
                        traceback.format_exc()))