def sendwechat(self, wechat_name, wechat_time, wechat_text):
        num = 1
        try:
            bot = wxpy.Bot()
        except:
            Label(self.top, text='微信登陆出错,请核对是否能在微信网页版登录').grid(row=4)

        my_friend = bot.friends().search(wechat_name)[0]
        if wechat_time == 0:
            my_friend.send(wechat_text)
            Label(self.top, text='发送成功').grid(row=4)
        else:
            try:
                while True:
                    my_friend.send(wechat_text)
                    text = '已发送' + str(num) + '条消息'
                    Label(self.top, text=text).grid(row=4)
                    Button(self.top, text='停',
                           command=bot.logout).grid(row=4,
                                                    column=1,
                                                    sticky=E,
                                                    padx=10,
                                                    pady=5)
                    #print(text)
                    num = num + 1
                    time.sleep(wechat_time)
            except AssertionError as f:
                print(f)
                bot.logout()
        bot.logout()
Exemplo n.º 2
0
def main():
    if len(sys.argv) < 2:
        show_help()
        sys.exit(1)

    if ('list' not in sys.argv) and ('send' not in sys.argv):
        show_help()
        sys.exit(1)

    bot = wxpy.Bot(cache_path=True, console_qr=False)
    bot.enable_puid()

    if 'list' in sys.argv:
        greetings = Greetings()

        for friend in bot.friends():
            greetings.append(Greeting(
                name=friend.name,
                puid=friend.puid,
            ))

        with open('friends.json', 'w', encoding='utf8') as f:
            f.write(greetings.toJSON())

    if 'send' in sys.argv:
        greetings = Greetings()
        with open('friends.json', encoding='utf8') as f:
            greetings.fromJSON(f.read())
        for i in greetings:
            try:
                send_greeting(bot, i)
            except Exception as e:
                print(e)
            sleep(0.5)
    wxpy.embed()
Exemplo n.º 3
0
    def __init__(self):
        super(Client, self).__init__()
        wxbot = wxpy.Bot()

        @wxbot.register(wxbot.groups(), wxpy.TEXT)
        def raw_on_group_message(raw_message):
            message = Message(raw_message.text)
            user = User(raw_message.member.name, raw_message.member.wxid)
Exemplo n.º 4
0
 def __init__(self, msg_queue, download_queue):
     self.msg_queue = msg_queue
     self.download_queue = download_queue
     self.bot = wxpy.Bot(cache_path='/tmp/chatlog.cache', console_qr=True)
     self.bot.enable_puid()
     self.friends = [friend.name for friend in self.bot.friends()]
     self.myself = self.friends[0]
     self.china_tz = pytz.timezone(pytz.country_timezones['CN'][0])
Exemplo n.º 5
0
    def login(self):
        self.bot = wxpy.Bot(cache_path=True)
        # self.bot.self.add('123')

        self.bot.messages.max_history = 10000
        self.status = True
        self.friend_list()
        self.runthd = ReceiveMsgThread(self)
        self.runthd.start()
Exemplo n.º 6
0
def wxbot_main():
    while True:
        global wxbot
        wxbot = wxpy.Bot(console_qr=True, cache_path=True)
        wxbot.register(wxpy.Friend)(handle_direct_message)
        wxbot.register(msg_types=wxpy.FRIENDS,
                       enabled=config.auto_accept)(handle_friend_request)
        wxbot.register(wxpy.Group)(handle_msg_all)
        wxbot.join()
        time.sleep(60.0)
Exemplo n.º 7
0
def start():
    global bot
    while True:
        bot = wxpy.Bot(console_qr = getattr(settings, 'console_qr', False),
                       cache_path=getattr(settings, 'cache_file', None))
        for module in settings.install_apps:
            __import__(module)
        Base.metadata.create_all(engine)
        bot.join()
        time.sleep(2)
