社羣營銷 - 程序自動發淘寶商品消息到微信羣 案例展示

話不多說,開始分享乾貨,歡迎討論!QQ微信同號: 6550523

一、背景:

有一個做淘寶營銷的小夥伴兒找到我,希望能幫他實現淘寶商品自動羣發到微信,減少他手下員工的工作量(畢竟都是複製轉發的活,又繁瑣又辛苦),給老闆點贊~,我也想要這樣的老闆,哈哈。

 

二、設計思路如下:

1.python flask 服務器,HTTP API形式接收任意淘寶、天貓、京東、拼多多等商品信息。

2.將商品信息轉發到指定的微信羣(使用JSON配置),實現自動化社羣營銷。

3.非微信Web版,無登錄限制。

 

三、功能實現:

上代碼 , web服務器模塊:

import sys
import threading
import time
import traceback
from flask import Flask, json
from flask import request
import wechat_qq
from mylog import logger
import click
import wx
import wx.adv


global g_group
app_flask = Flask(__name__)

# {"data":{"id":"559802945645","imgUrl":"https://img.alicdn.com/bao/uploaded/i3/2726809950/TB2dLIybNTpK1RjSZFMXXbG_VXa_!!2726809950.jpg_80x80.jpg","price":"當前價格:¥900.00","title":"全新正品天能12v150ah蓄電池奇瑞寶雅電動車免維護電池6-EVF-150"},"time":1576508829011,"type":"market","config":{"hz":"300","title":"新頁籤"}}
@app_flask.route('/pushToWechat/<wechat_group>', methods=['GET', 'POST'])
def pushToWechat(wechat_group):
# @app.route('/pushToWechat', methods=['GET', 'POST'])
# def pushToWechat():
    result = {}
    msg = {}
    try:
        # global g_group
        # wechat_group = g_group

        logger.debug("wechat_group %s", wechat_group)
        req_data = request.get_data().decode("utf-8")

        json_data = json.loads(req_data)
        data = json_data.get("data")

        title = data["title"]
        # msg.append(title)
        msg["title"] = "%s" % title
        logger.debug(title)

        tp = json_data.get("type")
        tp_str = ""
        if tp.find("market") >= 0:
            tp_str = "【購物車】"
        elif tp.find("ft") >= 0:
            tp_str = "【足跡】"
        logger.debug("type %s %s" % (tp, tp_str))

        # id = data.get("id")
        nickname = json_data.get("nickname")
        logger.debug("nickname %s " % nickname)
        # msg.append("%s%s"% (tp_str, nickname))
        msg["type_nickname"] = "%s%s"% (tp_str, nickname)


        imgUrl = data.get("imgUrl")
        logger.debug("imgUrl %s", imgUrl)
        msg["imgUrl"] = "%s" % imgUrl

        price_ori = data.get("price")
        price = price_ori
        index = price_ori.find("/")
        if index > 0:
            price = price_ori[0: index]
        # msg.append("【在售價】%s" % price)
        msg["price"] = "【在售價】%s" % price

        tm = json_data.get("time")
        # msg.append("【時間】%s" % time.strftime("%H:%M:%S", time.localtime(time/1000)))
        msg["time"] = "【時間】%s" % time.strftime("%H:%M:%S", time.localtime(tm/1000))

        url = data["url"]
        msg["url"] = "%s" % url
        # msg.append(url)
        logger.debug(url)

        wechat_qq.wechat_send(windowTitle=wechat_group, msgList=msg)
    except Exception as e:
        logger.error(traceback.format_exc())
        print(e)

    return {"ret": 0}

@click.command()
# @click.option('--group', '-g',  prompt='Please enter  wechat group name ', help='')
@click.option('--port', '-p',  default= "5000", prompt='Please enter listen port, default 5000', help='')
@click.option('--debug', '-d',  default = 0 ,  help='For example: 1 or 0 ')
# def run( port , group, debug):
def run( port , debug):
    print(port, debug)
    # global g_group
    # g_group = group
    app_flask.run(host="0.0.0.0", port=port, debug = debug)

#
# if __name__ == '__main__':
#     run()

