예제 #1
0
 def send_msg(self, to_uin, msg=u'hello world'):
     '''
     url = 'http://d.web2.qq.com/channel/send_buddy_msg2'
     data_poll = {
         'r': '{"to":'+str(to_uin)+',"content":"[\"'+msg+u'\",[\"font\",{\"name\":\"宋体\",\"size\":10,\"style\":[0,0,0],\"color\":\"000000\"}]]","face":147,"clientid":'+self.clientid+',"msg_id":'+str(self.msgid)+',"psessionid":"'+self.psessionid+'"}'
     }
     req = urllib2.Request(url, data=urllib.urlencode(data_poll))
     req.add_header(
         'Referer', 'http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2')
     urllib2.urlopen(req)
     '''
     print 'sendto:', to_uin, '-', msg
     self.msgid += 1
     msg = u"[\"" + msg + u"\",[\"font\",{\"name\":\"" + u'宋体' + u"\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]"
     url = 'http://d.web2.qq.com/channel/send_buddy_msg2'
     a = {
         'to': to_uin,
         'face': 180,
         'content': msg,
         'msg_id': self.msgid,
         'clientid': self.clientid,
         'psessionid': self.psessionid
     }
     array = {'r': json_encode.JSONEncoder().encode(a)}
     req = urllib2.Request(url, data=urllib.urlencode(array))
     req.add_header(
         'Referer',
         'http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2')
     urllib2.urlopen(req)
예제 #2
0
    def __send_group_message(self, gid, msg):
        '''
            @url:http://d.web2.qq.com/channel/send_qun_msg2
            r:{"group_uin":1132101900,"content":"[\"哈哈哈,测试\",\"\\n【提示:此用户正在使用WebQQ:http://webqq.qq.com/】\",[\"font\",           {\"name\":\"宋体\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]","msg_id":31330002,"clientid":"76133590",
            "psessionid":"a"}
            clientid:76133590
            psessionid:a

            Referer:http://d.web2.qq.com/proxy.html?v=20110331002&callback=2

            {"retcode":0,"result":"ok"}
        '''
        self.__send_num += 1
        msg = "[\"" + msg + "\",[\"font\",{\"name\":\"宋体\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]"
        self.__headers.update({
            'Referer':
            'http://d.web2.qq.com/proxy.html?v=20110331002&callback=2'
        })
        url = 'http://d.web2.qq.com/channel/send_qun_msg2'
        a = {
            'group_uin': gid,
            'content': msg,
            'msg_id': self.__send_num,
            'clientid': self.__clientid,
            'psessionid': self.__psessionid
        }
        array = {
            'r': json_encode.JSONEncoder().encode(a),
            'clientid': self.__clientid,
            'psessionid': self.__psessionid
        }
        str = self.__request(url, 'POST', array)
        print(str)
        pass
예제 #3
0
 def __request_post(self):
     '''
         http://d.web2.qq.com/channel/login2
         r:{"status":"online","ptwebqq":"95b148b95af9be7677757b3a629e3904f52f153d0b714c527f81f8d9e385867a","passwd_sig":"",
         "clientid":"21628014","psessionid":null}
         clientid:21628014
         psessionid:null
     '''
     self.__headers.update({
         'Referer':
         'http://d.web2.qq.com/proxy.html?v=20110331002&callback=2'
     })
     a = {
         'status': 'online',
         'ptwebqq': self.__getcookies('ptwebqq'),
         'passwd_sig': '',
         'clientid': self.__clientid,
         'psessionid': 'null'
     }
     array = {
         'r': json_encode.JSONEncoder().encode(a),
         'clientid': self.__clientid,
         'psessionid': 'null'
     }
     url = 'http://d.web2.qq.com/channel/login2'
     str = self.__request(url, 'POST', array)
     str = json_decode.JSONDecoder().decode(str)
     self.__psessionid = str['result']['psessionid']
     self.__vfwebqq = str['result']['vfwebqq']
     self.__get_friend_info2()
     self.__get_user_friends2()
     self.__get_group_name_list_mask2()
     self.__poll2_()
     self.__get_msg_tip_()
     pass
