def test_session(): robot = werobot.WeRoBot(token=werobot.utils.generate_token(), enable_session=True) @robot.text def first(message, session): if 'last' in session: return session['last'] = message.content return message.content @robot.text def second(message, session): return session['last'] tester = werobot.testing.WeTest(robot) message_1 = werobot.testing.make_text_message('ss') message_2 = werobot.testing.make_text_message('dd') session_storages = [ filestorage.FileStorage(), mongodbstorage.MongoDBStorage(pymongo.MongoClient().t.t), redisstorage.RedisStorage(redis.Redis()), ] for session_storage in session_storages: robot.session_storage = session_storage assert tester.send(message_1) == tester.send(message_2) == 'ss',\ session_storage remove_session(session_storage)
def test_echo(): robot = werobot.WeRoBot(token=werobot.utils.generate_token()) @robot.handler def echo(message): return message.content tester = werobot.test.WeTest(robot) message = werobot.test.make_text_message('test') assert tester.send(message) == 'test'
def test_echo(): robot = werobot.WeRoBot(token=werobot.utils.generate_token()) @robot.handler def echo(message): return message.img tester = werobot.test.WeTest(robot) message = werobot.test.make_image_message('http://a.com/b.jpg') assert tester.send(message) == 'http://a.com/b.jpg'
def test_session(): robot = werobot.WeRoBot(token=werobot.utils.generate_token(), enable_session=True) @robot.text def first(message, session): if 'last' in session: return session['last'] = message.content return message.content @robot.text def second(_, session): return session['last'] tester = werobot.testing.WeTest(robot) xml_1 = """ <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[ss]]></Content> <MsgId>1234567890123456</MsgId> </xml> """ xml_2 = """ <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[dd]]></Content> <MsgId>1234567890123456</MsgId> </xml> """ try: os.remove(os.path.abspath("werobot_session")) except OSError: pass session_storages = [ filestorage.FileStorage(), mongodbstorage.MongoDBStorage(pymongo.MongoClient().t.t), redisstorage.RedisStorage(redis.Redis()), ] for session_storage in session_storages: remove_session(session_storage) robot.session_storage = session_storage reply_1 = tester.send_xml(xml_1)._args['content'] assert reply_1 == 'ss', (reply_1, session_storage) reply_2 = tester.send_xml(xml_2)._args['content'] assert reply_2 == 'ss', (reply_2, session_storage) remove_session(session_storage)
def test_echo(): robot = werobot.WeRoBot(token=werobot.utils.generate_token()) @robot.location def report(message): x, y = message.location return 'You are at ({x}, {y})'.format(x=x, y=y) tester = werobot.testing.WeTest(robot) message = werobot.testing.make_location_message('20', '30', 40, 'label') assert tester.send(message) == 'You are at (20.0, 30.0)'
def test_events(): robot = werobot.WeRoBot(token=werobot.utils.generate_token()) t = [False, ''] @robot.subscribe def first(message): return 'Hi' tester = werobot.testing.WeTest(robot) xml = """ <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[subscribe]]></Event> </xml> """ assert tester.send_xml(xml) == 'Hi' @robot.unsubscribe def second(message): t[0] = True xml = """ <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[unsubscribe]]></Event> </xml> """ tester.send_xml(xml) assert t[0] @robot.click def f(message): t[1] = message.key xml = """ <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[CLICK]]></Event> <EventKey><![CDATA[EVENTKEY]]></EventKey> </xml> """ tester.send_xml(xml) assert t[1] == 'EVENTKEY'
class Werobot_Run(): __init__(self, name) robot = werobot.WeRoBot(token='testrobot', enable_session=True) @robot.subscribe def subscribe(message): return '欢迎关注本公众号!' @robot.handler def echo(message): return '我是WeRoBot机器人'
def test_add_handler(): robot = werobot.WeRoBot(token=werobot.utils.generate_token()) def a(message): pass robot.add_handler(a) try: robot.add_handler(5) except TypeError: pass else: raise
def main(cfg): try: robot = werobot.WeRoBot(cfg['wiexin']['Token']) urls.register_urls(robot.app) wxrobot.register_handler(robot) robot.run(server='tornado', host="0.0.0.0", port=80, url=cfg['wiexin']["ServerUrl"]) except KeyboardInterrupt: print "exit"
def test_one(): robot = werobot.WeRoBot(token=werobot.utils.generate_token()) @robot.handler def first(message): return @robot.handler def second(message): return "Hi" tester = werobot.test.WeTest(robot) message = werobot.test.make_text_message('oo') assert tester.send(message) == 'Hi'
def __init__(self,hass,face:dict,config:dict,users:dict,regex:dict): self.hass=hass self.face=aip.AipFace(str(face["appId"]),face["apiKey"],face["secretKey"]) if self.face.getGroupUsers("werobot")["error_code"] != 0: raise AuthenticationError("人脸识别认证错误!") self.robot = werobot.WeRoBot() for k,v in config.items(): self.robot.config[k]=v self.users=users self.regex=regex self.robot.config['HOST'] = '0.0.0.0' self.robot.add_handler(self.subscribe, "subscribe_event") self.robot.add_handler(self.recv,"text") self.robot.add_handler(self.recv, "voice") self.robot.add_handler(self.recv, "image")
def test_types(): robot = werobot.WeRoBot(token=werobot.utils.generate_token()) @robot.text def second(message): return "Hi" @robot.image def third(message): return 'nice pic' tester = werobot.test.WeTest(robot) message = werobot.test.make_text_message('oo') assert tester.send(message) == 'Hi' message = werobot.test.make_image_message('img') assert tester.send(message) == 'nice pic'
def test_two(): robot = werobot.WeRoBot(token=werobot.utils.generate_token()) @robot.handler def first(message): if 'hi' in message.content: return 'Hello' @robot.handler def second(message): return "Hi" tester = werobot.testing.WeTest(robot) message = werobot.testing.make_text_message('oo') assert tester.send(message) == 'Hi' message = werobot.testing.make_text_message('hi') assert tester.send(message) == 'Hello'
def test_three(): robot = werobot.WeRoBot(token=werobot.utils.generate_token()) @robot.handler def first(message): if message.type == 'text': return 'txt' @robot.handler def second(message): if message.type == 'image': return 'img' tester = werobot.testing.WeTest(robot) message = werobot.testing.make_text_message('oo') assert tester.send(message) == 'txt' message = werobot.testing.make_image_message('http://a.jpg') assert tester.send(message) == 'img'
class Werobot_Run(): __init__(self,name) robot = werobot.WeRoBot(token='testrobot', enable_session=True) @robot.subscribe def subscribe(message): return '欢迎关注本公众号!' @robot.handler def echo(message): return '我是WeRoBot机器人' #robot.run(server='cherrypy',host='0.0.0.0',port=80) def raw_wsgi_app(): start = Werobot_Run() cherrypy.tree.graft(raw_wsgi_app, '/weixin')
def test_session(): robot = werobot.WeRoBot(token=werobot.utils.generate_token(), enable_session=True) @robot.text def first(message, session): if 'last' in session: return session['last'] = message.content return message.content @robot.text def second(_, session): return session['last'] tester = werobot.testing.WeTest(robot) xml_1 = """ <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[ss]]></Content> <MsgId>1234567890123456</MsgId> </xml> """ xml_2 = """ <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[dd]]></Content> <MsgId>1234567890123456</MsgId> </xml> """ reply_1 = tester.send_xml(xml_1)._args['content'] assert reply_1 == 'ss' reply_2 = tester.send_xml(xml_2)._args['content'] assert reply_2 == 'ss'
def test_link(): robot = werobot.WeRoBot(token=werobot.utils.generate_token()) @robot.link def first(message): assert message.title == 'title' assert message.description == 'description' assert message.url == 'url' tester = werobot.testing.WeTest(robot) xml = """ <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><![CDATA[link]]></MsgType> <Title><![CDATA[title]]></Title> <Description><![CDATA[description]]></Description> <Url><![CDATA[url]]></Url> </xml> """ tester.send_xml(xml)
# @Time : 2020/3/19 17:22 # @Author : Libuda # @FileName: 个人公众号.py # @Software: PyCharm # coding: utf-8 import re import requests import csv import werobot robot = werobot.WeRoBot(token='asdfghgfdsaasdfggfdsasdf') # 被关注自动回复 # @robot.subscribe def subscribe(message): return "嘟嘟最可爱" # 接受信息自动回复 # @robot.handler def search(keyword): return "嘟嘟最可爱 啦啦啦啦" if __name__ == '__main__': robot.config['HOST'] = '127.0.0.1' robot.config['PORT'] = 80 robot.run()
import werobot import os from tuling import visit_tuling from baidu import visit_baidu from chatbot_graph import ChatBotGraph token = os.getenv("token", "XTiw5QAnhO3NOPiYS5AUyQvxOdKI") robot = werobot.WeRoBot(token=token) handler = ChatBotGraph() # @robot.text # def home(message,session): # if "百度百科" in message.content: # session['百度百科']=True # return "欢迎使用百度百科,例如;长沙学院的地址是什么? 输入“退出” 退出词条" # if session['百度百科']: # if "退出" not in message.content: # return visit_baidu(message.content) # else: # session['百度百科'] = False # return "退出百度百科" # return visit_tuling(message.content) @robot.text def home(message, session): if "健康助手" in message.content: session['健康助手'] = True return "欢迎使用健康助手,例如;感冒了不应该吃什么? 输入“退出” 退出健康助手" if session['健康助手']: if "退出" not in message.content: return handler.chat_main(message.content)
# -*- coding:utf-8 -*- import werobot robot = werobot.WeRoBot(token='testrobot') #token="testrobot" @robot.text def echo(message): return message.content robot.config['HOST'] = '0.0.0.0' #默认允许所有IP访问 robot.config['PORT'] = 80 #指定80端口 robot.run()
#coding=utf-8 import werobot from function import * from urllib import request import os robot = werobot.WeRoBot(token='tokenhere') robot.config["APP_ID"] = "wxccd39fd7bd00f08d" robot.config["APP_SECRET"] = "8794656c2edb03f116fd1c49c394a1ff" # robot.config["APP_ID"] = "wx7407f5c28abc23c0" # robot.config["APP_SECRET"] = "0b0e1bf34d4253ff1e550830da0818f8" @robot.filter('订阅通知') def subscribe(): return '欢迎订阅包打听' @robot.text def sub(message): text = message.content if "添加关键词" in text: text = text.split() try: if text[1] == "图片": request.urlretrieve(text[3], r"./demo.jpg") media_id = robot.client.upload_media("image", open(r"./demo.jpg", "rb"))['media_id'] text[3] = media_id
TR = TextReview() C2E = {} C2E['有害垃圾'] = 'harmful-waste' C2E['可回收物'] = 'recyclable' C2E['干垃圾'] = 'residual_waste' C2E['湿垃圾'] = 'household_food_waste' E2C = {} E2C['harmful-waste'] = '有害垃圾' E2C['recyclable'] = '可回收物' E2C['residual_waste'] = '干垃圾' E2C['household_food_waste'] = '湿垃圾' robot = werobot.WeRoBot(token='sapb1') ''' #test robot.config["APP_ID"] = "wx40fe985b752f7cf5" robot.config["APP_SECRET"] ="2b6144472e3307043d3d79b05ea3cb30" ''' #formal robot.config["APP_ID"] = "wx3a3a712bb0ef657e" robot.config["APP_SECRET"] = "420cbcc9e9a99fac7d172b3c34c1009b" client = robot.client media_id_hw = client.upload_permanent_media( "image", open(r"picture/harmful-waste.jpg", "rb"))["media_id"] media_id_hfw = client.upload_permanent_media( "image", open(r"picture/household_food_waste.jpg", "rb"))["media_id"]
class wechat_development: robot = werobot.WeRoBot(token='zyp123456789', app_id='wx075e6145dec8e5e9', app_secret='35d5b46369f00465c9eb82847be53d1e') try: @robot.text def text_message(message): openid = message.source if re.findall( "丝芙兰" + '.*?' + 'sephora.com' + '.*?' + 'P' + "[0-9]+", message.content): stock_url = re.findall("https://www.sephora.com" + '.*', message.content)[0] sql_stock_message, sql_apiurl = is_stockurl_inmysql( ).is_stockurl_inmysql(stock_url) if sql_stock_message == None: data = {"url": "%s" % stock_url} url = "http://54.255.165.203:2333/stockmessage" api_message = requests.post(url=url, data=data) if not re.findall("https://", api_message.text): return "未找到商品,请核对商品链接" stock_message = api_message.text.split("https://")[0] api_url = "https://" + api_message.text.split( "https://")[1] if "skuId=" in stock_url: result = add_stockurl().add_stockurl( openid, stock_url, api_url, stock_message) return "商品信息:\n" + stock_message + '\n' + result else: sku_number = "?skuId=" + api_url.split("Sku=")[1] new_stock_url = stock_url + sku_number result = add_stockurl().add_stockurl( openid, new_stock_url, api_url, stock_message) return "商品信息:\n" + stock_message + '\n' + result else: result = add_stockurl().add_stockurl( openid, stock_url, sql_apiurl, sql_stock_message) return "商品信息:\n" + sql_stock_message + '\n' + result if re.findall("取消关注" + '[0-9]+', message.content): stock_num = re.findall("取消关注" + '[0-9]+', message.content)[0].split("取消关注")[1] return delete_stockurl().delete_stockurl(stock_num, openid) if re.findall("卡泡" + '.*?' + 'colourpop.com/products' + '.*?', message.content): stock_url = re.findall("https://colourpop.com" + '.*', message.content)[0] sql_stock_message, sql_apiurl = is_stockurl_inmysql( ).is_stockurl_inmysql(stock_url) if sql_stock_message == None: data = {"url": "%s" % stock_url} url = "http://54.255.165.203:2333/stockmessage" api_message = requests.post(url=url, data=data) if not re.findall("https://", api_message.text): return api_message.text stock_message = api_message.text.split("https://")[0] api_url = "https://" + api_message.text.split( "https://")[1] result = add_stockurl().add_stockurl( openid, stock_url, api_url, stock_message) return "商品信息:\n" + stock_message + '\n' + result else: result = add_stockurl().add_stockurl( openid, stock_url, sql_apiurl, sql_stock_message) return "商品信息:\n" + sql_stock_message + '\n' + result # if message.content=="测试": # article = [ # { # "title": "这是一个帮助", # "description": "有什么问题可以加这个微信", # "url": "http://47.93.149.238:8888/download?filename=/www/wwwroot/WeChatZyp/application/index/controller/my_wechat.jpg", # "picurl": "http://47.93.149.238:8888/download?filename=/www/wwwroot/WeChatZyp/application/index/controller/my_wechat.jpg" # } # ] # openid=message.source # return clinet.Client.send_article_message(message,openid,article,kf_account=None) else: return "我很专注的,可不会闲聊哦" @robot.click def click_event(message): if message.key == 'attention_sephora': return "请回复 丝芙兰+要关注的商品地址" + '\n' + "示例:丝芙兰https://www.sephora.com/product/powermatte-lip-pigment-P421485" if message.key == 'attention_colorpop': return "请回复 卡泡+要关注的商品地址" + '\n' + "示例:卡泡https://colourpop.com/products/mulan-eyeshadow-palette" if message.key == 'attention_list': openid = message.source return my_attention().check_attention(openid) if message.key == 'help': # article = [ # { # "title": "这是一个帮助", # "description": "有什么问题可以加这个微信", # "url": "http://47.93.149.238:8888/download?filename=/www/wwwroot/WeChatZyp/application/index/controller/my_wechat.jpg", # "picurl": "http://47.93.149.238:8888/download?filename=/www/wwwroot/WeChatZyp/application/index/controller/my_wechat.jpg" # } # ] # openid=message.source # return clinet.Client.send_article_message(message,openid,article,kf_account=None) return "1.提供境外商品补货通知服务,直接按照指示回复商品链接就可以了哦,商品补货后这边会第一时间通知您的!" + '\n' + '2.若商品有多个色号或大小,商品链接请精确到具体的色号或大小哦' + '\n' + 'ps(若需更多帮助可加微信:either2 记得备注“微信公众号”哦)' @robot.subscribe def subscribe(message): return "终于等到你!" robot.config['HOST'] = '0.0.0.0' robot.config['PORT'] = 80 robot.run() except Exception as e: with open("./wechat_development.txt", 'a', encoding='utf8') as f: f.write(str(e))
import werobot robot = werobot.WeRoBot(token='ssjsecrettoken980612ssj') @robot.handler def echo(message): return 'Hello World!' robot.config['HOST'] = '0.0.0.0' robot.config['PORT'] = 80
# -*- coding:utf-8 -*- import werobot, requests, pymysql import re from bs4 import BeautifulSoup robot = werobot.WeRoBot(token='yanhuaijun') # 全部回复 # @robot.handler # def echo(message): # return 'Hello World!' # 你发什么我回复什么 # @robot.text # def echo(message): # return message.content # 连接数据库 def my_db(msg): conn = pymysql.Connect( host='47.106.143.70', ##mysql服务器地址 port=3306, ##mysql服务器端口号 user='******', ##用户名 passwd='123456', ##密码 J5p";~OVazNl%y)? db='666', ##数据库名 charset='utf8', ##连接编码 ) sq1 = 'SELECT * FROM cityid WHERE city_name LIKE "%s"' % ('%' + msg + '%') # cursor = con.cursor() # 获取游标 # sql = 'select * from my_user where username="******";' % username
# -*- coding: utf-8 -*- import werobot import game import conf import tools robot = werobot.WeRoBot() tools.robot = robot ''' msg: ToUserName: FromUserName: CreateTime: Content: MsgId: ''' @robot.text def reply(msg, session): return game.onUserReply(msg, session) # 让服务器监听在 127.0.0.1:80 robot.config.from_object(conf.RobotConfig) if not conf.is_demo: robot.run()
import os from searchsession import * from weatherstation import * from apistatics import * import werobot import time import urllib import json import requests from apscheduler.schedulers.background import BackgroundScheduler global weatherstation weatherstation = [] onlinesession = [] # list to store the information of chatting robot = werobot.WeRoBot(token='louishe999617') #client = robot.client #DEVELOPING... def getData(org,lon,lat): if org == 'GFS': data = urllib.request.urlopen('https://node.windy.com/forecast/v2.1/gfs/' + str(lat) +'/' + str(lon) + '?source=detail').read() if org == 'EC': data = urllib.request.urlopen('https://node.windy.com/forecast/v2.1/ecmwf/' + str(lat) +'/' + str(lon) + '?setup=summary&includeNow=true&source=hp').read() record = data.decode('UTF-8') data = json.loads(record) ''' for i in range(0,len(data)): station.append(data[i]['station']['city']) province.append(data[i]['station']['province'])
# -*- coding:utf-8 -*- import werobot # robot = werobot.WeRoBot(token='robot', enable_session=True, session_storage=saekvstorage.SaeKVDBStorage()) # robot = werobot.WeRoBot(token='testrobot', enable_session=True, session_storage=filestorage.FileStorage()) robot = werobot.WeRoBot(token='testrobot', enable_session=True) @robot.subscribe def subscribe(message): return '欢迎关注本公众号!' @robot.handler def echo(message): return '我是WeRoBot机器人' robot.run(server='cherrypy', host='0.0.0.0', port=80)
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import werobot from urllib.request import urlretrieve from mods_available import * import threading import requests robot = werobot.WeRoBot(token='token') # @robot.handler # def hello(message): # return 'Hello World!' @robot.text def textReply(message, session): if message.content[:2] != '往事': reply = msgReply(message, session) else: access_token = get_access_token() hisReply = History() hisImgPath = hisReply() media_id = upload_media(access_token, hisImgPath) reply = werobot.replies.ImageReply(message=message, media_id=media_id) return reply @robot.voice def vioceReply(message):
import requests import time from aip import AipFace import base64 from io import BytesIO import json import os import simplejson import requests import json import base64 import json from bs4 import BeautifulSoup import requests client = AipFace(APP_ID, API_KEY, SECRET_KEY) robot = werobot.WeRoBot(token='11223344') def nCoV(message): res = requests.get("http://3g.dxy.cn/newh5/view/pneumonia") def get_data(res): soup = BeautifulSoup(res.content, 'html.parser') data = soup.find(id="getAreaStat").string data = data.strip("try { window.getAreaStat = ").strip("}catch(e){}") data = json.loads(data) return data def get_data2(res):