Example #1
0
    def post(self, *args, **kwargs):
        from wxpy import ensure_one

        content = self.get_argument('content', '')
        search = self.get_argument('search', '')
        token = self.get_argument('token', None)
        default_receiver = self.get_argument('receiver', None)

        if glb.token:
            if glb.token != token:
                self.status_code = STATUS_PERMISSION_DENIED
                self.write('Token is missing')
                return
        try:
            search = json.loads(search)
        except ValueError:
            search = search
        try:
            if isinstance(search, dict):
                receiver = ensure_one(
                    glb.wxbot.bot.friends(update=True).search(**search))
            else:
                receiver = ensure_one(
                    glb.wxbot.bot.friends(update=True).search(search))
        except ValueError:
            receiver = None
        if receiver:
            receiver.send_msg(content)
        else:
            msg = '消息发送失败,没有找到接收者。\n[搜索条件]: {0}\n[消息内容]:{1}'.format(
                search, content)
            message = Message(msg, receiver=default_receiver)
            glb.wxbot.send_msg(message)
            _logger.info(msg)
        self.write('Success')
Example #2
0
 def get_group(self, puid=None, name=None):
     try:
         if name:
             return wxpy.ensure_one(self.bot.groups().search(name=name))
         else:
             return wxpy.ensure_one(self.bot.search(puid=puid))
     except:
         error = 'No such group with {}'.format(
             'name {}'.format(name) if name else 'puid {}'.format(puid))
         raise Exception(error)
Example #3
0
def find_person(names):
    bot = wxpy.Bot(
    )  #若是采用from import 则这里可以写成 bot=Bot() 此时Bot()方法已经引入 不用通过模块名来调用
    friends = []
    # 使用异常处理
    for name in names:
        try:
            friend = bot.search(name)
            wxpy.ensure_one(friend)
            friends.append(friend)
        except ValueError:
            print('检索名重复,请重新输入')
        except wxpy.ResponseError as e:
            print(e.err_code, e.err_msg)
    return friends
Example #4
0
    def start_tuling(bot):
        groups = bot.groups(update=True)
        junwei_group = ensure_one(groups.search(GroupNames.JUNWEI))
        morning_group = ensure_one(groups.search(GroupNames.MORNING))

        tianya_group = ensure_one(groups.search('天涯'))
        sunjiaxiao_group = ensure_one(groups.search('孙家小群'))
        sunjiada_group = ensure_one(groups.search('孙家大群'))

        tuling = Tuling(api_key=TuLingConfig.API_KEY)

        @bot.register([junwei_group, morning_group, tianya_group, sunjiaxiao_group, sunjiada_group], TEXT)
        def forward_msg(msg):
            if msg.is_at:
                tuling.do_reply(msg, at_member=True)
Example #5
0
def replay_message(message, friends):
    # 将管理员消息按照#分割,0 为好友名称 1 为消息内容
    rep = message.split('#')

    # 判断是否为查询快递命令
    if '@快递' in rep[0]:
        express = spider.GetExpress(''.join(rep[1:]))
        return express.get_express()
    # 获取好友名称,将@替换掉
    reply_name = rep[0].replace('@', '')

    # 查找人员,返回对应的对象
    replay = friends.search(reply_name)

    # 如果有数据,表示有该好友
    if replay:
        # 获取好友对象
        replay = ensure_one(replay)
        # 放置有多个#在文本中,所有用空字符组合一下消息
        reply_msg = ''.join(rep[1:])
        # 将回复的消息发送给好友
        replay.send_msg(reply_msg)
        # 返回管理员通知消息
        return '禀报小主,信息已成功回复!'

    # 当没有找到还有时,返回通知消息
    else:
        return '禀报小主,小的翻遍花名册,查无此人,请问小主是否记错名字了呢!'
Example #6
0
 def msg_en(self, index):
     # self.bot.self.add()
     # self.bot.self.accept()
     # QtCore.QModelIndex.
     print(index.row())
     row = index.row()
     col1 = index.column()
     if col1 == 0:
         name = index.data()
         name_re = re.search('[(]' + '.*' + '[)]', str(name), re.M | re.I)
         if name_re:
             name = name_re.group().replace('(', '').replace(')', '')
         print(name)
         # print(col1, col2)
         try:
             # print('')
             self.now_msg_friend = wxpy.ensure_one(
                 self.my_friend.search(name))
             if self.now_msg_friend.name == self.bot.self.name:
                 # self.now_msg_friend.add(None)
                 self.now_msg_friend.accept(None)
             self.msg_win = MsgWindow(self)
             self.msg_win.show()
         except ValueError:
             print('Not Found Friend')
         else:
             print(self.now_msg_friend.sex)
Example #7
0
 def remove_members(self, members):
     members_list = [
         wxpy.ensure_one(self.robot.bot.search(puid=puid))
         for puid in members
     ]
     self.get_group(self.puid).remove_members(members_list)
     self.robot.save_config()