Exemplo n.º 8
0
    def login(self):
        if not self.loginned and not self.loginning:
            self.loginning = True
            try:
                self.bot = wxpy.Bot(cache_path=PKL_PATH,
                                    qr_path=self.qr_path,
                                    qr_callback=self.qr_callback,
                                    logout_callback=self.logout_callback)
                self.loginned = True
                self.loginning = False
                self.update_groups()
                self.bot.enable_puid(path=PUID_PATH)
            except:
                self.loginning = False
                server_send({'style': 'error'})
                server_send({
                    'style': 'login',
                    'pic_path': self.wx_path,
                    'text': '请点击登录按钮',
                    'status': 0
                })
                os.remove(PKL_PATH)
                return

            if not self.bot.self.name:
                raise Exception
            elif self.name != self.bot.self.name:
                self.clear_config()
                self.name = self.bot.self.name
                self.puid = self.bot.self.puid
                self.avatar_path = os.path.join(AVA_PATH,
                                                '{}.png'.format(self.puid))
                self.bot.self.get_avatar(self.avatar_path)
            else:
                for group in self.trans_groups:
                    try:
                        group.check_puid()
                        group.register()
                    except Exception as e:
                        log.error(e)

            log.info('{}登录成功'.format(self.name))
            server_send({
                'style': 'login',
                'pic_path': self.avatar_path,
                'text': '{}登录成功'.format(self.name),
                'status': 2
            })
            self.save_config()
            self.start()
            for file in os.listdir(SRC_PATH):
                if 'qr' in file:
                    file_path = os.path.join(SRC_PATH, file)
                    if os.path.isfile(file_path):
                        os.remove(file_path)
Exemplo n.º 9
0
 def __init__(self, debugLevel=1, update=True):
     self.debugLevel = debugLevel
     self.path = os.getcwd() + "\\"
     self.wxCachePath = self.path + "cache"
     self.configPath = self.path + "config\\send.py"
     self.bot = wxpy.Bot(cache_path=True)
     self.bot.enable_puid()
     self.blessQ = queue.Queue()
     self.blessReplace = "%!sendname!%"
     if update:
         self.Inition()
Exemplo n.º 10
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')
Exemplo n.º 11
0
 def __init__(self):
     is_save_bot = './bot_saver/'
     bot_temp_name = input('请问你登陆微信的备注是(输入0不缓存):')
     if bot_temp_name == '0':
         is_save_bot = False
     else:
         is_save_bot += bot_temp_name + '.pkl'
     bot = wxpy.Bot(cache_path=is_save_bot,
                    console_qr=False)  # 如果你是linux用户,请把console_qr设置为True或者2
     wx_c = WX_C(bot)
     wx_c.login_callback()
     bot.join()
Exemplo n.º 12
0
def send_pic(names, pic_dir):  # 发送
    ccy = wxpy.Bot()  # 登陆

    for n in names:
        n1 = ccy.friends().search(n)

        if len(n1) == 1:
            n1[0].send_image(pic_dir)
            n1[0].send('程序测试,勿回')
        else:
            print('请核查好友 %s ' % n)

        time.sleep(5)
Exemplo n.º 13
0
def send_info(ripe_info):  # 传入信息列表并发送至对应联系人
    bot = wxpy.Bot()  # 实例化聊天机器人 及登陆一个账号
    for msg in ripe_info:
        fren_name = msg.split('.')[0]  # 取得名字
        f = bot.friends().search(fren_name)  # 搜索好友 获得一个列表(有可能不止一个好友)

        if len(f) == 1:  # 确定只有一个好友时才发送
            f[0].send(msg)
        else:
            print('请核实好友名称:')
            print(fren_name)

        time.sleep(5)  # 设定休眠时间,避免被封号哈哈哈哈
