Ejemplo n.º 1
0
def __return_message(body:dict, returnmessage:dict) -> None:
    """Gets original message and return message and sends to proper channels"""
    if 'channel' in returnmessage:
        DiscordFramework.SendDiscordMessage(returnmessage['channel'],body['guildchannelid'])
    if 'author' in returnmessage:
        DiscordFramework.send_discord_private_message(returnmessage['author'],body['authorid'])
    if 'target' in returnmessage and 'targetdiscordid' in returnmessage:
        DiscordFramework.send_discord_private_message(returnmessage['target'],returnmessage['targetdiscordid'])
    return None
 def __post_contest_results(channelid: str,
                            statrandom: bool = True) -> None:
     """Posts Contest results, Needs Channel ID and if results should be randomized"""
     results = CosmosFramework.QueryItems(
         'SELECT TOP 3 * FROM c WHERE IS_DEFINED(c.contest.currentscore) AND c.contest.currentscore != 0 ORDER BY c.contest.currentscore DESC',
         'users')
     if not bool(results):  ##No users with score greater then 1
         return None
     config = CommonFramework.RetrieveConfigOptions('discord')
     place = 1
     if statrandom is True:
         message = 'Please note that score is slightly randomized when displayed and may lead to appear that lower place is winning, true score is used when determining place.'
         DiscordFramework.SendDiscordMessage(message=message,
                                             channelid=channelid)
     DiscordFramework.SendDiscordMessage('Current Contest results:',
                                         channelid)
     for result in results:
         userdata = DiscordFramework.get_user_guild_info(
             result['discordid'], config['serverid'])
         if result['contest']['currentscore'] == 0:
             place += 1
             continue
         if 'code' in userdata and userdata['code'] == 10007:
             CosmosFramework.delete_user_from_cosmos_by_discordid(
                 result['discordid'])
             continue
         if userdata['nick'] is None:
             nick = userdata['user']['username']
         else:
             nick = userdata['nick']
         if statrandom is True:
             score = int(result['contest']['currentscore'] *
                         (random.randint(100, 110) / 100))
         else:
             score = int(result['contest']['currentscore'])
         discordmessage = "{0} is currently in #{1} place with score: {2}".format(
             nick, place, score)
         DiscordFramework.SendDiscordMessage(discordmessage, channelid)
         place += 1
def citadel(body: dict) -> dict:
    returnmessage = {}
    citadelroleid = 636372439261249566
    citadelchannelid = 636374196355858452
    result = __query_cosmos_for_info_by_discordid(str(body['authorid']))
    discordserverid = CommonFramework.RetrieveConfigOptions('discord')
    discordserverid = discordserverid['serverid']
    if result is None or 'wgid' not in result:
        returnmessage[
            'author'] = "You have not registered with the bot, this is mandatory. Please visit <#507725600073449482> to register or please complete registration."
        return returnmessage
    wgid = [int(result['wgid'])]
    claninfo = wotframework.GetPlayersClanInfo(wgid)
    claninfo = claninfo[0]
    if claninfo[1] is None:
        returnmessage[
            'author'] = "You are not a member of clan, citadel access is denied"
        return returnmessage
    elif claninfo[2] not in [
            'commander', 'executive_officer', 'combat_officer',
            'personnel_officer'
    ]:
        returnmessage[
            'author'] = "Citadel access is restricted to Clan officers only"
        return returnmessage
    results = CosmosFramework.QueryItems(
        'SELECT * FROM c WHERE c.wgid = {0}'.format(claninfo[1]), 'citadel')
    if bool(results):  #Meaning their clan ID is in citadel container
        result = results[0]
        if result['citadel'] is True:
            DiscordFramework.AddUserRole(citadelroleid, body['authorid'],
                                         discordserverid)
            returnmessage['author'] = "Access granted"
            DiscordFramework.SendDiscordMessage(
                "{0} from {1} has joined the citadel.".format(
                    body['authordisplayname'], result['name']),
                citadelchannelid)
            result = __query_cosmos_for_info_by_discordid(str(
                body['authorid']))
            result['citadel'] = True
            CosmosFramework.ReplaceItem(result['_self'], result)
        else:
            returnmessage[
                'author'] = 'Citadel access has been revoked because: {0}. If you believe access should be granted, please see moderator.'.format(
                    result['excludereason'])
    else:
        returnmessage[
            'author'] = 'Citadel access is restricted to clans who rank on Global Map ELO. If you believe access should be granted, please see moderator.'
    return returnmessage
 def __start_new_contest(channelid: str) -> None:
     """Starts new contest by removing old contest results"""
     results = CosmosFramework.QueryItems(
         'SELECT * FROM c WHERE IS_DEFINED(c.contest)')
     for result in results:
         del result['contest']
         CosmosFramework.ReplaceItem(result['_self'], result)
     results = CosmosFramework.QueryItems(
         'SELECT * FROM c WHERE c.start = true', 'contest')
     results = results[0]
     results['start'] = False
     results['active'] = True
     CosmosFramework.ReplaceItem(results['_self'], results)
     days = int((results['endtime'] - results['starttime']) / 86400)
     startmessage = 'Reddit World of Tanks contest has started! It will run for {0} days.'.format(
         days)
     startmessage += '\nContest is measurement of World of Tanks single stat in random battles from now until end of contest.'
     startmessage += '\nStat is chosen randomly and not available to any staff member.'
     startmessage += '\nContest is open to anyone with who has register with bot or registers with bot while contest is running. RDDT clan membership is not required.'
     DiscordFramework.SendDiscordMessage(message=startmessage,
                                         channelid=channelid)
 def __end_current_contest(channelid: str) -> None:
     contestresults = CosmosFramework.QueryItems(
         'SELECT * FROM c WHERE c.active = true', 'contest')
     contestresults = contestresults[0]
     winnerresults = CosmosFramework.QueryItems(
         'SELECT TOP 10 * FROM c WHERE IS_DEFINED(c.contest.currentscore) AND c.contest.currentscore != 0 ORDER BY c.contest.currentscore DESC',
         'users')
     message = 'Contest is over, congratulations to the winners. Stat being tracked this contest was: {0}. Rewards will be issued shortly.'.format(
         contestresults['stat'])
     DiscordFramework.SendDiscordMessage(message=message,
                                         channelid=channelid)
     placedict = {}
     place = 1
     for result in winnerresults:
         placedict[str(place)] = {
             result['wgid']: result['contest']['currentscore']
         }
         place += 1
     contestresults['winners'] = dict(placedict)
     contestresults['active'] = False
     CosmosFramework.ReplaceItem(contestresults['_self'], contestresults)
def run_citadel_check():
    def __get_citadel_results() -> dict:
        primary = {}
        secondary = {}
        results = CosmosFramework.QueryItems(
            'SELECT * FROM c WHERE c.citadel = true', 'citadel')
        for result in results:
            secondary['tag'] = result.get('tag')
            secondary['name'] = result.get('name')
            secondary['citadel'] = result.get('citadel')
            secondary['override'] = result.get('citadeloverride')
            secondary['excludereason'] = result.get('excludereason')
            secondary['excludetime'] = result.get('excludetime')
            primary[result['wgid']] = dict(secondary)
            secondary.clear()
        return primary

    def __exclude_clan_from_citadel(clanid):
        citadelroleid = 636372439261249566
        discordserverid = CommonFramework.RetrieveConfigOptions('discord')
        discordserverid = discordserverid['serverid']
        results = CosmosFramework.QueryItems(
            'SELECT * FROM c WHERE c.clan = {0} AND c.citadel = true'.format(
                clanid), 'users')
        for result in results:
            status_code = DiscordFramework.RemoveUserRole(
                citadelroleid, result['discordid'], discordserverid)
            if status_code == 204:
                del result['citadel']
                CosmosFramework.ReplaceItem(result['_self'], result)
            else:
                DiscordFramework.send_discord_private_message(
                    "Citadel checker is having issues", 113304266269003776)
                raise "Clan removal failed"

    def __exclude_wgid_from_citadel(wgid: int) -> None:
        """Removes WGID from citadel"""
        citadelroleid = 636372439261249566
        discordserverid = CommonFramework.RetrieveConfigOptions('discord')
        discordserverid = discordserverid['serverid']
        result = CosmosFramework.QueryItems(
            'SELECT * FROM c WHERE c.discordid="{0}"'.format(wgid), 'users')
        if bool(result):
            result = result[0]
            DiscordFramework.RemoveUserRole(citadelroleid, result['discordid'],
                                            discordserverid)
            DiscordFramework.send_discord_private_message(
                'You have been removed from RDDT citadel due clan/rank changes',
                result['discordid'])
            del result['citadel']
            CosmosFramework.ReplaceItem(result['_self'], result)

    citadelchannelid = 636374196355858452  #Actual citadel channel
    wgapi = CommonFramework.RetrieveConfigOptions('wargaming')
    results = __get_citadel_results()
    apiresults = CommonFramework.get_json_data(
        "https://api.worldoftanks.com/wot/clanratings/top/?application_id={0}&rank_field=gm_elo_rating&limit=200"
        .format(wgapi['apitoken']))
    wgidlist = []
    #Do clan checks ##TODO put this in it's own def block
    for apiresult in apiresults[
            'data']:  #Get information about clans from Wargaming API
        wgidlist.append(apiresult['clan_id'])
        if apiresult['clan_id'] not in results:
            item = {}
            item['wgid'] = apiresult['clan_id']
            item['name'] = apiresult['clan_name']
            item['tag'] = apiresult['clan_tag']
            item['citadel'] = True
            CosmosFramework.InsertItem(item, 'citadel')
        elif apiresult['clan_id'] in results and (
                results[apiresult['clan_id']]['tag'] != apiresult['clan_tag']
                or results[apiresult['clan_id']]['name'] !=
                apiresult['clan_name']):
            #Checks the database and Wargaming API match around clan tag and name, if not, it updates it
            updateitem = CosmosFramework.QueryItems(
                'SELECT * FROM c WHERE c.wgid={0}'.format(
                    apiresult['clan_id']), 'citadel')
            updateitem = updateitem[0]
            updateitem['name'] = apiresult['clan_name']
            updateitem['tag'] = apiresult['clan_tag']
            CosmosFramework.ReplaceItem(updateitem['_self'], updateitem)
    clanlist = list(results.keys())
    removeclans = list(set(clanlist) -
                       set(wgidlist))  #List of clans to be removed
    for removeclan in removeclans:
        claninfo = CosmosFramework.QueryItems(
            'SELECT * FROM c WHERE c.wgid={0}'.format(removeclan), 'citadel')
        claninfo = claninfo[0]
        if 'override' in claninfo and claninfo['override'] is True:
            continue  #Overrides are not removed
        elif 'excludetime' not in claninfo:  #Step 2, put in removal time
            claninfo['excludetime'] = int(time.time(
            )) + 604700  #This is 6 days, 23 hours and ~58 minutes
            message = "WARNING: Clan {0} ({1}) will be removed within 7 days due to lack of clan rating.".format(
                claninfo['name'], claninfo['tag'])
            DiscordFramework.SendDiscordMessage(message, citadelchannelid)
            CosmosFramework.ReplaceItem(claninfo['_self'], claninfo)
        elif claninfo['excludetime'] < int(
                time.time()
        ):  #when their time is hit, mark them no longer allowed in citadel with reason and remove all clan members
            __exclude_clan_from_citadel(removeclan)
            message = "Clan {0} ({1}) has been removed from citadel.".format(
                claninfo['name'], claninfo['tag'])
            DiscordFramework.SendDiscordMessage(message, citadelchannelid)
            claninfo['citadel'] = False
            claninfo['excludetime'] = None
            claninfo['excludereason'] = 'Excluded due to lack of ranking'
            CosmosFramework.ReplaceItem(claninfo['_self'], claninfo)
    #Do user checks ##TODO Put this in it's own def block
    userresults = CosmosFramework.QueryItems(
        'SELECT c.wgid FROM c WHERE c.citadel = true', 'users')
    wgidtocheck = []
    for userresult in userresults:
        wgidtocheck.append(userresult['wgid'])
        if len(wgidtocheck) >= 99:
            apiresults = wotframework.GetPlayersClanInfo(wgidtocheck)
            for apiresult in apiresults:
                if apiresult[1] is None or apiresult[2] not in [
                        'commander', 'executive_officer', 'combat_officer',
                        'personnel_officer'
                ]:
                    __exclude_wgid_from_citadel(apiresult[0])
            wgidtocheck.clear()