Example #8
0
    def __init__(self, wx_bot):
        self.friends = wx_bot.friends()
        self.groups = wx_bot.groups()
        self.mps = wx_bot.mps()
        self.setting_command = [
            '@接收好友消息', '@屏蔽好友消息', '@接收群消息', '@屏蔽群消息', '@关闭公众号', '@接收公众号',
            '@屏蔽', '@接收好友', '@接收群', '@接收公众号'
        ]

        self.administrator = ensure_one(self.friends.search('管理员'))

        # self.msg = msg

        # 初始化各类数据
        self.msg = Message
        self.msg_raw = dict()
        self.sender = chats.group.Group
        self.msg_content = str()
        self.msg_command = str()
        self.msg_command_content = str()
        self.is_mp = bool()
        self.is_friend = bool()
        self.is_group = bool()

        # 获取配置文件
        self.setting = json.load(open('setting.ini', 'r'))
Example #9
0
    def forward_zaobao(bot):
        """
        转发王小二早报
        """
        groups = bot.groups(update=True)

        junwei_group = ensure_one(groups.search(GroupNames.JUNWEI))
        morning_group = ensure_one(groups.search(GroupNames.MORNING))

        wangerxiao = ensure_one(junwei_group.search('赣州 王二小'))

        @bot.register(junwei_group)
        def forward_msg(msg):
            if msg.member == wangerxiao:
                if ZaoBaoService.__is_zaobao__(msg.text):
                    msg.forward(morning_group, prefix='Kinga')
Example #10
0
 def _search_group(self, group_name):
     if self.bot is not None:
         groups = self.bot.groups().search(group_name)
         # groups = self.bot.friends().search(group_name)
         if len(groups) < 1:
             raise RuntimeError("未能找到该微信群组或群组未被添加到通讯录!")
         group = ensure_one(groups)
         self.group = group
     else:
         raise RuntimeError('请先登录微信机器人!')
Example #11
0
 def send(self, remark_name: str, msg: str):
     try:
         fr_list = self.bot.friends().search(remark_name)
         fr = wxpy.ensure_one(fr_list)
         fr.send(msg)
     except Exception:
         print("!!!发送遇到问题!!!请检查 %s 的消息发送是否成功" % remark_name)
         pass
     local_time = str(time.asctime(time.localtime(time.time())))
     print("%s , 成功向 %s 发送消息 :%s " % (local_time, remark_name, msg))
Example #12
0
def reply_with_service_info(customer, bot, vpn_service):
    ip,port,password,expire_on = \
        vpn_service.ip,vpn_service.port,vpn_service.password,\
        vpn_service.expire_on
    expire_on = expire_on.strftime('%Y-%m-%d %H:%M %p')
    receiver = wxpy.ensure_one(bot.friends()\
        .search(user_name=customer.wechat_id))
    receiver.send(u'台湾服务器:{ip},端口:{port},密码:{password};'\
        '到期时间:{expire_on}'
        .format(ip=ip,port=port,password=password,expire_on=expire_on))
Example #13
0
 def get_group_info(self, puid):
     self.update_groups()
     group = wxpy.ensure_one(self.bot.search(puid=puid))
     if group:
         # pl.run_thread_pool([(self.get_avatar, (member,)) for member in group.members], False)
         avater_path = os.path.join(AVA_PATH, '{}.png'.format(group.puid))
         group.get_avatar(avater_path)
         _group = self.find_in_trans(group.puid)
         if _group:
             is_trans = _group.work if self.work else False
             rule_list = [rule.__dict__ for _, rule in _group.rules.items()]
             target_group = [{
                 'name': group.name,
                 'puid': group.puid
             } for group in _group.target_groups()]
             white = _group.white
         else:
             is_trans = False
             rule_list = []
             target_group = []
             white = []
         log.info('发送群{}信息'.format(group.name))
         group_info = {
             'name':
             group.name,
             'avatar':
             avater_path,
             'puid':
             group.puid,
             'member': [{
                 'name':
                 member.name,
                 'puid':
                 member.puid,
                 'pic_path':
                 os.path.join(AVA_PATH, '{}.png'.format(member.puid))
             } for member in group.members],
             'res':
             True,
             'white':
             white,
             'people_num':
             len(group.members),
             'rule':
             rule_list,
             'is_trans':
             is_trans,
             'is_owner':
             group.is_owner,
             'target_group':
             target_group
         }
         return group_info
     else:
         return None