Exemplo n.º 14
0
def wxlogin():
    window.geometry('400x500+400+100')
    login_frame = LoginFrame(window)
    login_frame.pack()
    wxbot = wx.Bot(qr_callback=login_frame.qr_callback,
                   login_callback=login_frame.login_callback,
                   logout_callback=logout_callback)
    wxbot.enable_puid('wxpy_puid.pkl')
    wxbot.core.send_video()
    init_user(wxbot)
    logger.info('%s login', util.filter_unicode(wxbot.self.name))
    login_frame.destroy()
    return wxbot
Exemplo n.º 15
0
def shell_entry():
    import re

    import logging
    import wxpy

    arg_parser = get_arg_parser()
    args = arg_parser.parse_args()

    if not args.bot:
        arg_parser.print_help()
        return

    if args.version:
        print(wxpy.version_details)
        return

    def get_logging_level():
        logging_level = args.logging_level.upper()
        for level in 'CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET':
            if level.startswith(logging_level):
                return getattr(logging, level)
        else:
            return logging.INFO

    logging.basicConfig(level=get_logging_level())

    try:
        bots = dict()
        for name in args.bot:
            if not re.match(r'\w+$', name):
                continue
            cache_path = 'wxpy_{}.pkl'.format(name) if args.cache else None
            bots[name] = wxpy.Bot(cache_path=cache_path, console_qr=args.console_qr)
    except KeyboardInterrupt:
        return

    banner = 'from wxpy import *\n'

    for k, v in bots.items():
        banner += '{}: {}\n'.format(k, v)

    module_members = dict(inspect.getmembers(wxpy))

    embed(
        local=dict(module_members, **bots),
        banner=banner,
        shell=args.shell
    )
Exemplo n.º 16
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
Exemplo n.º 17
0
def run():
    bot = wxpy.Bot(cache_path=True)
    my_friend = bot.friends()  # .search('木', sex=wxpy.MALE)
    friend_status_text = my_friend.stats_text()
    friend_status = my_friend.stats()
    # text = friend_status_text.split("\n")
    sex_a = friend_status['sex'].get(wxpy.MALE, 0)
    sex_b = friend_status['sex'].get(wxpy.FEMALE, 0)
    num_friend = len(my_friend)
    rate_a = sex_a / num_friend
    rate_b = sex_b / num_friend
    labels = ['Male', 'Female', 'Intersex']
    plot_pie_status(labels, sizes=[rate_a, rate_b, 1 - rate_a - rate_b])

    # print(bot.user_details(my_friend))
    pass
Exemplo n.º 18
0
def shell_entry():
    import re

    import logging
    import wxpy

    args = get_args()

    if args.version:
        print(wxpy.version_details)
        return

    level = args.logging_level.lower()
    if level.startswith('d'):
        level = logging.DEBUG
    elif level.startswith('w'):
        level = logging.WARNING
    elif level.startswith('c'):
        level = logging.CRITICAL
    else:
        level = logging.INFO

    logging.getLogger('wxpy').setLevel(level)

    module_members = dict(inspect.getmembers(wxpy))

    try:
        bots = dict()
        for name in args.bot:
            if not re.match(r'\w+$', name):
                continue
            cache_path = 'wxpy_{}.pkl'.format(name) if args.cache else None
            bots[name] = wxpy.Bot(cache_path=cache_path, console_qr=args.console_qr)
    except KeyboardInterrupt:
        return

    banner = 'from wxpy import *\n'

    for k, v in bots.items():
        banner += '{}: {}\n'.format(k, v)

    embed(
        local=dict(module_members, **bots),
        banner=banner,
        shell=args.shell
    )
Exemplo n.º 19
0
def send_msg(ns, ri_msg):  # 判断联系人并发送
    bot = wxpy.Bot()  # 登陆

    for n1 in ns:
        count = 0  # 设置触发器 联系人在csv中找到就触发

        for n2 in ri_msg:  # 在每一个联系人中再建csv姓名循环并比对
            if n1 == n2.split(',')[0]:
                count = 1  # csv中找到 触发
                fre = bot.friends().search(n1)

                if fre == 1:  # 找到唯一好友才发送
                    fre[0].send(n2)
                else:  # 否则需手动核查
                    print('请在微信中核查联系人:')
                    print(n1)

        if not count:  # 未触发就说明csv中无此人信息
            print('名单中无此人:')
            print(n1)