class MyTaskBarIcon(wx.adv.TaskBarIcon):
    ICON = "logo.ico"  # 圖標地址
    ID_ABOUT = wx.NewId()  # 菜單選項“關於”的ID
    # ID_EXIT = wx.NewId()  # 菜單選項“退出”的ID
    # ID_SHOW_WEB = wx.NewId()  # 菜單選項“顯示頁面”的ID
    TITLE = "推送消息到微信"  # 鼠標移動到圖標上顯示的文字

    def __init__(self):
        wx.adv.TaskBarIcon.__init__(self)
        self.SetIcon(wx.Icon(self.ICON), self.TITLE)  # 設置圖標和標題
        self.Bind(wx.EVT_MENU, self.onAbout, id=self.ID_ABOUT)  # 綁定“關於”選項的點擊事件
        # self.Bind(wx.EVT_MENU, self.onExit, id=self.ID_EXIT)  # 綁定“退出”選項的點擊事件
        # self.Bind(wx.EVT_MENU, self.onShowWeb, id=self.ID_SHOW_WEB)  # 綁定“顯示頁面”選項的點擊事件

    # “關於”選項的事件處理器
    def onAbout(self, event):
        wx.MessageBox('最後更新日期:2019-12-21', "關於")

    # “退出”選項的事件處理器
    def onExit(self, event):
        wx.Exit()


    # “顯示頁面”選項的事件處理器
    def onShowWeb(self, event):
        pass

    # 創建菜單選項
    def CreatePopupMenu(self):
        menu = wx.Menu()
        for mentAttr in self.getMenuAttrs():
            menu.Append(mentAttr[1], mentAttr[0])
        return menu

    # 獲取菜單的屬性元組
    def getMenuAttrs(self):
        return [#('進入程序', self.ID_SHOW_WEB),
                ('關於', self.ID_ABOUT)]
                # ('退出', self.ID_EXIT)]


class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self)
        MyTaskBarIcon()  # 顯示系統托盤圖標
        # run()

        t = threading.Thread(target=run)
        t.start()

    #
    # def __init__(self):
    #     wx.Frame.__init__(self, None)
    #     self.panel = wx.Panel(self, -1)
    #     self.button = wx.Button(self.panel, wx.ID_OK)
    #     self.Bind(wx.EVT_BUTTON, self.onClick, self.button)
    #     print(app_flask)
    #     t = threading.Thread(target=run)
    #     t.start()
        # run()

    #
    # def onClick(self, evt):
    #     dialog = wx.Dialog(self.panel)
    #     rec = dialog.ShowModal()



class MyApp(wx.App):
    def OnInit(self):
        MyFrame()
        return True


if __name__ == "__main__":
    # app = MyApp()
    # app.MainLoop()
    app = wx.App()
    frame = MyFrame()
    frame.Show()
    app.MainLoop()

羣發消息模塊:

# coding = utf-8
import win32gui
import win32api
from threading import Lock

import win32con
import win32clipboard as clipboard
import time
from pynput.mouse import Button, Controller as mController
from pynput.keyboard import Key, Controller as kController
from mylog import *
from PIL import ImageGrab
import image_clipboard

import traceback, threading

mouse = mController()
keyboard = kController()

import win32api,win32gui,win32con
import os
import time
from enum import Enum

class Lan(Enum):
    """
    語言代碼值參考:https://msdn.microsoft.com/en-us/library/cc233982.aspx
    """
    EN = 0x4090409
    ZH = 0x8040804

def change_lan(lan :Lan):
    """
    修改當前激活窗口輸入法
    :param lan: 語言類型
    :return: True 修改成功,False 修改失敗
    """
    # 獲取系統輸入法列表
    hwnd = win32gui.GetForegroundWindow()
    im_list = win32api.GetKeyboardLayoutList()
    im_list = list(map(hex, im_list))

    # 加載輸入法
    if hex(lan.value) not in im_list:
        win32api.LoadKeyboardLayout('0000' + hex(lan.value)[-4:], 1)

    result = win32api.SendMessage(
        hwnd,
        win32con.WM_INPUTLANGCHANGEREQUEST,
        0,
        lan.value)
    if result == 0:
        logger.info('設置 %s 鍵盤 %d (0 == success)!' % (lan.name, result))
    return result


def get_keyboard_status():
    # 獲取鍵盤佈局列表
    im_list = win32api.GetKeyboardLayoutList()
    im_list = list(map(hex, im_list))
    print(im_list)