Example #14
0
def auto_reply(msg):
    """ 自动回复 """
    # 固定格式: @[小米9&小米8,2000-4000] 或 @[2000-4000]
    fromuser = ensure_one(bot.search(msg.fromUserName))
    res = re.match(r'\@\[(.*?)\]', msg)
    if res:
        msg = res.group(1)
        msg = msg.replace(",", ",")
        a = msg.split(",")
        if len(a) == 1:
            b = a[0].split("-")
            if len(b) != 2:
                return "价格范围是必要条件且必须符合`0-9999`此格式"
            try:
                ap, bp = int(b[0]), int(b[1])
                if ap > bp:
                    Lprice, Hprice = bp, ap
                else:
                    Lprice, Hprice = ap, bp
            except Exception as e:
                return "价格必须为数值"
            mobiles, prices = [], [Lprice, Hprice]
            User(id=fromuser.puid, care_mobiles=mobiles,
                 care_price=prices).save()
            return """
                恭喜订阅成功! \n
                你关注的手机为: 无限制 \n
                你关注的价格范围为: ¥{} 至 ¥{}这个价格区间
                """.format(Lprice, Hprice)
        elif len(a) == 2:
            b = a[1].split("-")
            if len(b) != 2:
                return "价格范围必须符合`0-9999`此格式"
            try:
                ap, bp = int(b[0]), int(b[1])
                if ap > bp:
                    Lprice, Hprice = bp, ap
                else:
                    Lprice, Hprice = ap, bp
            except Exception as e:
                return "价格必须为数值"
            mobiles, prices = a[0].split("&"), [Lprice, Hprice]
            User(id=fromuser.puid, care_mobiles=mobiles,
                 care_price=prices).save()
            return """
                恭喜订阅成功! \n
                你关注的手机为: {} \n
                你关注的价格范围为: ¥{} 至 ¥{}这个价格区间
                """.format(" | ".join(mobiles), Lprice, Hprice)
        else:
            return "订阅信息必须符合`@[小米9&小米8,2000-4000]或者@[2000-4000]`"
    else:
        return "暂时不支持闲聊功能。。。"
Example #15
0
 def __init__(self):
     print('Please log in by scanning QR code')
     self.bot = wxpy.Bot(cache_path=True,console_qr=True)
     self.bot.enable_puid()
     self.payment_mp = wxpy.ensure_one(self.bot.mps().search(u'微信支付'))
     self.developer = self.bot.friends().search('Han Chen')[0]
     logging.info('setting developer to: {}, with wechat id: {}'\
         .format(self.developer.name, self.developer.user_name))
     self._register_wechat_listeners()
     logging.debug('registered wechat listeners')
     self._start_bot_server()
     logging.debug('started bot server')
Example #16
0
    def admin_cmd(self):

        # 管理员获取帮助信息
        command_content = ['@指令', '指令', '帮助']
        if self.msg_command in command_content:
            self.administrator.send(wx_ai_help)
            return
        # 管理员设置配置文件
        if self.msg_command in self.setting_command:
            self.set_setting()
            return

        # 当以上两条均不符合时,默认为给好友发送消息
        target = self.msg_command.replace('@', '')  # 获取好友名称
        search_friend = self.friends.search(target)  # 查找好友
        search_group = self.groups.search(target)  # 查找群组
        search_mp = self.mps.search(target)  # 查找公众号

        # 判断目标是否为好友/群组/公众号三者之一
        if search_friend or search_group or search_mp:
            if search_friend:
                ensure_one(search_friend).send(self.msg_command_content)

            if search_mp:
                ensure_one(search_mp).send(self.msg_command_content)

            if search_group:
                ensure_one(search_group).send(self.msg_command_content)

            return self.administrator.send('禀报小主,消息已发送至对方')
        else:
            return self.administrator.send(
                '禀报小主,未在您的好友/群组/公众号中查询到此名称,请小主核实后再次尝试哦!')
Example #17
0
def name_to_groupList(group_names, allGroup):
    groups = []
    for name in group_names:
        res, resnum = search_groupName_among_groups(name, allGroup)
        if resnum == 0:
            print('警告:', name, '未找到')
        if resnum > 1:
            print('警告:', name, '匹配多个结果:', res)
            mark = ''
            while mark != 'y' and mark != 'n':
                mark = input('继续(y/n)?')
                if mark == 'n':
                    raise Exception("用户终止程序")
                if mark == '\r':
                    break
                if mark != 'y':
                    print('输入错误,请输入y或n')
            for group in res:
                if group not in groups:
                    groups.append(group)
        if resnum == 1 and res[0] not in groups:
            groups.append(ensure_one(allGroup.search(name)))
    return groups
Example #18
0
def send_greeting(bot: wxpy.Bot, greeting: Greeting):
    people = wxpy.ensure_one(bot.friends().search(puid=greeting.puid))
    print("Sending {} to {}……".format(people.name, greeting.greeting))
    people.send(greeting.greeting)
Example #19
0
 def handle_msg_send(wechat_id, msg):
     user = wxpy.ensure_one(self.bot.friends().search(user_name=wechat_id))
     user.send(msg)
