#Preview
1.why i wrote this blog
2.Whole article structure
3.General Algorithm
4.specific implementation
5.Demo
6.Plus
PART I
-----------Pass part I-----------
I.CUZ I’d like to ‘water group’, my Nickname is the ‘QQ小冰’. I wanna build a robot for reply message automatic for years.Now I have learnt Cs 4 almost one year.I think I no how to code it with python.
And I search on Baidu,Google as well, there r few passage describing how to build a QQrobot.And I found no article tell me how to catch the QQ’s packages.
So…let’s talk about the article structure.
-----------Pass part I-----------
PART II
I wanna talk about the general algorithm first, and then specific coding and implementation.
U can focus on Part IV, But U’d better get familiar with the GA in Part III
PART III
It’s simply get and send.The difficulties are mostly on ‘send and get message on QQ’
1st we catch the screenshot on screen,CUZ I dont no how to catch the QQ packages.
2nd we translate it to text.With Baidu AI’s API
3rd when after processing, we send the text to Tencent robot API,and get response.
4th we find the target window by win32gui,and then automatic write the response message, and simulate clicking ‘Enter’
then it’s done
we add a loop, and let it sleep 1s every loop.
PART IV
The Pro Structure
1.QQbots.py#this module is the main module
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 17 15:12:56 2020
@author: Showi
QQ chatbot
"""
import get1
import Send
#from robot import ask
import time
from robot02 import ask
#to_who = input('选一个群:')#要提前设定发给谁
to_who = '机客公会总部'
#yourname = input('你的群备注:')
yourname = 'QQ小猪'
#li = []
while(True):
mesList = get1.getMes()#获取了消息
for i in mesList:
print('#',i)
# print(li)
# if i in li:
# continue
print('#',('@'+yourname) not in i)
isInside = '@'+yourname
if isInside not in i:
continue
i = i.split(isInside)[1]
responseMes = ask(i)
# li.append(responseMes)
print('#',responseMes)
Send.send_qq(to_who,responseMes)
time.sleep(1)
2.get1.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 17 14:20:20 2020
@author: Showi
catch the screenshot
and translate it to text
"""
import time
from p2text import p2text
from PIL import ImageGrab, Image
folderpath = 'images'
# 区域截图left, upper, right, lower
def screenRegion():
'''return the position of screenshot'''
try:
left, top = 10, 720
width, height = 500, 667/6 - 20 # iphone6
bbox = (left, top, left + width, top + height)
img = ImageGrab.grab(bbox)
newfilename = "images/{}{}.jpg".format(folderpath,int(time.time() * 1000))
img.save(newfilename)
# img.show()
print("screen saved!")
except Exception as e:
print('error')
print("error:",e)
finally:
return newfilename
def getMes():
'''get the mess,return a string'''
imgPath = screenRegion()
textList = p2text(imgPath)
return textList
3.p2text.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 17 14:20:02 2020
@author: 27879
"""
# encoding:utf-8
import requests
import base64
import os
'''
text recognition
'''
def p2text(imgPath):
'''picture to text
in:image
out:text
'''
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
# open the image with file
f = open(imgPath, 'rb')
img = base64.b64encode(f.read())
f.close()
params = {"image":img}
access_token = '[Your Access_tocken]'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
if response:
recMes = (response.json())['words_result']
recMesText = []
for one in recMes:
recMesText.append(one['words'])
os.remove(imgPath)#release space
return(recMesText)
4.robot02.py#I use another robot before,Tianxin robot . I found Tencent’s robot better
# -*- coding: utf-8 -
'''
Created on Sun Jan 19 19:48:35 20
@author: 27879
'''
import requests
import md5sign
def get_content(plus_item):
url = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat"
#get prameters
plus_item = plus_item.encode('utf-8')
payload = md5sign.get_params(plus_item)
# r = requests.get(url,params=payload)
r = requests.post(url,data=payload)
return r.json()["data"]["answer"]
#if __name__ == '__main__':
# while True:
# comment = input('I:')
# if comment == 'quit()':
# break
# answer=get_content(comment)
# print('Resp:'+answer)
def ask(question):
comment = question
answer=get_content(comment)
return answer
5.md5sign.py#you should get the app id and app key yourself
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 19 19:47:52 2020
@author: not showi
"""
import hashlib
import time
import random
import string
from urllib.parse import quote
def curlmd5(src):
m = hashlib.md5(src.encode('UTF-8'))
return m.hexdigest().upper()
def get_params(plus_item):
# 请求时间戳(秒级),用于防止请求重放(保证签名5分钟有效)
t = time.time()
time_stamp=str(int(t))
# 请求随机字符串,用于保证签名不可预测
nonce_str = ''.join(random.sample(string.ascii_letters + string.digits, 10))
# 应用标志,这里修改成自己的id和key
app_id = '[get it yourself]'
app_key = '[get it yourself]'
params = {'app_id':app_id,
'question':plus_item,
'time_stamp':time_stamp,
'nonce_str':nonce_str,
'session':'10000'
}
sign_before = ''
# 要对key排序再拼接
for key in sorted(params):
# 键值拼接过程value部分需要URL编码,URL编码算法用大写字母,例如%E8。quote默认大写。
sign_before += '{}={}&'.format(key,quote(params[key], safe=''))
# 将应用密钥以app_key为键名,拼接到字符串sign_before末尾
sign_before += 'app_key={}'.format(app_key)
# 对字符串sign_before进行MD5运算,得到接口请求签名
sign = curlmd5(sign_before)
params['sign'] = sign
return params
6.Send.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 9 19:37:49 2020
@author: Showi
"""
import win32gui
import win32con
import win32clipboard as w
def getText():
"""get the text ion clipboard"""
w.OpenClipboard()
d = w.GetClipboardData(win32con.CF_UNICODETEXT)
w.CloseClipboard()
return d
def setText(aString):
"""set clipboard text"""
w.OpenClipboard()
w.EmptyClipboard()
w.SetClipboardData(win32con.CF_UNICODETEXT, aString)
w.CloseClipboard()
def send_qq(to_who, msg):
"""send qq message
to_who:whi u wanna send to
msg:the message u wanna send
"""
# write the text to clipboard
setText(msg)
# catch the QQ window
try:
print('Successfully call')
qq = win32gui.FindWindow(None, to_who)
except:
print('#Failed to find window')
# trasnform the text from clipboard to window
win32gui.SendMessage(qq, 258, 22, 2080193)
win32gui.SendMessage(qq, 770, 0, 0)
# simulation pressing Enter
win32gui.SendMessage(qq, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
win32gui.SendMessage(qq, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
=ok_now=
PART IIV Demo
PartIIIV Plus
1.you should open the dialog window,and the to_who should be the same as the window shows.
2.there should be lots of bugs.CUZ I am LAJI
3.I leant and reference from a few csdn blogs and other blogs.thanks.And if i infringe anybody, tell me and I’ll change it.
4.the program should be modified.But I gotta go.