# 傳入類名,標題,返回tuple(句柄,座標左,座標左頂,座標左右,座標左底)
def findWindow(classname, titlename):
    hwnd = win32gui.FindWindow(classname, titlename)
    if (hwnd != 0):
        left, top, right, bottom = win32gui.GetWindowRect(hwnd)
        return {'hwnd': hwnd, 'left': left, 'top': top, 'right': right, 'bottom': bottom}
    else:
        return 0

def send_line(message):
    keyboard.type(message)  # 程序運行時候,這裏一定要是英文輸入狀態,要不然可能無法發送消息
    with keyboard.pressed(Key.ctrl):
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)

# 發送消息,需要窗口標題,消息內容兩個參數
def wechat_send(windowTitle, msgList):
    # 微信pc端的輸入框都沒有句柄,所以需要通過模擬點擊來獲得焦點.雖然QQ有句柄,但是爲了統一,也用模擬點擊吧
    # 定位QQ(tim)窗口輸入框位置,模擬鼠標點擊來獲得焦點。
    winClass = "ChatWnd"  # 默認是微信消息
    win = findWindow(winClass, windowTitle)
    if 0 == win:
        logger.error("發送消息給[%s]失敗:找不到窗口" % windowTitle)
        return

    hwnd = win['hwnd']
    try:
        # shell = win32com.client.Dispatch("WScript.Shell")
        # shell.SendKeys('%') #發送ALT鍵,ALT鍵使用%號表示
        win32gui.SetForegroundWindow(hwnd) # bool
    except Exception as e:
        logger.error(traceback.format_exc())

    time.sleep(0.002)  # 這裏要緩一下電腦才能反應過來,要不然可能找不到焦點
    change_lan(Lan.EN)
    mutex.acquire()
    inputPos = [win['right'] - 50, win['bottom'] - 50]
    win32api.SetCursorPos(inputPos)  # 定位鼠標到輸入位置

    # 執行左單鍵擊,若需要雙擊則延時幾毫秒再點擊一次即可
    mouse.press(Button.left)
    mouse.release(Button.left)

    send_line(msgList.get("title"))
    send_line(msgList.get("type_nickname"))
    send_line(msgList.get("price"))
    send_line(msgList.get("time"))
    send_line("")
    send_line(msgList.get("url"))

    # 獲取網絡圖片粘貼到剪貼板南極
    try:
        image_clipboard.setImageClipboard(image_clipboard.set_image_txt(msgList))
    except Exception as  e:
        pass
    # image_clipboard.set_image_clipboard(msgList["imgUrl"])
    # image_clipboard.setImageClipboard(image_clipboard.set_image(msgList.get("imgUrl")))

    # 粘貼到微信輸入框
    with keyboard.pressed(Key.ctrl):
        keyboard.press('v')
        keyboard.release('v')

    # 發送消息的快捷鍵是 Alt+s
    with keyboard.pressed(Key.alt):
        keyboard.press('s')
        keyboard.release('s')
    mutex.release()
    logger.info("發送消息給[%s]成功" % windowTitle)


# 發送QQ消息,這裏默認使用 TIM
def qqsend(windowTitle, message):
    win = findWindow("TXGuiFoundation", windowTitle)
    if (win):
        clipboard.OpenClipboard()
        clipboard.EmptyClipboard()
        clipboard.SetClipboardData(win32con.CF_UNICODETEXT, message)
        clipboard.CloseClipboard()
        # 填充消息
        win32gui.SendMessage(win['hand'], 770, 0, 0)
        # 回車發送消息
        win32gui.SendMessage(win['hand'], win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
    else:
        print("發送消息給[%s]失敗" % windowTitle)


# 發送消息不能太頻繁,會被微信封鎖 1秒一個,發1000條被限制
# i = 0
# while True:
#     i = i + 1
#     wechat_send(windowTitle=u"test", message="%d 我是 robot , 我在測試自動發消息 %d" % (i, time.time()))
#     time.sleep(1)
# 英文必須末尾加上\n ,才把備選字符串放入了輸入框\

mutex = threading.Lock()
msgList = list()
msgList.append("迪士尼兒童帽子時尚男女孩加厚加絨寶寶針織帽可愛保暖護耳冬帽")
msgList.append("【用戶id】560184843123")

# wechat_send(windowTitle=u"test", msgList=msgList, imgUrl="" )

四、總結

兩頁代碼實現了這個功能,讓小夥伴兒有更多的時間去做更人性化的工作。

本次分享結束,歡迎討論!QQ微信同號: 6550523

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章