Use Python to realize WeChat group sending daily sentence

I have set up three WeChat groups in the four classes I teach, and each group has about 50-90 people. I plan to send bilingual daily sentences to students every day, so that students can not only keep learning English, but also pass on positive energy to them, so as to maintain a positive and promising state in the post-epidemic era. However, from copying the daily sentence of Kingsoft or Haici, to opening WeChat, finding three groups, and copying the information one by one, the process is quite time-consuming and laborious. At that time, I wanted to use the powerful Python to realize the online capture of a sentence every day, find the sender in WeChat, and then send it one by one.

1. Introduction to programming principles

Function: Wechat group sending a sentence of the day on Jinshan or Haici to designated Wechat groups or individuals

  1. tkinter to design program interface
  2. Use requests and BeautifulSoup to get the sentence of the day from Kingsoft PowerWord and HaiCi
  3. Use the exclusive package to control WeChat: wxauto to operate group sending

2. Software Interface Description

Daily sentence group sending software

  1. Save the name of the sending object in names.txt in the current directory, one per line, without spaces before and after. This object name may be a custom name of the group.
  2. Set the check boxes of Kingsoft PowerWord and HaiCi, select one, and click Get Sentence to get a daily sentence. If both are checked, you will get the sentence of the day for both platforms, displayed in the text box.
  3. Click Send to send the content in the text box to the objects in names.txt in batches.

When you need to pay attention, when running the program, WeChat needs to be opened and minimized, otherwise the interface may not be opened automatically.

3. Realize the code

from tkinter import Entry,Button,END,Label,Text,Checkbutton,Tk,StringVar,IntVar
from tkinter import messagebox
from wxauto import WxUtils,WeChat
from tkinter.filedialog import askopenfilename
import requests
from bs4 import BeautifulSoup

root = Tk()
# 设置窗口前段显示
root.wm_attributes('-topmost',1)
#设置居中显示
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
width = 730
height = 420
#size = "%dx%d+%d+%d" % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
size = "%dx%d+%d+%d" % (width, height, 350, 230)
root.geometry(size)
# 设置窗口标题及大小
root.title('每日一句发送器1.0|By Gordon')
#设置接受UI界面中Label和它的位置
var = StringVar()
var.set('Tip:请先选择要发送的微信对象')
url_input=Label(root,textvariable=var,width=32,height=1,font=("微软雅黑",12))
url_input.grid(row=0,column=0,columnspan=5)
# 设置搜索框
t_url = Entry(root,width=50,font=("微软雅黑",12))
t_url.insert(0,"请把发送对象微信名称输入到names.txt, 然后点击打开文件..")
t_url.grid(row=1,column=0,columnspan=4,padx=5)
t_read = Text(root,width=50,height=10,font=("微软雅黑",12))
t_read.grid(row=3,column=0,columnspan=4,padx=5)
checkVar1 = IntVar()
checkVar2 = IntVar()
c1 = Checkbutton(root, text = "金山词霸", font=("微软雅黑",11), variable = checkVar1, onvalue = 1, offvalue = 0, height=1,width = 8) 
c1.grid(row=2,column=0)
c2 = Checkbutton(root, text = "海词", font=("微软雅黑",11), variable = checkVar2, onvalue = 1, offvalue = 0, height=1,width = 8) 
c2.grid(row=2,column=1)
def main():
    def get_txt(filepath): #获取发送对象
        ls=[]
        try:
            with open(filepath,"r",encoding="utf-8") as f:
                ls=[line.strip() for line in f.readlines() if line.strip()!=""]
        except Exception as exc:
            messagebox.showwarning('Warning', f'{exc}')
            t_url.delete(0,END)
        return ls
    
    def b1_prog(event=None): #打开names.txt文件,并显示在Text文本框中
        t_url.delete(0,END)
        t_read.delete("1.0", "end")
        file_path=askopenfilename(title='选择文件',filetypes=[('TXT文件','*.txt')])
        text_list=get_txt(file_path)
        t_url.insert("insert",file_path)
        for i in text_list:
            t_read.insert("insert",i+"\n")
        var.set("以下是您要发送的对象,请核对信息!")
        return file_path
    b1 = Button(root,text="选择对象",width=8,height=1,font=("微软雅黑",12),command=b1_prog)
    b1.grid(row=1,column=4)

    def jinshan():#获取金山词霸每日一句
        url = 'http://open.iciba.com/dsapi/'
        res = requests.get(url)
        content = res.json()['content'] + res.json()['note']
        return content
    def haici():#获取海词每日一句
        url2=r"http://dict.cn"
        resp = requests.get(url2)
        soup = BeautifulSoup(resp.text,"html.parser")
        htm=soup.find("div",class_="daily_sentence")
        sen=htm.text.strip().split("\t\t\t")[2] #split("\n\t")[2].strip()
        return sen
    def get_sentence():# 获取每日一句信息
        msg="每日一句:"
        if checkVar1.get() ==1 and checkVar2.get() ==1:
            t_read.delete("1.0", "end")
            msg=msg+jinshan()+"\n"+haici()
        elif checkVar1.get() ==1 and checkVar2.get() ==0:
            t_read.delete("1.0", "end")
            msg=msg+jinshan()
        elif checkVar1.get() ==0 and checkVar2.get() ==1:
            t_read.delete("1.0", "end")
            msg=msg+haici()
        else:
            messagebox.showwarning("错误信息","请选中金山词霸或者海词")
        return msg
    def b2_prog():# 显示每日一句信息,校对并准备发送。
        msgs=get_sentence()
        for m in msgs:
            t_read.insert('insert',m)
        var.set("以下是您要发送的每日一句,请核对信息!")
    b2 = Button(root,text="获取句子",width=8,height=1,font=("微软雅黑",12),command=b2_prog)
    b2.grid(row=2,column=4)
    def wechat(who,msg):#查询发送对象
        wx = WeChat()
        # 获取会话列表
        wx.GetSessionList()
        for w in who:
            wx.ChatWith(w)  # 打开`文件传输助手`聊天窗口
            wx.SendMsg(msg)  # 向`文件传输助手`发送消息:你好~
    def send_txt(): # 发送信息
        filepath=t_url.get()
        if not filepath.endswith(".txt"):
            messagebox.showwarning("错误信息","请先打开文件!")
        else:
            who=get_txt(filepath)
            msgs=get_sentence()
            t_read.delete("1.0", "end")
            wechat(who,msgs)
            messagebox.showwarning("成功信息","您的信息已经发送成功!")
    b3 = Button(root,text="开始发送",width=8,height=1,font=("微软雅黑",12),command=send_txt)
    b3.grid(row=3,column=4,pady=20)
    root.mainloop()
main()

4. Demonstration video

Python operates WeChat to realize group information sending

Python implements a daily English group WeChat group

5. Future direction

In the future, it will realize the batch WeChat group sending function of multiple files such as text information, documents, videos, audios, etc., to further optimize traffic and improve work efficiency.

If you have any good suggestions, you are welcome to put them forward.

Follow me, a liberal arts student who likes Python programming and English translation, brings you a different learning experience.

 

Guess you like

Origin blog.csdn.net/henanlion/article/details/122462740