Exemple #1
0
def build():
    _config = config.get('WeChat', None)
    _wechat = WeChat(_config)

    docs = list()
    ret = _wechat.getMaterialsList('news', get_all=True)
    media_list = list()
    for item in ret['item']:
        news_item = item['content']['news_item'][0]
        media_list.append(news_item['thumb_media_id'])
        doc = dict(
                thumb_media_id = news_item['thumb_media_id'],
                title = '%s' % (news_item['title']),
                url = news_item['url'],
                show_cover_pic = news_item['show_cover_pic'],
                cover_pic_url = fill_pic_url(news_item['thumb_media_id']),
                summary = '%s' % (news_item['digest']),
                content = '%s' % (news_item['content']),
                update_time = datetime.fromtimestamp(item['update_time']),
                content_source_url = news_item['content_source_url'],
                )
        docs.append(doc)

    create_index(docs, indexdir=_config['INDEX_DIR'])
    print "=" * 20
    print "Finished creating index."
    print generate_download_shell(_wechat.getAccessToken(), media_list)
def init(provider: ServiceProvider, config: Config):
    global service_provider
    service_provider = provider

    global wechat
    wechat = WeChat()
    load_config(config)

    wechat.set_msg_handler('text', handle_text_message)
Exemple #3
0
class MainWindow(QWidget, Ui_mainform):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.timer = QTime()
        self.newChat = WeChat()
        self.qrUI = QrWindow()
        self.freemsgUI = FreeMsgWindow()
        self.normalUI = NormalMsgWindow()
        self.pushButton_NewMessage.clicked.connect(
            self.on_pB_NewMessage_clicked)
        self.pushButton_LoginWechat.clicked.connect(
            self.on_pB_LoginWechat_clicked)
        self.pushButton_DeleteMessage.clicked.connect(
            self.on_pB_DeleteMessage_clicked)
        self.thread = Thread_login()
        self.thread.sinOut.connect(self.login)
        self.init_MsgTable()

    def init_MsgTable(self):
        self.tableWidget_MSG.setColumnWidth(5, 200)

    def on_pB_NewMessage_clicked(self):
        self.freemsgUI.show()

    def on_pB_DeleteMessage_clicked(self):
        self.normalUI.show()

    def on_pB_LoginWechat_clicked(self):
        self.newChat.open_qr()
        qrpic = QPixmap(self.newChat.picDir)
        self.qrUI.labe_Qrcode.setPixmap(qrpic)
        self.qrUI.label_Qrstatus.setText('请打开手机微信扫码登陆')
        self.qrUI.show()
        self.thread.start()

    def login(self, file_inf):
        if file_inf == '200':
            self.qrUI.label_Qrstatus.setText('登陆成功')
            self.newChat.run()
            self.qrUI.close()
            self.thread.quit()
            self.pushButton_LoginWechat.setText('切换用户')
            username = self.newChat.init_username()
            self.label_username.setText(username)

        elif file_inf == '201':
            self.qrUI.label_Qrstatus.setText('请在手机微信中确认登陆')
        elif file_inf == '408':
            self.qrUI.label_Qrstatus.setText('二维码失效')
Exemple #4
0
 def __init__(self):
     super(MainWindow, self).__init__()
     self.setupUi(self)
     self.timer = QTime()
     self.newChat = WeChat()
     self.qrUI = QrWindow()
     self.freemsgUI = FreeMsgWindow()
     self.normalUI = NormalMsgWindow()
     self.pushButton_NewMessage.clicked.connect(
         self.on_pB_NewMessage_clicked)
     self.pushButton_LoginWechat.clicked.connect(
         self.on_pB_LoginWechat_clicked)
     self.pushButton_DeleteMessage.clicked.connect(
         self.on_pB_DeleteMessage_clicked)
     self.thread = Thread_login()
     self.thread.sinOut.connect(self.login)
     self.init_MsgTable()
Exemple #5
0
def main():
    wc = WeChat()
    spider_man = {
        "hc3i": "",
        "iyiou": "",
        "sina": "",
        "hchina": "",
        "vcbeat": "",
        "xinhua": "",
        "biodiscover": "",
    }
    site_map = {
        "hc3i": u"中国数字医疗网",
        "iyiou": u"亿欧",
        "sina": u"新浪医药",
        "hchina": u"健康中国",
        "vcbeat": u"动脉网",
        "ckxx": u"参考消息",
        "xinhua": u"新华健康",
        "biodiscover": u"生物探索",
    }
    spider_bug = """
    ||  ||
     \\()//
    //(__)\\
    ||    ||
    """
    logging.info("start ower spider .... ")
    logging.info(spider_bug)
    while True:
        for item in spider_man:
            try:
                spider_res = getattr(spider, item)()
            except Exception as e:
                logging.error(e)
                continue
            logging.info(u'【' + site_map[item] + u'】' + spider_res['title'])
            if spider_man[item] and spider_man[item] != spider_res["title"]:
                logging.info("new post find:")
                wc.send(u'【' + site_map[item] + u'】' + spider_res['title'],
                        spider_res['preview'], spider_res['url'])
            spider_man[item] = spider_res["title"]

        time.sleep(10)
        logging.info("new loop")