예제 #4
0
def _BuildPackageEverythingInternal(package: Mod.Package) -> None:
    baseFileExists = os.path.exists(package.SourceBaseFilePath)  # type: bool
    loosePathExists = os.path.exists(package.SourceLoosePath)  # type: bool

    packageManifest = dict(
    )  # type: typing.Dict[str, typing.Union[float, typing.Dict[str, float]]]

    if baseFileExists:
        packageManifest["Base"] = os.path.getmtime(package.SourceBaseFilePath)
    else:
        packageManifest["Base"] = -1

    packageManifest["Loose"] = dict()

    for sourceDirectoryRoot, sourceDirectoryNames, sourceFileNames in os.walk(
            package.SourceLoosePath
    ):  # type: str, typing.List[str], typing.List[str]
        for sourceFileName in sourceFileNames:  # type: str
            sourceFilePath = os.path.join(sourceDirectoryRoot,
                                          sourceFileName)  # type: str
            relativeSourceFilePath = os.path.relpath(
                sourceFilePath, package.SourceLoosePath)  # type: str

            packageManifest["Loose"][
                relativeSourceFilePath] = os.path.getmtime(sourceFilePath)

    addingFilePaths = list()  # type: typing.List[str]

    if loosePathExists:
        for sourceDirectoryRoot, sourceDirectoryNames, sourceFileNames in os.walk(
                package.SourceLoosePath
        ):  # type: str, typing.List[str], typing.List[str]
            for sourceFileName in sourceFileNames:  # type: str
                # noinspection SpellCheckingInspection
                if os.path.splitext(
                        sourceFileName)[1].lower() == ".sourceinfo":
                    continue

                sourceFilePath = os.path.join(sourceDirectoryRoot,
                                              sourceFileName)  # type: str

                if os.path.isfile(sourceFilePath):
                    addingFilePaths.append(sourceFilePath)

    if baseFileExists:
        Package.BuildPackage(package.BuildFilePath,
                             baseFilePath=package.SourceBaseFilePath,
                             addingFilePaths=addingFilePaths)
    else:
        Package.BuildPackage(package.BuildFilePath,
                             addingFilePaths=addingFilePaths)

    with open(package.BuildManifestFilePath, "w+") as packageManifestFile:
        packageManifestFile.write(
            encoder.JSONEncoder(indent="\t").encode(packageManifest))
예제 #5
0
    def add_callback_button(self, title: str = "", payload=None):
        if payload is None:
            payload = {}

        self.add_button_to_list({
            'action': {
                'type': "callback",
                'title': title,
                'payload': encoder.JSONEncoder().encode(payload),
            }
        })
예제 #6
0
    def add_vk_pay_button(self, payload=None, pay_hash: str = ""):
        if payload is None:
            payload = {}

        self.add_button_to_list({
            'action': {
                'type': "vkpay",
                'payload': encoder.JSONEncoder().encode(payload),
                'hash': pay_hash,
            }
        })
예제 #7
0
 def __get_group_name_list_mask2(self):
     '''
         @url:http://s.web2.qq.com/api/get_group_name_list_mask2
     '''
     self.__headers.update({'Referer':'http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2'})
     url = 'http://s.web2.qq.com/api/get_group_name_list_mask2'
     a = {'vfwebqq':self.__vfwebqq}
     array = {'r':json_encode.JSONEncoder().encode(a)}
     str = self.__request(url,'POST',array)
     print(str)
     pass
예제 #8
0
def read_config() -> dict:
    if os.path.exists("config.json"):
        cfg_decoder = decoder.JSONDecoder()
        with open("config.json", 'rt') as f:
            return cfg_decoder.decode('\n'.join(f.readlines()))
    else:
        print('Config file not found. Creating new one...')
        cfg = create_default_config()
        cfg_encoder = encoder.JSONEncoder()
        json = cfg_encoder.encode(cfg)
        with open("config.json", 'wt') as f:
            f.write(json)
            f.flush()
        return cfg
예제 #9
0
    def add_text_button(self,
                        label: str,
                        color: str = "secondary",
                        payload=None):
        if payload is None:
            payload = {}

        self.add_button_to_list({
            'action': {
                'type': "text",
                'label': label,
                'payload': encoder.JSONEncoder().encode(payload),
            },
            'color': color,
        })
예제 #10
0
 def send_group_msg(self, gid, msg=u'hello world'):
     print 'send group to:', gid, '-', msg
     self.msgid += 1
     msg = u"[\"" + msg + u"\",[\"font\",{\"name\":\"" + u'宋体' + u"\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]"
     url = 'http://d.web2.qq.com/channel/send_qun_msg2'
     a = {
         'group_uin': gid,
         'face': 180,
         'content': msg,
         'msg_id': self.msgid,
         'clientid': self.clientid,
         'psessionid': self.psessionid
     }
     array = {'r': json_encode.JSONEncoder().encode(a)}
     req = urllib2.Request(url, data=urllib.urlencode(array))
     req.add_header(
         'Referer',
         'http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2')
     result = urllib2.urlopen(req).read()
     print 'group:', result
