import
requests
import
hashlib
import
base64
class
WeChatBot:
def
__init__(
self
,key):
self
.key
=
key
self
.wxurl
=
'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key='
+
key
def
send_file(
self
,name,filepath):
fl
=
open
(filepath,
'rb'
)
files
=
{
'files'
: (name, fl,
'application/octet-stream'
, {
'Expires'
:
'0'
})}
url
=
'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key='
+
self
.key
+
'&type=file'
req
=
requests.post(url, files
=
files).json()
if
req[
'media_id'
]
is
not
None
:
send_json
=
{
"msgtype"
:
"file"
,
"file"
: {
"media_id"
: req[
'media_id'
]
}
}
requests.post(send_url
=
self
.wxurl, json
=
send_json)
def
send_message(
self
,content
=
'',mentioned_list
=
[],mentioned_mobile_list
=
[] ):
data
=
{
"msgtype"
:
"text"
,
"text"
: {
"content"
: content,
"mentioned_list"
:mentioned_list,
"mentioned_mobile_list"
:mentioned_mobile_list
}
}
res
=
requests.post(
self
.wxurl,json
=
data).json()
print
(res)
def
send_img(
self
,filename):
png
=
filename
with
open
(png,
"rb"
) as f:
md
=
hashlib.md5(f.read())
res1
=
md.hexdigest()
with
open
(png,
"rb"
) as f:
base64_data
=
base64.b64encode(f.read())
im_json
=
{
"msgtype"
:
"image"
,
"image"
: {
"base64"
:
str
(base64_data,
'utf-8'
),
"md5"
: res1
}
}
requests.post(
self
.wxurl, json
=
im_json)