Exemple #6
0
def run():
    usage = 'usage: %prog --touser=<to user> --message=<sending message> [options]'
    parser = OptionParser(usage=usage)
    parser.add_option('--touser', '-u', dest='touser', help='message send to')
    parser.add_option('--message',
                      '-m',
                      dest='message',
                      help='message you want to send')
    parser.add_option('--toparty',
                      '-p',
                      dest='toparty',
                      help='sending party. Use the one in cfg.ini as default')
    (options, args) = parser.parse_args()
    for option_name, key in REQUIRED_OPTIONS:
        if not getattr(options, key, None):
            raise ValueError('Missing required argument: ' + option_name)

    wechat = WeChat(toparty=options.toparty,
                    touser=options.touser,
                    msg=options.message)

    wechat.send_msg()
Exemple #7
0
from config import Constant
from config import Log
#---------------------------------------------------
import flask
import threading
import traceback
import os
import logging
import time
#===================================================

cm = ConfigManager()
db = SqliteDB(cm.getpath('database'))
# db = MysqlDB(cm.mysql())
wechat_msg_processor = WeChatMsgProcessor(db)
wechat = WeChat(cm.get('wechat', 'host'))
wechat.db = db
wechat.bot = Bot()
wechat.msg_handler = wechat_msg_processor
wechat_msg_processor.wechat = wechat

PORT = int(cm.get('setting', 'server_port'))
app = flask.Flask(__name__)
app.config['UPLOAD_FOLDER'] = cm.getpath('uploaddir')

logger = logging.getLogger('werkzeug')
log_format_str = Constant.SERVER_LOG_FORMAT
formatter = logging.Formatter(log_format_str)
flask_log_handler = logging.FileHandler(cm.getpath('server_log_file'))
flask_log_handler.setLevel(logging.INFO)
flask_log_handler.setFormatter(formatter)
app = Flask(__name__)
app.config.from_object(os.getenv('FLASK_SETTINGS', 'settings'))

session = Session()
session.trust_env = False
session.headers.update({
    'Authorization':
    'Bearer ' + app.config['INTERCOM_ACCESS_TOKEN'],
    'Accept':
    'application/json',
    'Connection':
    'Keep-Alive'
})

wechat = WeChat(app.config['WECHAT_API_BASE_URL'])


def api(path):
    return 'https://api.intercom.io/' + path.lstrip('/')


@app.route('/wechat', methods=['POST'])
def wechat_entry():
    ctx = request.json

    wechat_client = 'default'
    if 'client' in request.args:
        wechat_client = urldecode(request.args['client'])
    g.wechat_client = wechat_client
    g.wechat_client_encoded = urlencode(wechat_client)
Exemple #9
0
from config import Log
#---------------------------------------------------
from flask import Flask, render_template, send_file, jsonify, request
import threading
import traceback
import os
import logging
import time
#===================================================


cm = ConfigManager()
db = SqliteDB(cm.getpath('database'))
# db = MysqlDB(cm.mysql())
wechat_msg_processor = WeChatMsgProcessor(db)
wechat = WeChat(cm.get('wechat', 'host'))
wechat.db = db
wechat.bot = Bot()
wechat.msg_handler = wechat_msg_processor
wechat_msg_processor.wechat = wechat

PORT = int(cm.get('setting', 'server_port'))
app = Flask(__name__, template_folder='flask_templates')
app.config['UPLOAD_FOLDER'] = cm.getpath('uploaddir')

logger = logging.getLogger('werkzeug')
log_format_str = Constant.SERVER_LOG_FORMAT
formatter = logging.Formatter(log_format_str)
flask_log_handler = logging.FileHandler(cm.getpath('server_log_file'))
flask_log_handler.setLevel(logging.INFO)
flask_log_handler.setFormatter(formatter)
Exemple #10
0
 def __init__(self):
     self.wechat = WeChat()
     self.openldap = OpenLdap()
     self.e_mail = Email()