예제 #11
0
 def __poll2_(self):
     """
         不知道干嘛的,一分钟连接一次,属于长连接,接收消息
         @url:http://d.web2.qq.com/channel/poll2
         r:{"clientid":"9467930","psessionid":"8368046764001e636f6e6e7365727665725f77656271714031302e3132382e36362e31313500003058000000c0026e040009456f266d0000000a407169446b464737436b6d00000028f8d256743e5c191cb40a2217845fab12fda62acd2e6145ae196976d7a8b3bb11a64d3c9565868322","key":0,"ids":[]}
         clientid:9467930
         psessionid:8368046764001e636f6e6e7365727665725f77656271714031302e3132382e36362e31313500003058000000c0026e040009456f266d0000000a407169446b464737436b6d00000028f8d256743e5c191cb40a2217845fab12fda62acd2e6145ae196976d7a8b3bb11a64d3c9565868322
     """
     self.__headers.update({
         'Referer':
         'http://d.web2.qq.com/proxy.html?v=20110331002&callback=2'
     })
     urlv = 'http://d.web2.qq.com/channel/poll2'
     a = {
         'clientid': self.__clientid,
         'psessionid': self.__psessionid,
         'key': 0,
         'ids': []
     }
     array = {
         'r': json_encode.JSONEncoder().encode(a),
         'clientid': self.__clientid,
         'psessionid': self.__psessionid
     }
     self.__poll2 = self.__request(url=urlv, method='POST', data=array)
     str = json_decode.JSONDecoder().decode(self.__poll2)
     print(str)
     if str['retcode'] == 0:
         if str['result'][0]['poll_type'] == 'message':
             self.__message(str['result'][0]['value']['from_uin'])
         elif str['result'][0]['poll_type'] == 'group_message':
             self.__group_message(str['result'][0]['value']['from_uin'])
             pass
     t1 = th.Timer(1, self.__poll2_)
     t1.start()
     pass
예제 #12
0
_MULTIPLE_PLOT_HEIGHT_PER_PLOT = 4

_MULTIPLE_PLOT_MARKER_TYPE = 'o'
_MULTIPLE_PLOT_MARKER_SIZE = 4
_SINGLE_PLOT_STYLE = 'bs-'  # blue squares with lines connecting
_SINGLE_PLOT_ERROR_BAR_COLOR = 'r'

_LEGEND_FONT_SIZE = 'xx-small'
_LEGEND_HANDLE_LENGTH = 0.03
_LEGEND_NUM_POINTS = 3
_LEGEND_MARKER_TYPE = 'o'

_LINE_XTICK_LABELS_SIZE = 'x-small'
_BAR_XTICK_LABELS_SIZE = 8

_json_encoder = encoder.JSONEncoder()


class NoDataError(Exception):
    """\
    Exception to raise if the graphing query returned an empty resultset.
    """


def _colors(n):
    """\
    Generator function for creating n colors. The return value is a tuple
    representing the RGB of the color.
    """
    for i in xrange(n):
        yield colorsys.hsv_to_rgb(float(i) / n, 1.0, 1.0)