Exemplo n.º 20
0
def main():
    
    message = getWeather()
    print('成功获取天气信息')

#    # 参数hotReload=True实现保持微信网页版登陆状态,下次发送无需再次扫码
#    itchat.auto_login()
#    users=itchat.search_friends('')
#    print(users)
#    userName=users[0]['UserName']
#    ret=itchat.send(msg = message, toUserName = userName)
#    if ret:
#        print("成功发送")
#    else:
#        print("发送失败")
#    time.sleep(3)
#    itchat.logout()
    
    bot=wxpy.Bot()
    my_friend=bot.friends().search('Snall')[0]
    my_friend.send(message[0])
Exemplo n.º 21
0
def main():

    bot = wxpy.Bot()
    data = get_friends_signature(bot)
    bot.logout()
    word_list = []
    for k, v in data.items():
        if not v:
            continue
        word_list.append(clean_str(v))


#    print(word_list)
    img_1 = build_word_colud(word_list, isJieba=False)
    img_2 = build_word_colud(word_list)
    plt.imshow(img_1)
    plt.imshow(img_2)
    plt.show()
    plt.imsave('./result/1.jpg', img_1)
    plt.imsave('./result/2.jpg', img_2)

    pass
Exemplo n.º 22
0
def main():
    bot=wxpy.Bot()
#     # 在 Web 微信中把自己加为好友
#     bot.self.add()
#     bot.self.accept()

# # 发送消息给自己
#     bot.self.send('能收到吗?')
#     embed()
    friends=bot.friends()
    @bot.register(friends, SHARING)
    def handler(msg):
        try:
            logging.info('sharing url=%s',msg.url)
            article=get_article(msg.url)
            result=stats_word.stats_text_cn(article,20)
            image_path=path.join(cwd,'stats.png')
            generate_image(result,image_path)
            msg.reply_image(image_path)
        except Exception as e:
            logging.exception(e)
    embed()
Exemplo n.º 23
0
def main():
    bot = wxpy.Bot()
    #     # 在 Web 微信中把自己加为好友
    #     bot.self.add()
    #     bot.self.accept()

    # # 发送消息给自己
    #     bot.self.send('能收到吗?')
    #     embed()
    friends = bot.friends()

    @bot.register(friends, SHARING)
    def handler(msg):
        try:
            logging.info('sharing url=%s', msg.url)
            article = get_article(msg.url)
            result = stats_word.stats_text_cn(article, 100)
            msg.reply(str(result))
        except Exception as e:
            logging.exception(e)

    embed()
Exemplo n.º 24
0
def bots_add_wechat_groupName(group_name):
    wxbot = wxpy.Bot()
    wxbot.enable_puid()
    wxgroup = wxbot.groups().search(group_name)[0]
    wxbot_receiver = None

    def set_wxbot_receiver(on_receive):
        nonlocal wxbot_receiver
        wxbot_receiver = on_receive

    @wxbot.register(wxgroup, wxpy.TEXT)
    def wxbot_receive_raw(rawmsg):
        print(rawmsg)
        msg = {}
        msg['sender'] = rawmsg.member.name
        msg['sender_id'] = rawmsg.member.puid
        msg['message'] = rawmsg.text
        wxbot_receiver(msg)

    def wxbot_sendmsg(message):
        wxgroup.send(message)

    bots_add(set_wxbot_receiver, wxbot_sendmsg)