Exemple #11
0
class Main:
    def __init__(self):
        self.wechat = WeChat()
        self.openldap = OpenLdap()
        self.e_mail = Email()

    def get_wechat_uid_info(self, uid):
        #根据uid获取企业微信中该用户的属性值
        wechat_user_list = self.wechat.get_user_list()
        for info in wechat_user_list:
            for k_info, v_info in info.items():
                if k_info == 'userid':
                    v = v_info.lower()
                    if v == uid:
                        return info

    def get_wechat_gid_info(self, gid):
        #跟据部门id获取企业微信中该部门的属性值
        wechat_department_list = self.wechat.get_department_list()
        for info in wechat_department_list:
            for k_info, v_info in info.items():
                if k_info == 'id':
                    if v_info == gid:
                        return info

    def get_wechat_ugid(self, uid):
        #根据uid获取企业微信的部门id,用于排除添加某部门用户
        wechat_user_list = self.wechat.get_user_list()
        for info in wechat_user_list:
            for k_info, v_info in info.items():
                if k_info == 'userid':
                    v = v_info.lower()
                    if v == uid:
                        dep_id = info.get('department')
                        return dep_id

    def add_user(self):
        ldap_uid = self.openldap.get_ldap_uid()
        ldap_gid = self.openldap.get_ldap_gid()
        wechat_uid = self.wechat.get_wechat_userid()
        wechat_gid = self.wechat.get_wechat_gid()

        #添加用户组
        for w_gid in wechat_gid:
            #判断微信部门是否已经存在ldap组中
            if w_gid not in ldap_gid:
                #列表[id]转成字符串id
                gid = [str(x) for x in w_gid]
                gid_new = "".join(gid)
                wechat_gid_info = self.get_wechat_gid_info(int(gid_new))
                print(wechat_gid_info)

                # 不存在则向ldap添加部门信息
                def f(id, name):
                    return self.openldap.ldap_add_group(id, name)

                f(**wechat_gid_info)

        #添加用户
        for w_uid in wechat_uid:
            # 判断微信账号是否已经存在ldap中
            if w_uid not in ldap_uid:
                # 不存在则向ldap添加账号信息
                # 列表[uid]转成字符串'uid'
                uid = "".join(w_uid)
                #判断用户是否属于排除添加的部门:合作伙伴(:40)
                exclude = [40]
                wechat_dep_id = self.get_wechat_ugid(uid)
                if wechat_dep_id not in exclude:
                    #添加用户
                    wechat_uid_info = self.get_wechat_uid_info(uid)

                    def f(userid, name, mobile, email, position, department):
                        print('开始添加ldap用户:%s' % userid)
                        if self.openldap.ldap_add_user(userid, name, mobile,
                                                       email, position,
                                                       department):
                            print('开始发送邮件')
                            self.e_mail.send_mail(email, userid, name)

                    f(**wechat_uid_info)
Exemple #12
0
# -*- coding: utf-8 -*-
from config import config
from wechat import WeChat


_config = config.get('WeChat', None)
if __name__ == '__main__':

    _wechat = WeChat(_config)
    ret = _wechat.getMaterialsList('news', get_all=True)
    media_id = ret['item'][20]['content']['news_item'][0]['thumb_media_id']
    ret = _wechat.getMaterial(media_id)
    with open('a.jpg', 'w+') as f:
        f.write(str(ret))
        f.close()

Exemple #13
0
def main():
    client = WeChat()
    client.run()
Exemple #14
0
# -*- coding: utf-8 -*-
from config import config
from flask import request
from flask import Response
from flask import current_app as app
from wechat import WeChat
from hooks import *

__all__ = ['hello', 'wechat']

_config = config.get('WeChat', None)
_wechat = WeChat(_config)
#_wechat.register('*', no_reply)
#_wechat.register('normal', normal_reply)
#_wechat.register('*', simsimi_reply)
_wechat.register('*', material_search)
#_wechat.register('search', material_search)
_wechat.register('event', event_reply)
_wechat.register('trademe', system_control)

def hello():
    return "Hello, I'm Pikachu."

def wechat():
    res = request.data
    app.logger.debug('Response: %s' % res)

    signature = request.args.get('signature')
    timestamp = request.args.get('timestamp')
    nonce = request.args.get('nonce')
    if not _wechat.validate(signature, timestamp, nonce):
Exemple #15
0
import os
import logging
import time
import signal
#===================================================
import roslib
import rospy
from std_msgs.msg import String
from robot_msgs.srv import Speak
#===================================================

cm = ConfigManager()
db = SqliteDB(cm.getpath('database'))
# db = MysqlDB(cm.mysql())
wechat_msg_processor = WeChatMsgProcessor(db)
wechat = WeChat(cm.get('wechat', 'host'))
wechat.db = db
wechat.bot = Bot()
wechat.msg_handler = wechat_msg_processor
wechat_msg_processor.wechat = wechat

PORT = int(cm.get('setting', 'server_port'))
app = Flask(__name__, template_folder='flask_templates')
app.config['UPLOAD_FOLDER'] = cm.getpath('uploaddir')

logger = logging.getLogger('werkzeug')
log_format_str = Constant.SERVER_LOG_FORMAT
formatter = logging.Formatter(log_format_str)
flask_log_handler = logging.FileHandler(cm.getpath('server_log_file'))
flask_log_handler.setLevel(logging.INFO)
flask_log_handler.setFormatter(formatter)