Example #20
0
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 19:09:05 2018

@author: Snailclimb
@description使用图灵机器人自动与指定好友聊天
"""

from wxpy import Bot, Tuling, embed, ensure_one
bot = Bot()
my_friend = ensure_one(bot.search('郑凯'))  #想和机器人聊天的好友的备注
tuling = Tuling(api_key='72bce33cb2b248a199d07175225a5264')


@bot.register(my_friend)  # 使用图灵机器人自动与指定好友聊天
def reply_my_friend(msg):
    tuling.do_reply(msg)


embed()
Example #21
0
def main():
    bot = Bot() 

    my_friend = ensure_one(bot.friends().search('果果爸爸')) 



    @bot.register(my_friend,SHARING) 

    def auto_reply(msg):

        response = requests.get(msg.url) #msg.url为分享的网址

        document = PyQuery(response.text)

        content = document('#js_content').text()

        

        contents = stats_word.stats_text_cn(content,count=10)

        

        result=np.array(contents) 

        word_list=[] 

        number_list=[] 

        for i in range(len(result)): 

            word_list+=[result[i][0]]

            
            number_list+=[int(result[i][1])]

        

        #绘图:

        #为了能在matplotlib中显示中文,需要中文字体的支持

        font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=8)

    

        plt.rcdefaults()

        fig, ax = plt.subplots()

        y_pos = np.arange(len(word_list))



        ax.barh(y_pos, number_list, align='center', color='green', ecolor='black')

        ax.set_yticks(y_pos)

        ax.set_yticklabels(word_list, fontproperties=font)

        ax.invert_yaxis()

        ax.set_xlabel('词频', fontproperties=font)

        ax.set_title('好友分享文章词频统计', fontproperties=font)

        plt.savefig("stats.png") #保存图片

        msg.reply_image("stats.png") #回复图片



    embed() #堵塞线程,保持监听状态
Example #22
0
def show_group_members(bot, group_name):
    group = ensure_one(bot.groups(update=True).search(group_name))
    for member in group.members:
        print("name:%s, nick_name:%s, puid:%s" %
              (member.name, member.nick_name, member.puid))
Example #23
0
from wxpy import Bot, embed, ensure_one  # 微信机器人
import os
import codecs
import json

bot = Bot()
sex_dict = {}
sex_dict['0'] = "其他"
sex_dict['1'] = "男"
sex_dict['2'] = "女"
department_group = ensure_one(bot.groups().search('我们运维部'))
# 通常可用在查找聊天对象时,确保查找结果的唯一性,并直接获取唯一项
# 定位部门群
manager = ensure_one(
    department_group.search(nick_name='龙'))  # 定位部门经理,nick_name(精准名称)


def download_images(friend_list):  # 下载好友头像
    image_dir = 'info/' + bot.self.name + '/images/'
    for myfriend in friend_list:
        print('正在保存 %s 的头像...' % myfriend['NickName'])
        image_name = str(myfriend['NickName']) + '.jpg'
        img = bot.core.get_head_img(userName=myfriend["UserName"])
        with open(image_dir + image_name, 'wb') as file:
            file.write(img)


def save_data(frined_list):
    out_file_name = 'data/myfriends.json'
    with codecs.open(out_file_name, 'w', encoding='utf-8') as json_file:
        json_file.write(json.dumps(frined_list, ensure_ascii=False, indent=4))
import threading
from .config import wechat_mp
import time
from logzero import logger
import sys
r = '[\s+\.\!\/_,$%^*(+\"\']+|[+——!,。?、~@#¥%……&*()“”]+'
r2 = '(?<!/)&'

messages = []

# def qrcode_wechat(uuid, status, qrcode):
#     with open('wxlogin.png', 'wb') as f:
#         f.write(qrcode)

bot = Bot(cache_path=True, console_qr=1)
target = [ensure_one(bot.search(x)) for x in wechat_mp]


def run_wechat():
    @bot.register(target, SHARING)
    def handle_receive_msg(msg):
        global messages
        try:
            answer = minidom.parseString(msg.raw['Content'].replace(
                '\x01',
                '&')).getElementsByTagName('des')[0].firstChild.nodeValue
            if answer:
                messages.append(answer)
        except:
            pass
Example #25
0
#!/usr/bin/env python3
"""简单地在两个微信群中同步消息
"""
import wxpy

wechat = wxpy.Bot()

groups = wechat.groups()

G1 = wxpy.ensure_one(groups.search("生物信息学群"))
G2 = wxpy.ensure_one(groups.search("生物信息学2群"))
F_groups = [G1, G2]


@wechat.register(F_groups, except_self=False)
def sync_my_groups(msg):
    wxpy.sync_message_in_groups(msg, F_groups)


wxpy.embed(banner="堵塞微信,直至手动结束")