Exemplo n.º 25
0
                      '--input',
                      dest="inFile",
                      help="Output file in json format")
    parser.add_option('-o',
                      '--output',
                      dest="outFile",
                      help="Output file in json format")

    (opts, args) = parser.parse_args()

    Records = []
    if opts.inFile:
        with open(opts.inFile, 'r', encoding='utf-8') as jsonFile:
            Records = json.load(jsonFile)

    bot = wxpy.Bot(console_qr=True)

    @bot.register(chats=[bot.self], msg_types=wxpy.SHARING, except_self=False)
    def register_sharing(msg):
        global Records
        print(msg)
        for i in range(0, len(Records)):
            if Records[i]['Text'] == msg.text:
                Records[i] = {
                    'Text':
                    msg.text,
                    'LongUrl':
                    msg.url,
                    'ShortUrl':
                    urllib.request.urlopen(
                        "http://tinyurl.com/api-create.php?url=%s" %
Exemplo n.º 26
0
        print("version: %s" % environment.version)
        sys.exit(0)
    if argv_1 in ["-h", "-H", "-help", "--help"]:
        print(\
'''
double click the exe, with nickname: default
nickname: start with nickname
-v version
-h help
''')
        sys.exit(0)
    nickname = argv[1]

# 初始化bot
login_pkl, puid_pkl = get_pkls_path(nickname, environment.work_dir)
bot = wxpy.Bot(login_pkl)
bot.enable_puid(path=puid_pkl)

# 在 Web 微信中把自己加为好友
# bot.self.add()
# bot.self.accept()

# 发送消息给自己
# bot.self.send('能收到吗?')

# master消息处理
# master = bot.friends().search("master")[0]
master_msg_handler = MasterMsgHandler(bot, [], environment.work_dir)

# 自动回复所有好友(非群)的消息
# 初始化图灵机器人 (API key 申请: http://tuling123.com),这个KEY是我自己的
Exemplo n.º 27
0
from mymodule import stats_word
import requests
import pyquery
import wxpy

bot = wxpy.Bot()
my_friend = bot.friends().search()


@bot.register()
def print_others(msg):
    print(msg)


@bot.register(my_friend, msg_types='Sharing')  #接受分享类消息
def auto_reply(msg):
    response = requests.get(msg.url)  #msg.url为分享的网址
    document = pyquery.PyQuery(response.text)
    content = document('#js_content').text()
    #处理文本
    result = content
    print(result)


wxpy.embed()
Exemplo n.º 28
0
    def run(self):
        self.bot = wxpy.Bot(cache_path=True, console_qr=False)
        self.bot.messages.max_history = MAX_HISTORY
        self.bot.enable_puid('wxpy_puid.pkl')
        self.friends = self.bot.friends()
        self.groups = self.bot.groups()

        print('登录成功!')

        target_friend = self.friends.search(MONITOR_FRIEND_LIST)[0]
        # current_friend = self.friends.search(u'好友昵称', sex=FEMALE, city="好友信息中的城市")[0]
        print('监控对象:', target_friend)

        # todo
        # ====================================================================================
        # 找到好友列表中昵称为“我说”的好友,监控聊天,打印该好友发来的文本消息
        # @self.bot.register(chats=target_friend, except_self=False, msg_types=wxpy.TEXT)
        # def reply_friend(msg):
        #     print('header reply_friend:', msg)
        #     #  ['_get_chat_by_user_name', '_receive_time',
        #     #  'articles', 'bot', 'card', 'chat', 'create_time', 'file_name', 'file_size', 'forward', 'get_file', 'id',
        #     #  'img_height', 'img_width', 'is_at', 'latency', 'location', 'media_id', 'member', 'play_length', 'raw',
        #     #  'receive_time', 'receiver', 'reply', 'reply_file', 'reply_image', 'reply_msg', 'reply_raw_msg',
        #     #  'reply_video', 'sender', 'text', 'type', 'url', 'voice_length']
        #
        #     # print(msg.member, type(msg.sender))
        #     # target_friend.send('我已经截图了,哈哈,你撤回也么有用咯!' + msg.text)
        #     # target_friend.send_image('my_picture.png')
        #     # target_friend.send_video('my_video.mov')
        #     # target_friend.send_file('my_file.zip')
        #     # target_friend.send('@img@my_picture.png')
        #
        #     print('footer reply_friend:', msg)

        target_group = self.groups.search(MONITOR_GROUP_LIST)[0]
        print('监控群组:', target_group)

        # 监控群聊消息,打印群聊中的文本消息
        @self.bot.register(
            chats=target_group,
            msg_types=wxpy.TEXT or wxpy.PICTURE or wxpy.VIDEO or wxpy.MAP or wxpy.CARD or wxpy.SHARING or
                      wxpy.RECORDING or wxpy.ATTACHMENT or wxpy.NOTE
        )
        def reply_group(msg):
            print('header reply_group:', msg)
            # target_group.send('我已经截图了,哈哈,你撤回也么有用咯!' + msg.text)
            print('footer reply_group', msg)

        # 处理撤回消息
        @self.bot.register(except_self=False)
        def handle_receive_msg(msg):
            """
            监听消息
            :param msg: 接收到的消息
            :return:
            """
            try:
                # 原信息数据
                raw = msg.raw

                # raw.get('Status') == 3 个人消息
                # 如果消息的状态码是4  即撤回消息
                if raw.get('Status') == 4:
                    # 如果是群消息
                    if isinstance(msg.chat, wxpy.api.chats.group.Group):
                        # 获取群成员的puid
                        puid = msg.member.puid
                        # 获取发送者的昵称
                        name = msg.member.nick_name
                    # 如果是好友消息
                    elif isinstance(msg.chat, wxpy.api.chats.friend.Friend):
                        # 获取好友的puid
                        puid = msg.chat.puid
                        # 获取好友的昵称
                        name = msg.chat.nick_name

                        # # 获取发送者的puid
                        # puid = msg.sender.puid
                        # # 获取发送者的名称
                        # name = msg.sender.raw['UserName']
                    else:
                        puid = None
                        name = None

                    if puid:
                        # 被撤回消息的msgid的匹配规则
                        msg_id_regex = re.compile('<msgid>(\d+)</msgid>')

                        # 获取被撤回消息的msgid
                        msg_content = msg_id_regex.findall(raw.get('Content'))
                        if msg_content:
                            old_msg_id = msg_content[0]
                        else:
                            old_msg_id = None

                        # 获取该发送者的最后5次的消息记录
                        chat_msgs = self.msgs.get(puid)
                        print(chat_msgs)

                        # 遍历消息记录
                        for chat_msg in chat_msgs[::-1]:
                            # 跳过不是被撤回的信息
                            if str(chat_msg.id) != old_msg_id:
                                continue
                            chat = chat_msg.chat
                            # 如果被撤回的信息是文本信息
                            if chat_msg.type == "Text":
                                # 如果消息长度过长 则不予处理
                                if len(chat_msg.text) >= 150:
                                    warning = "有人炸群咯!!!"
                                    self.bot.file_helper.send('%s %s' % (name, warning))
                                    break
                                # 将此消息转发出来
                                chat_msg.forward(chat, prefix='%s 已截图,哈哈哈,消息内容为:' % name)
    
                            # 如果被撤回的是位置信息
                            elif chat_msg.type == "Map":
                                # 位置信息的匹配规则
                                map_regex = re.compile(r'label="(.+?)"')
                                # 获取位置信息中的位置
                                map = map_regex.findall(chat_msg.raw.get("OriContent"))[0]
                                # 将位置信息发出来
                                msg.reply('%s 已经看到你的位置啦,啦啦啦,位置信息为:【%s】' % (name, map))
                            else:
                                # 获取信息的类型
                                # msg_type = self.msg_types.get(chat_msg.type).encode('utf-8')
                                msg_type = self.msg_types.get(chat_msg.type)
                                # 将信息转发出来
                                chat_msg.forward(chat, prefix='%s 怀孕了也不用怕,我们一起想办法!撤回了一条%s消息,消息内容为:' % (name, msg_type))
                            break
                else:
                    # 如果是群消息
                    if isinstance(msg.chat, wxpy.api.chats.group.Group):
                        # 获取群成员的puid
                        puid = msg.member.puid
                    # 如果是好友消息
                    elif isinstance(msg.chat, wxpy.api.chats.friend.Friend):
                        # 获取好友的puid
                        puid = msg.chat.puid
                    else:
                        puid = None

                    if puid:
                        # 记录消息
                        self.msgs.setdefault(puid, []).append(msg)
                        # 截取消息  保留最大5条记录
                        self.msgs[puid] = self.msgs[puid][-5:]

            except Exception as ex:
                print('error:{}'.format(ex))

        # # 机器人回复
        # @self.bot.register(msg_types=TEXT)
        # def tuling_reply_msg(msg):
        #     print(msg)
        #     sender_username = msg.sender.raw['UserName']
        #     # 输出发送信息的好友或者群聊中的人员信息
        #     print(sender_username)
        #     # 判断是否和我设置的想要自动恢复到人一致如果一致调用tuling进行消息回复
        #     if sender_username == target_friend.raw['UserName']:
        #         # 输出或得到的消息
        #         print(msg)
        #
        #         # # 调用tuling机器人回复消息,并将消息赋值给message
        #         # message = tuling.do_reply(msg)
        #         # # 输出回复消息的内容
        #         # print(message)

        # @self.bot.register()
        # def tuling_reply_msg(msg):
        #     """
        #     自动回复消息
        #     :param msg: 接收到的信息数据
        #     :return: 回复文本
        #     """
        #     # do_reply会自动回复消息并返回消息文本
        #     tu_ling.do_reply(msg)
        #     pass
        # ====================================================================================

        print('正在运行...')

        # 阻塞进程
        # self.bot.join()

        # 使机器人后台运行,并进入交互模式
        wxpy.embed()
Exemplo n.º 29
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 20 01:35:22 2019

@author: chengxin
"""

import wxpy
bot = wxpy.Bot(cache_path=True)

print('123*')
print(bot.friends().search('杨承欣'))
ycx = bot.friends().search('杨承欣')[0]

ycx.send('Hello')


@bot.register(ycx)
def reply_ycx(msg):
    print(msg.text)
    return msg.text


@bot.register(ycx)
def reply_ycx(msg):
    print(msg.text)
    weather = main.reveiveMsg(msg.text)
    print(weather)
    return weather
Exemplo n.º 30
0
text1 = urwid.Text('2345')
text2 = urwid.Text('23333', align = 'right')

filler1 = urwid.Filler(text1)
filler2 = urwid.Filler(text2)

class ChatListItem(urwid.Filler):
    name = None
    text = None

    def __init__(self, name, text):
        self.name = urwid.Text(name)
        self.text = urwid.Text(text, align = 'right')

class ChatListBox(urwid.ListBox):
    def __init__(self, chat_list_item_list):
        widget_list = list()
        for chat_list_item in chat_list_item_list:
            widget_list.append(chat_list_item.name)
            widget_list.append(chat_list_item.text)
            widget_list.append(urwid.Divider('─'))
        widget_list.pop()
        super(ChatListBox, self).__init__(urwid.SimpleListWalker(widget_list))

bot = wxpy.Bot(cache_path=True, console_qr=True)
zhat_list_item_list = list()
for chat in bot.chats():
    chat_list_item_list.append(ChatListItem(chat.raw['RemarkName'], chat.raw['NickName']))
listbox = ChatListBox(chat_list_item_list)
urwid.MainLoop(listbox).run()