예제 #13
0
def BuildPackageChanges() -> bool:
    if not Package.CanBuildPackage():
        return False

    for package in Mod.GetCurrentMod().Packages:  # type: Mod.Package
        baseFileExists = os.path.exists(
            package.SourceBaseFilePath)  # type: bool
        loosePathExists = os.path.exists(package.SourceLoosePath)  # type: bool

        packageManifest = None  # type: typing.Optional[typing.Dict[str, typing.Union[float, typing.Dict[str, float]]]]

        if not os.path.exists(package.BuildFilePath):
            _BuildPackageEverythingInternal(package)
            return True

        if os.path.exists(package.BuildManifestFilePath):
            with open(package.BuildManifestFilePath) as packageManifestFile:
                packageManifest = decoder.JSONDecoder().decode(
                    packageManifestFile.read())

        if packageManifest is not None and not isinstance(
                packageManifest, dict):
            packageManifest = None

        if packageManifest is not None and (not "Loose" in packageManifest
                                            or not "Base" in packageManifest):
            packageManifest = None

        if packageManifest is None:
            _BuildPackageEverythingInternal(package)
            return True
        else:
            filesChanged = False  # type: bool

            if baseFileExists:
                baseCurrentChangeTime = os.path.getmtime(
                    package.SourceBaseFilePath)  # type: float

                if packageManifest["Base"] != os.path.getmtime(
                        package.SourceBaseFilePath):
                    packageManifest["Base"] = baseCurrentChangeTime
                    filesChanged = True

            if loosePathExists:
                packageManifestLooseDictionary = packageManifest[
                    "Loose"]  # type: dict

                for entryFileName in list(
                        packageManifestLooseDictionary.keys()):  # type: str
                    entryChangeTime = packageManifestLooseDictionary[
                        entryFileName]  # type: float

                    entryFilePath = os.path.join(package.SourceLoosePath,
                                                 entryFileName)  # type: str

                    if not os.path.exists(entryFilePath):
                        packageManifestLooseDictionary.pop(entryFileName)
                        filesChanged = True
                        continue

                    entryCurrentChangeTime = os.path.getmtime(
                        entryFilePath)  # type: float

                    if entryCurrentChangeTime != entryChangeTime:
                        packageManifest["Loose"][
                            entryFileName] = entryCurrentChangeTime
                        filesChanged = True

                for sourceDirectoryRoot, sourceDirectoryNames, sourceFileNames in os.walk(
                        package.SourceLoosePath
                ):  # type: str, typing.List[str], typing.List[str]
                    for sourceFileName in sourceFileNames:  # type: str
                        sourceFilePath = os.path.join(
                            sourceDirectoryRoot, sourceFileName)  # type: str
                        relativeSourceFilePath = os.path.relpath(
                            sourceFilePath,
                            package.SourceLoosePath)  # type: str
                        sourceFileDuplicate = False  # type: bool

                        for entryFileName in packageManifest["Loose"].keys(
                        ):  # type: str
                            if entryFileName.lower(
                            ) == relativeSourceFilePath.lower():
                                sourceFileDuplicate = True
                                break

                        if not sourceFileDuplicate:
                            packageManifest["Loose"][
                                relativeSourceFilePath] = os.path.getmtime(
                                    sourceFilePath)
                            filesChanged = True

            if filesChanged:
                addingFilePaths = list()  # type: typing.List[str]

                if loosePathExists:
                    for sourceDirectoryRoot, sourceDirectoryNames, sourceFileNames in os.walk(
                            package.SourceLoosePath
                    ):  # type: str, typing.List[str], typing.List[str]
                        for sourceFileName in sourceFileNames:  # type: str
                            # noinspection SpellCheckingInspection
                            if os.path.splitext(sourceFileName)[1].lower(
                            ) == ".sourceinfo":
                                continue

                            sourceFilePath = os.path.join(
                                sourceDirectoryRoot,
                                sourceFileName)  # type: str

                            if os.path.isfile(sourceFilePath):
                                addingFilePaths.append(sourceFilePath)

                if baseFileExists:
                    Package.BuildPackage(
                        package.BuildFilePath,
                        baseFilePath=package.SourceBaseFilePath,
                        addingFilePaths=addingFilePaths)
                else:
                    Package.BuildPackage(package.BuildFilePath,
                                         addingFilePaths=addingFilePaths)

                with open(package.BuildManifestFilePath,
                          "w+") as packageManifestFile:
                    packageManifestFile.write(
                        encoder.JSONEncoder(
                            indent="\t").encode(packageManifest))

    return True
예제 #14
0
def GetLatestText() -> str:
    automationModule = util.find_spec("Automation")

    if automationModule is None and not _showedWarning:
        print(
            "Failed to build mod distribution index. Environment automation modules are not loaded."
        )
        return ""

    from Automation import Distribution

    latestDictionary = dict()  # type: typing.Dict[str, typing.Dict[str, str]]

    for releaseNamespace in Distribution.Releases.keys():
        latestReleaseVersion = GetLatestReleaseVersion(
            releaseNamespace)  # type: str

        releaseNamespaceDictionary = latestDictionary.get(
            releaseNamespace)  # type: typing.Dict[str, str]

        if releaseNamespaceDictionary is None:
            releaseNamespaceDictionary = dict()
            latestDictionary[releaseNamespace] = releaseNamespaceDictionary

        releaseNamespaceDictionary["Release"] = latestReleaseVersion

        try:
            releasedMod = Mods.GetModConfig(releaseNamespace)
        except:
            continue

        for releaseLegacyNamespace in releasedMod.LegacyNamespaces:  # type: str
            releaseLegacyNamespaceDictionary = latestDictionary.get(
                releaseLegacyNamespace)  # type: typing.Dict[str, str]

            if releaseLegacyNamespaceDictionary is None:
                releaseLegacyNamespaceDictionary = dict()
                latestDictionary[
                    releaseLegacyNamespace] = releaseLegacyNamespaceDictionary

            releaseLegacyNamespaceDictionary["Release"] = latestReleaseVersion

    for previewNamespace in Distribution.Previews.keys():
        latestPreviewVersion = GetLatestPreviewVersion(
            previewNamespace)  # type: str

        previewNamespaceDictionary = latestDictionary.get(
            previewNamespace)  # type: typing.Dict[str, str]

        if previewNamespaceDictionary is None:
            previewNamespaceDictionary = dict()
            latestDictionary[previewNamespace] = previewNamespaceDictionary

        previewNamespaceDictionary["Preview"] = latestPreviewVersion

        try:
            previewedMod = Mods.GetModConfig(previewNamespace)
        except:
            continue

        for previewLegacyNamespace in previewedMod.LegacyNamespaces:  # type: str
            previewLegacyNamespaceDictionary = latestDictionary.get(
                previewLegacyNamespace)  # type: typing.Dict[str, str]

            if previewLegacyNamespaceDictionary is None:
                previewLegacyNamespaceDictionary = dict()
                latestDictionary[
                    previewLegacyNamespace] = previewLegacyNamespaceDictionary

            previewLegacyNamespaceDictionary["Preview"] = latestPreviewVersion

    return encoder.JSONEncoder(indent="\t").encode(latestDictionary)