Ejemplo n.º 7
0
                    elif discordmessage[0] == '!ping':
                        returnmessage = {'channel':'pong!'}
                        __return_message(body,returnmessage)
                        
                    elif discordmessage[0] == '!citadel':
                        returnmessage = DiscordBotFramework.citadel(body)
                        __return_message(body,returnmessage)

                    elif discordmessage[0] == '!info':
                        MessageHandler(message=body).info()

                    elif discordmessage[0] == '!startcontest':
                        returnmessage = DiscordBotFramework.startcontest(body)
                        __return_message(body,returnmessage)

                    elif "http" in body['message'].lower():
                        returnmessage = DiscordBotFramework.handle_links(body)
                        if returnmessage:
                            __return_message(body,returnmessage)
                        
                elif body['type'] == 'reactionadd':
                    pass #Future actions
                elif body['type'] == 'reactionremove':
                    pass #Future actions
                sbmessage.complete()
                
        except Exception as e:
            DiscordFramework.SendDiscordMessage(str(e),'491800495980150789')
            sbmessage.abandon() #If message fails, abandon it so it can be reprocessed quickly
            pass
from Modules.twitch import TwitchAPI
import Modules.CommonFramework as CommonFramework
import Modules.DiscordFramework as DiscordFramework

i = 0
channelid = '414607006821777440'
options = CommonFramework.RetrieveConfigOptions("twitch")
twitch = TwitchAPI(options['clientid'], options['clientsecret'])
users = ['worldoftanksna']
active = {}
for user in users:
    active[user] = False
while i < 1008:
    for user in users:
        currentstreams = twitch.get_streams_by_userlogin(userlogin=user)
        if len(currentstreams['data']) > 0 and active[user] is False:
            embed = {"title": f"Twitch Streamer {user} is active"}
            embed['type'] = 'rich'
            title = currentstreams['data'][0]['title']
            embed[
                'description'] = f"Twitch Stream {user} is currently active and streaming {title}"
            embed['url'] = f"https://www.twitch.tv/{user}"
            DiscordFramework.SendDiscordMessage(message=None,
                                                channelid=channelid,
                                                embed=embed)
            active[user] = True
        elif len(currentstreams['data']) == 0 and active[user] is True:
            active[user] = False
    i += 1
    time.sleep(600)