• Страница 1 из 1
  • 1
Модератор форума: staford11  
Форум » Программы и прочее » Программы WoW » Скрипт для поощрения игроков за голоса MMOTOP на Groovy
Скрипт для поощрения игроков за голоса MMOTOP на Groovy
Адонай
Скаут
Для ManGOS-like серверов.

Для запуска не нужна настройка баз. Скрипт практически самодостаточен.
Необходимы только доступ по SOAP-протоколу и аккаунт с правами, с которого будут посылаться письма.
Измените только ссылки на статистику ммотопа и ссылку своего SOAP-клиента.

Ссылка в скрипте дана в целях ознакомления с форматом.

Код

#!/usr/bin/env groovy

/**
     * Данная программа является свободным программным обеспечением.     
     * Вы вправе распространять ее и/или модифицировать в соответствии с условиями версии 3,
     * либо, по вашему выбору, с условиями более поздней версии Стандартной Общественной Лицензии GNU,     
     * опубликованной Free Software Foundation. Я распространяю данную программу в надежде на то,     
     * что она будет вам полезной, однако не предоставляю на нее никаких гарантий,     
     * в том числе гарантии товарного состояния при продаже и пригодности для использования в конкретных целях.     
     * Для получения более подробной информации ознакомьтесь со Стандартной Общественной Лицензией GNU.
     *     
     * Author: Adonai Wintermute
     */

@Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.0') // soap packets sending

import groovy.transform.Canonical
import wslite.http.auth.HTTPBasicAuthorization
import wslite.soap.SOAPClient
import wslite.soap.SOAPFaultException

def final address = 'http://mmotop.ru/votes/9c9ab3e4fd43a9ae9c23d720e979793267421acb.txt?6ed2d73efc98a17a3f6110584ffc54f5' // <------- замените своей ссылкой на статистику

@Canonical
class MmotopEntry {
        int id
        String date
        String ip
        String characterName
        int votes

        /**
         * Construct MMOTOP entry from statistics line
         * @param statLine line of mmotop text statistics file
         */
        MmotopEntry(String statLine) {
            def tokens = statLine.split('\t')
            id = tokens[0] as int
            date = tokens[1]
            ip = tokens[2]
            characterName = tokens[3]
            votes = tokens[4] as int
        }

        @Override
        String toString() {
            return "$id\t$date\t$ip\t$characterName\t$votes"
        }
}

def void persist(File to, List<MmotopEntry> entries, long lastModified) {
        if (entries) {
            if(!to.exists())
                to.createNewFile()

            to.write entries.collect { it.toString() }.join('\n') // turn entries to lines back
            to.lastModified = lastModified
        }
}

/**
     * Resolves the difference in votes and applies it to the players
     * @param oldList
     * @param modifiedList
     */
def void sendMails(List<MmotopEntry> oldList, List<MmotopEntry> modifiedList) {
        for (entry in modifiedList) {
            int votesToProcess = entry.votes
            String name = entry.characterName

            def oldEntry = oldList.find { it.id == entry.id } // try to find old entry
            if(oldEntry) // we have an old entry for this one - should subtract the old votes
                votesToProcess -= oldEntry.votes

            println "Sending $votesToProcess tokens to $name"
            def client = new SOAPClient('http://91.121.36.198:7878/') // <------- замените своей ссылкой SOAP
            try {
                client.authorization = new HTTPBasicAuthorization('mail', 'godblessus') // <------- замените своими логином/паролем
                def response = client.send(SOAPAction: 'urn:TC') {
                    body {
                        executeCommand(xmlns:'urn:TC') {
                            command ".send items $name \"Награда за голосование\" \"Спасибо за участие!\" " +
                       "49426:${votesToProcess * 2}"
                        }
                    }
                }

                if(response.httpResponse.statusCode == 200)
                    println 'Successfully sent!'
            } catch (SOAPFaultException sfe) {
                println sfe.message
                println sfe.httpResponse.statusCode
                println sfe.fault.detail.text() // sfe.fault is a GPathResult of Envelope/Body/Fault
            }
        }
}

long lastModified = 0
def oldLines = new ArrayList<MmotopEntry>()

// get cached values if we have them
File cached = new File('cached-mmotop.txt')
if(cached.exists()) {
        println 'Cached script file found, reusing...'
        lastModified = cached.lastModified()
        oldLines = cached.readLines().collect {it -> new MmotopEntry(it)} // turn lines to entries
}

while (true) {
        try {
            HttpURLConnection request = new URL(address).openConnection() as HttpURLConnection
            request.setIfModifiedSince lastModified
            request.connect()

            if (request.responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { // not modified
                println 'File not modified - continuing...'
                request.disconnect()
                continue
            }

            // modified - read changes (new entry lines, new modification date)
            def newLines = request.inputStream.readLines().collect {it -> new MmotopEntry(it)} // turn lines to entries
            def newModified = request.lastModified
            request.disconnect() // not needed anymore

            // new line count is less than old - file rotated
            if(oldLines.size() > newLines.size()) {
                println "New month started, ${new Date()}"
                oldLines.clear() // should process all the entries
            }

            // find all modified lines
            def modifiedLines = newLines.findAll { !oldLines.contains(it) }
            if(!modifiedLines) { // no changes actually
                println 'No any changes detected...'
                lastModified = newModified
                continue
            }

            // applying changes!

            sendMails oldLines, modifiedLines
            println 'All modified processing done!'

            // persist cached file
            persist cached, newLines, newModified

            // update runtime entries
            oldLines = newLines
            lastModified = newModified
        } catch (IOException e) {
            println "Connection error! $e.message"
        } catch (Exception e) {
            println "System error! $e.message"
            System.exit(-1)
        } finally {
            sleep 10000 // 10 seconds
        }
}

Runtime.addShutdownHook {
        persist cached, oldLines, lastModified
}


Помните, лицензия скрипта GPL. Это означает, что если вы модифицируете или улучшите его функциональность, вы обязаны будете поделиться исходниками модифицированных версий с пользователями.
Сообщение # 1 отредактировано Адонай - Суббота, 25.07.2015, 12:11
Форум » Программы и прочее » Программы WoW » Скрипт для поощрения игроков за голоса MMOTOP на Groovy
  • Страница 1 из 1
  • 1
Поиск: