youfou / wxpy

微信机器人 / 可能是最优雅的微信个人号 API ✨✨
http://wxpy.readthedocs.io
MIT License
14.04k stars 2.39k forks source link

提示登录了两次,然后bot啥都获取不到 #10

Closed mu-yu closed 7 years ago

mu-yu commented 7 years ago

如题,如果第二次不登陆,会卡在 Please scan the QR code to log in.


Getting uuid of QR code.
Downloading QR code.
Please scan the QR code to log in.
Please press confirm on your phone.
Loading the contact, this may take a little while.
Login successfully as xxx
Getting uuid of QR code.
Downloading QR code.
Please scan the QR code to log in.
Please press confirm on your phone.
LOG OUT!
Loading the contact, this may take a little while.
Login successfully as xxx
>>> bot.friends()
[]
>>> ```
youfou commented 7 years ago

发下代码?或者说下怎么过来的?

mu-yu commented 7 years ago

index.py

#!/usr/bin/env python3
# coding=utf8

from wxpy import *

from utils import set_interval

bot = Bot()

@bot.register()
def default_auto_reply(msg):
    print(msg)
    Tuling(api_key='xxxxxx').reply_text(msg, at_member=False)

def heart_beat():
    get_wechat_logger().info('💓')

set_interval(heart_beat, 3)
embed()

utils.py

#!/usr/bin/env python3
# coding=utf8
import threading

def set_interval(fn, sec):
    def wrapper_fn():
        fn()
        set_interval(fn, sec)

    t = threading.Timer(sec, wrapper_fn)
    t.start()
    return t

我发现重复登录,并导致登录失效是 heart_beat 导致的…

youfou commented 7 years ago

是的,直接使用 get_wechat_logger() 不指定参数的话,每次都会初始化新的机器人。 这个操作应该在最外层进行,并传入已初始化的机器人对象。

...
bot = Bot()

logger = get_wechat_logger(bot, level=logging.INFO)

@bot.register()
def default_auto_reply(msg):
...

def heart_beat():
    logger.info('💓')
youfou commented 7 years ago

没有其他问题的话,先关闭了