def __init__(self): self.wxclient = Client('appid_xxxxxxxxxxxxxxx', 'appsecret_xxxxxxxxxxxxxx') self.robot = None self.subscribe_auto_msg = None super(WxEntry, self).__init__()
def __init__(self, app_id=APP_ID, app_secret=APP_SECRET): self.logger = Logger('PushClient') client_config = {'APP_ID': app_id, 'APP_SECRET': app_secret} self.client = Client(client_config) if DATABASE == 'redis': self.db = RedisConnect() elif DATABASE == 'sqlite': self.db = SQLiteConnect()
def __init__(self): self.wxclient = Client('appid_xxxxxxxxxxxxxxx', 'appsecret_xxxxxxxxxxxxxx') self.UUID_OPENID = {} # 微信用户客服消息的会话缓存 self.OPENID_UUID = {} self.robot = None
# coding=utf-8 from werobot.client import Client, ClientException from openerp import exceptions wxclient = Client('appid_xxxxxxxxxxxxxxx', 'appsecret_xxxxxxxxxxxxxx') UUID_OPENID = {} def send_text(openid, text): try: wxclient.send_text_message(openid, text) except ClientException, e: raise exceptions.UserError(u'发送失败 %s' % e) def chat_send(db, uuid, msg): _dict = UUID_OPENID.get(db, None) if _dict: openid = _dict.get(uuid, None) if openid: send_text(openid, msg) return -1
class WxEntry(EntryBase): def __init__(self): self.wxclient = Client('appid_xxxxxxxxxxxxxxx', 'appsecret_xxxxxxxxxxxxxx') self.robot = None self.subscribe_auto_msg = None super(WxEntry, self).__init__() def send_text(self, openid, text): try: self.wxclient.send_text_message(openid, text) except ClientException as e: raise exceptions.UserError(u'发送失败 %s' % e) def chat_send(self, uuid, msg): openid = self.get_openid_from_uuid(uuid) if openid: self.send_text(openid, msg) def upload_media(self, media_type, media_file): try: return self.wxclient.upload_media(media_type, media_file) except ClientException as e: raise exceptions.UserError(u'image上传失败 %s' % e) def send_image_message(self, openid, media_id): try: self.wxclient.send_image_message(openid, media_id) except ClientException as e: raise exceptions.UserError(u'发送image失败 %s' % e) def send_image(self, uuid, media_id): openid = self.get_openid_from_uuid(uuid) if openid: self.send_image_message(openid, media_id) def send_voice(self, uuid, media_id): openid = self.get_openid_from_uuid(uuid) if openid: try: self.wxclient.send_voice_message(openid, media_id) except ClientException as e: raise exceptions.UserError(u'发送voice失败 %s' % e) def create_reply(self, ret_msg, message): if type(ret_msg) == dict: if ret_msg.get('media_type') == 'news': self.wxclient.send_news_message(message.source, ret_msg['media_id']) return None else: return create_reply(ret_msg, message=message) def init(self, env): dbname = env.cr.dbname global WxEnvDict if dbname in WxEnvDict: del WxEnvDict[dbname] WxEnvDict[dbname] = self try: config = env['wx.config'].sudo().get_cur() action = config.action except: import traceback traceback.print_exc() action = None if action: self.subscribe_auto_msg = config.action.get_wx_reply() Param = env['ir.config_parameter'].sudo() self.wx_token = Param.get_param('wx_token') or '' self.wx_appid = Param.get_param('wx_appid') or '' self.wx_AppSecret = Param.get_param('wx_AppSecret') or '' #robot.config["TOKEN"] = self.wx_token self.wxclient.appid = self.wx_appid self.wxclient.appsecret = self.wx_AppSecret try: # 刷新 AccessToken self.wxclient._token = None _ = self.wxclient.token except: import traceback traceback.print_exc() _logger.error(u'初始化微信客户端token失败,请在微信对接配置中填写好相关信息!') session_storage = MemoryStorage() robot = WeRoBot(token=self.wx_token, enable_session=True, logger=_logger, session_storage=session_storage) enable_pretty_logging(robot.logger) self.robot = robot try: users = env['wx.user'].sudo().search([('last_uuid', '!=', None)]) for obj in users: if obj.last_uuid_time: self.recover_uuid( obj.openid, obj.last_uuid, fields.Datetime.from_string(obj.last_uuid_time)) except: env.cr.rollback() import traceback traceback.print_exc() print('wx client init: %s %s' % (self.OPENID_UUID, self.UUID_OPENID))
def client(self): config = Config() config.from_pyfile(os.path.join(BASE_DIR, "client_config.py")) return Client(config)
api.add_resource(App, '/api/applications') for rule in urlpatterns: app.url_map.add(rule) #### router #### #### wechat #### import werobot robot = werobot.WeRoBot(token='69b3f633cd9e4136bfdd8be812a34e28') config = Config() basedir = os.path.dirname(os.path.abspath(__file__)) config.from_pyfile(os.path.join(basedir, "client_config.py")) client = Client(config=config) from werkzeug.local import LocalProxy def get_client(): return client tulingbot = Tuling() ###client.get_menu ''' client.create_menu({ "button": [ { "name": "办事指南",
import werobot from werobot.replies import ArticlesReply, Article, ImageReply from werobot.client import Client import requests, json robot = werobot.WeRoBot(token='eeewomenbusinessacademy') client = Client( config={ 'APP_ID': 'wx3ff24c6f361db7c0', 'APP_SECRET': '42d3c288053541acb9a1b73da8a7b175' }) def get_media(): res = client.get_media_list('image', 0, 20) print(res) def send_reminder(): token = client.grant_token().get('access_token', None) groups = client.get_groups() tag_id = -1 for group in groups['groups']: if group.get('name', None) == '3E_Inner': tag_id = group['id'] print(tag_id) break if token: URL = 'https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token={token}'.format( token=token) params = {'tagid': tag_id}
def switch(): sensor_data = get_sensor_data() if (sensor_data): return "液化气浓度:{0} ppm".format(float(sensor_data['MQ-2'])) else: return err_msg @robot.key_click("SMOKE") def switch(): sensor_data = get_sensor_data() if (sensor_data): return "烟雾浓度:{0} ppm".format(float(sensor_data['MQ-5'])) else: return err_msg @robot.click def click_event(): return "我还没有准备好!" # Reading menu data back with open('./data/menu.json', 'r') as f: menu_data = json.load(f) client = Client("wx6eff06f20136ac85", "f2cafa0e5900a415e812ac2ef557d0f6") client.create_menu(menu_data) robot.run(host='0.0.0.0', port=8889)
# -*- coding: utf-8 -*- import werobot from werobot.client import Client robot = werobot.WeRoBot(token='hehe') app_id = 'wx35028b78608d38f9' app_secret = '107da9b468d3cf7427dc439de6405d01' client = Client(app_id, app_secret) client.create_menu({ "button": [ { "type": "view", "name": "Test", "url": "www.baidu.com" } ]}) @robot.handler def echo(message): print robot return 'http://www.baidu.com' robot.run(host='0.0.0.0', port=80)
def test_id_and_secret(): config = Config() config.from_pyfile(os.path.join(basedir, "test_client.py")) client = Client(config) assert client.appid == "123" assert client.appsecret == "321"
"http://weibo.com/woaini3721" ], [ "Jiajia's Qzone", "Jiajia's Qzone", "https://mmbiz.qlogo.cn/mmbiz/j3gm1jVss1wbcIEOP1BjFicLUFmueEujCvrDdTRSCwKYHh8vaVv6ET1dMnF35XjbDRBcAodtPoCibJPajzxibGYNg/0", "http://user.qzone.qq.com/670045284" ], [ "Jiajia's RenRen", "Jiajia's RenRen", "https://mmbiz.qlogo.cn/mmbiz/j3gm1jVss1wbcIEOP1BjFicLUFmueEujCSiaJxqmLYNd5zmdhzZWzuEDM6TFb1qtlNVkO5YCdGcrAN0iaDkianLjuA/0", "http://www.renren.com/431744788/profile" ] ] client = Client("wx6eff06f20136ac85", "f2cafa0e5900a415e812ac2ef557d0f6") client.create_menu({ "button": [{ "type": "view", "name": "Valentine", "url": "http://create.maka.im/k/1FG29JLU" }, { "type": "view", "name": "Beautiful", "url": "http://create.maka.im/k/EQ52YHUW" }, { "name": "More", "sub_button": [{ "type": "click", "name": "Life",
# Signature 验证不通过时显示的错误页面 @wx_robot.error_page def make_error_page(url): return "<h1>喵喵喵 %s 不是给麻瓜访问的快走开</h1>" % url # Handler # ################################################################# @wx_robot.handler def hello(message, session): print("handler:", type(message), type(session)) print(message.__type__) return '不支持消息类型:{}'.format(type(message)) if __name__ == '__main__': # Client # ################################################################# c = Client( config={ "APP_ID": "wx8df663f95f624ddc", "APP_SECRET": "9af6b8495185cfc6c4b5cea7e8bf7f07" }) res = c.get_followers(first_user_id=None) print(res) c.send_text_message(user_id="oBCxywNx_nthmopfu914jLSVuobU", content="你好") pass
def client(self): return Client(self.config)
class PushUpdatesClient: '''推送数据更新封装类''' def __init__(self, app_id=APP_ID, app_secret=APP_SECRET): self.logger = Logger('PushClient') client_config = {'APP_ID': app_id, 'APP_SECRET': app_secret} self.client = Client(client_config) if DATABASE == 'redis': self.db = RedisConnect() elif DATABASE == 'sqlite': self.db = SQLiteConnect() def parse_update_into_message(self, area): msg = '新增' msg += '确诊 {} 例、'.format( area['n_confirm']) if area['n_confirm'] != 0 else '' msg += '疑似 {} 例、'.format( area['n_suspect']) if area['n_suspect'] != 0 else '' msg += '死亡 {} 例、'.format(area['n_dead']) if area['n_dead'] != 0 else '' msg += '治愈 {} 例、'.format(area['n_heal']) if area['n_heal'] != 0 else '' msg = msg.rstrip('、') + '。\n' msg += '截至目前总计' msg += '确诊 {} 例、'.format(area['confirm']) msg += '死亡 {} 例、'.format(area['dead']) msg += '治愈 {} 例。'.format(area['heal']) return '\n{}\n'.format(msg) def main(self): # 检查是否有需要推送的数据更新 if not get_should_update(): self.logger.debug('无数据更新,无需推送') return with updates_file.open() as f: updates = json.load(f) self.logger.info('准备推送共{}个地区的数据更新'.format(len(updates))) # TODO: 最好把所有一个用户所有的订阅更新在一条消息里推送? for area in updates: subscribed_users = self.db.get_subscribed_users(area['area']) if not subscribed_users: continue template_data = { 'area': { 'value': get_area_display_name(area), 'color': '#2980b9' }, 'update': { 'value': self.parse_update_into_message(area), 'color': '#d35400' }, 'datetime': { 'value': datetime.datetime.now().strftime('%Y年%-m月%-d日 %H:%M'), 'color': '#7f8c8d' } } for user in subscribed_users: self.client.send_template_message(user, TEMPLATE_ID, template_data) # 完成推送,删除数据更新文件 remove_update() self.logger.info('全部更新推送完成')
class WxEntry(object): def __init__(self): self.wxclient = Client('appid_xxxxxxxxxxxxxxx', 'appsecret_xxxxxxxxxxxxxx') self.UUID_OPENID = {} # 微信用户客服消息的会话缓存 self.OPENID_UUID = {} self.robot = None def send_text(self, openid, text): try: self.wxclient.send_text_message(openid, text) except ClientException as e: raise exceptions.UserError(u'发送失败 %s' % e) def chat_send(self, db, uuid, msg): #_dict = self.UUID_OPENID.get(db,None) if self.UUID_OPENID: openid = self.UUID_OPENID.get(uuid, None) if openid: self.send_text(openid, msg) return -1 def init(self, env): dbname = env.cr.dbname global WxEnvDict if dbname in WxEnvDict: del WxEnvDict[dbname] WxEnvDict[dbname] = self Param = env['ir.config_parameter'].sudo() self.wx_token = Param.get_param('wx_token') or '' self.wx_appid = Param.get_param('wx_appid') or '' self.wx_AppSecret = Param.get_param('wx_AppSecret') or '' #robot.config["TOKEN"] = self.wx_token self.wxclient.appid = self.wx_appid self.wxclient.appsecret = self.wx_AppSecret try: # 刷新 AccessToken self.wxclient._token = None _ = self.wxclient.token except: import traceback traceback.print_exc() _logger.error(u'初始化微信客户端token失败,请在微信对接配置中填写好相关信息!') session_storage = MemoryStorage() robot = WeRoBot(token=self.wx_token, enable_session=True, logger=_logger, session_storage=session_storage) enable_pretty_logging(robot.logger) self.robot = robot users = env['wx.user'].sudo().search([('last_uuid', '!=', None)]) for obj in users: self.OPENID_UUID[obj.openid] = obj.last_uuid self.UUID_OPENID[obj.last_uuid] = obj.openid print('wx client init: %s %s' % (self.OPENID_UUID, self.UUID_OPENID))
"Jiajia's Qzone", "Jiajia's Qzone", "https://mmbiz.qlogo.cn/mmbiz/j3gm1jVss1wbcIEOP1BjFicLUFmueEujCvrDdTRSCwKYHh8vaVv6ET1dMnF35XjbDRBcAodtPoCibJPajzxibGYNg/0", "http://user.qzone.qq.com/670045284" ], [ "Jiajia's RenRen", "Jiajia's RenRen", "https://mmbiz.qlogo.cn/mmbiz/j3gm1jVss1wbcIEOP1BjFicLUFmueEujCSiaJxqmLYNd5zmdhzZWzuEDM6TFb1qtlNVkO5YCdGcrAN0iaDkianLjuA/0", "http://www.renren.com/431744788/profile" ] ] client = Client("wx6eff06f20136ac85", "f2cafa0e5900a415e812ac2ef557d0f6") client.create_menu({ "button": [ { "type": "view", "name": "Valentine", "url": "http://create.maka.im/k/1FG29JLU" }, { "type": "view", "name": "Beautiful", "url": "http://create.maka.im/k/EQ52YHUW" }, { "name": "More", "sub_button": [
formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) return logger def get_writer(file_path): return open(file_path, '+a') LOG = get_logger("/var/log/werobot.log") # csver = get_writer("/var/log/keyword_response.csv") robot = werobot.WeRoBot(token='iswbm', logger=LOG) client = Client(config) db = MYSQL() def upload_image_media(client, image_path): print( client.upload_permanent_media(media_type="image", media_file=open(image_path, "rb"))) def save_data_and_check_black_list(dbclient): def is_in_black_list(user_id): if db.is_banned(user_id): return True def wrapper(func):