后台登录微信并定时发送消息,消息包括农历、阴历、天气;自动监测是否断线,支持邮箱发送二维码登录;适合于挂在服务器上运行

时间:2022-07-23
本文章向大家介绍后台登录微信并定时发送消息,消息包括农历、阴历、天气;自动监测是否断线,支持邮箱发送二维码登录;适合于挂在服务器上运行,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#coding:utf-8
import requests
from bs4 import BeautifulSoup
import time
import threading
from wxpy import *
import sxtwl
global bot, group
import schedule
import os
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import smtplib

def youxiang(path_pic, content=''):
    msg_from = '2580833660@qq.com'  # 发送方邮箱
    passwd = ''  # 填入发送方邮箱的授权码
    receiver = ['1061700625@qq.com']  # 收件人邮箱
    subject = "请扫码登录微信"  # 主题

    msg = MIMEMultipart('related')
    msg['Subject'] = subject
    msg['From'] = msg_from
    msg['To'] = ";".join(receiver)# 收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
    msgAlternative = MIMEMultipart('alternative')
    msg.attach(msgAlternative)
    mail_msg = content + 'rn' + """<p><img src="cid:image1"></p>"""
    msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
    fp = open(path_pic, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    # 定义图片 ID,在 HTML 文本中引用
    msgImage.add_header('Content-ID', '<image1>')
    msg.attach(msgImage)

    s = smtplib.SMTP_SSL(host='smtp.qq.com', port=465)  # 邮件服务器及端口号
    try:
        s.login(msg_from, passwd)
        s.sendmail(msg_from, receiver, msg.as_string())
        print("邮件已发送成功!")
        time.sleep(5)
    except smtplib.SMTPException:
        print("Error")
    finally:
        s.quit()

def login_callback():
    print("登录成功")

def logout_callback():
    print("退出登录")
    startBot()

def qr_callback(uuid, status, qrcode):
    picDir = os.path.join(os.getcwd(), 'QRcode.png')
    with open(picDir, 'wb') as f:
        f.write(qrcode)
    youxiang(picDir)

def sendMsg(strings):
    global bot, group
    group.send(strings)
    time.sleep(5)

def startBot():
    global bot, group
    bot = Bot(cache_path=True, login_callback=login_callback, logout_callback=logout_callback, qr_callback=qr_callback)
    group = bot.groups().search('麻将组')[0]
    # group = bot.friends().search('静守时光,以待流年')[0]
    print(group)
    bot.join()

def rili():
    # 日历中文索引
    ymc = [u"十一", u"十二", u"正", u"二", u"三", u"四", u"五", u"六", u"七", u"八", u"九", u"十"]
    rmc = [u"初一", u"初二", u"初三", u"初四", u"初五", u"初六", u"初七", u"初八", u"初九", u"初十",
           u"十一", u"十二", u"十三", u"十四", u"十五", u"十六", u"十七", u"十八", u"十九",
           u"二十", u"廿一", u"廿二", u"廿三", u"廿四", u"廿五", u"廿六", u"廿七", u"廿八", u"廿九", u"三十", u"卅一"]
    numCn = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"]

    lunar = sxtwl.Lunar()  # 实例化日历库
    gongli = time.strftime("%Y-%m-%d", time.localtime()).split('-')
    day = lunar.getDayBySolar(int(gongli[0]), int(gongli[1]), int(gongli[2]))
    week = numCn[day.week]

    if day.Lleap:
        nongli = "[润]%s月%s" % (ymc[day.Lmc], rmc[day.Ldi])
    else:
        nongli = "%s月%s" % (ymc[day.Lmc], rmc[day.Ldi])
    return gongli, nongli, week

def weather():
    url = r'http://tianqi.2345.com/zhejiang-zhichengzhen/13222.htm'
    html = requests.get(url)
    html.encoding = 'gb2312'
    soup = BeautifulSoup(html.text, 'lxml')
    weather_only = soup.find('span', class_='data only').get_text().strip()
    wind_force = soup.find('div', class_='wea-about').find('ul', class_='clearfix').find_all('li')[1].get_text().strip()
    emoticon = soup.find('div', class_='emoticon').get_text().strip()
    return weather_only, wind_force, emoticon

def process():
    try:
        gongli, nongli, week = rili()
        weather_only, wind_force, emoticon = weather()
        strings = "【今天】:<%s年%s月%s日,星期%s>rn【农历】:<%s>rn【天气】:%srn%srn【生活小贴士】:%s" % 
                  (gongli[0], gongli[1], gongli[2], week, nongli, weather_only, wind_force, emoticon)
        sendMsg(strings)
        print(strings)
        print("发送完成!")
    except Exception as e:
        print(e)

def prosch():
    schedule.every().day.at("08:00").do(process)
    while True:
        schedule.run_pending()
        time.sleep(5)

def main():
    thread_Bot = threading.Thread(target=startBot)
    thread_prosch = threading.Thread(target=prosch)

    thread_Bot.start()
    thread_prosch.start()

    thread_Bot.join()
    thread_prosch.join()


if __name__ == '__main__':
    main()