예제 #15
0
 def generate(self) -> str:
     return encoder.JSONEncoder().encode({
         'inline': self.inline,
         'one_time': self.one_time,
         'buttons': self.buttons,
     })
예제 #16
0
def PublishModRelease(modNamespace: str) -> None:
    print("Publishing mod '" + modNamespace + "' as a release.")

    if Paths.DistributionReleasesPath is None:
        raise Exception(
            "No distribution release path has been specified via automation settings."
        )

    mod = Mods.GetMod(modNamespace)  # type: Mods.Mod
    modDirectoryPath = Mods.GetModPath(modNamespace)  # type: str

    version = mod.GetVersion()  # type: typing.Optional[str]

    installerFilePath = mod.GetInstallerFilePath(
    )  # type: typing.Optional[str]
    filesFilePath = mod.GetFilesFilePath()  # type: typing.Optional[str]
    sourcesFileName = mod.GetSourcesFileName()  # type: typing.Optional[str]

    if version is None:
        raise Exception(
            "Couldn't get the current version number for this mod.")

    if installerFilePath is None:
        raise Exception(
            "Couldn't get the current installer file path for this mod.")

    if filesFilePath is None:
        raise Exception(
            "Couldn't get the current files file path for this mod.")

    if sourcesFileName is None:
        raise Exception(
            "Couldn't get the current sources file name for this mod.")

    distributionVersionDirectoryPath = os.path.join(
        Paths.DistributionReleasesPath, modNamespace.lower(),
        version)  # type: str
    distributionInstallerDirectoryPath = os.path.join(
        distributionVersionDirectoryPath, "installer")  # type: str
    distributionFilesDirectoryPath = os.path.join(
        distributionVersionDirectoryPath, "files")  # type: str
    distributionSourcesDirectoryPath = os.path.join(
        distributionVersionDirectoryPath, "sources")  # type: str

    if os.path.exists(distributionVersionDirectoryPath):
        dir_util.remove_tree(distributionVersionDirectoryPath, verbose=1)

    os.makedirs(distributionInstallerDirectoryPath)
    os.makedirs(distributionFilesDirectoryPath)
    os.makedirs(distributionSourcesDirectoryPath)

    file_util.copy_file(installerFilePath,
                        distributionInstallerDirectoryPath,
                        preserve_times=0)
    file_util.copy_file(filesFilePath,
                        distributionFilesDirectoryPath,
                        preserve_times=0)

    sourcesIncludedPaths = GetIncludedPaths(
        Paths.StrippingModsFilePath,
        Mods.GetModPath(modNamespace))  # type: typing.List[str]

    archiveFile = zipfile.ZipFile(
        os.path.join(distributionSourcesDirectoryPath, sourcesFileName),
        mode="w",
        compression=zipfile.ZIP_DEFLATED)  # type: zipfile.ZipFile

    for sourcesIncludedPath in sourcesIncludedPaths:  # type: str
        archiveFile.write(os.path.join(modDirectoryPath, sourcesIncludedPath),
                          arcname=sourcesIncludedPath)

    archiveFile.close()

    with open(
            os.path.join(distributionVersionDirectoryPath, "information.json"),
            "w+") as versionInformationFile:
        versionInformationFile.write(
            encoder.JSONEncoder(indent="\t").encode({
                "Game Version":
                S4.Version,
                "Release Date":
                datetime.datetime.now().date().isoformat()
            }))