-
Notifications
You must be signed in to change notification settings - Fork 989
Expand file tree
/
Copy pathclient.py
More file actions
1302 lines (1144 loc) · 41.6 KB
/
Copy pathclient.py
File metadata and controls
1302 lines (1144 loc) · 41.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import time
import requests
import urllib.parse
from requests.compat import json as _json
from werobot.utils import to_text
from werobot.replies import Article
class ClientException(Exception):
pass
def check_error(json):
"""
检测微信公众平台返回值中是否包含错误的返回码。
如果返回码提示有错误,抛出一个 :class:`ClientException` 异常。否则返回 True 。
"""
if "errcode" in json and json["errcode"] != 0:
raise ClientException("{}: {}".format(json["errcode"], json["errmsg"]))
return json
def _build_send_data(msg_type, content):
"""
编译群发参数
:param msg_type: 群发类型,图文消息为 mpnews,文本消息为 text,语音为 voice,音乐为 music,图片为 image,视频为 video,卡券为 wxcard。
:param content: 群发内容。
:return: 群发参数。
"""
send_data = {}
send_data['msgtype'] = msg_type
if msg_type in ['mpnews', 'voice', 'music', 'image']:
send_data[msg_type] = {'media_id': content}
elif msg_type == 'video':
send_data['mpvideo'] = {'media_id': content}
send_data['msgtype'] = 'mpvideo'
elif msg_type == 'text':
send_data['text'] = {'content': content}
elif msg_type == 'wxcard':
send_data['wxcard'] = {'card_id': content}
else:
send_data['text'] = {'content': content}
send_data['msgtype'] = 'text'
return send_data
class Client(object):
"""
微信 API 操作类
通过这个类可以方便的通过微信 API 进行一系列操作,比如主动发送消息、创建自定义菜单等
"""
def __init__(self, config):
self.config = config
self._token = None
self.token_expires_at = None
@property
def appid(self):
return self.config.get("APP_ID", None)
@property
def appsecret(self):
return self.config.get("APP_SECRET", None)
@staticmethod
def _url_encode_files(file):
if hasattr(file, "name"):
file = (urllib.parse.quote(file.name), file)
return file
def request(self, method, url, **kwargs):
if "params" not in kwargs:
kwargs["params"] = {"access_token": self.token}
if isinstance(kwargs.get("data", ""), dict):
body = _json.dumps(kwargs["data"], ensure_ascii=False)
body = body.encode('utf8')
kwargs["data"] = body
r = requests.request(method=method, url=url, **kwargs)
r.raise_for_status()
r.encoding = "utf-8"
json = r.json()
if check_error(json):
return json
def get(self, url, **kwargs):
return self.request(method="get", url=url, **kwargs)
def post(self, url, **kwargs):
if "files" in kwargs:
# Although there is only one key "media" possible in "files" now,
# we decide to check every key to support possible keys in the future
# Fix chinese file name error #292
kwargs["files"] = dict(
zip(
kwargs["files"],
map(self._url_encode_files, kwargs["files"].values())
)
)
return self.request(method="post", url=url, **kwargs)
def grant_token(self):
"""
获取 Access Token。
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/token",
params={
"grant_type": "client_credential",
"appid": self.appid,
"secret": self.appsecret
}
)
def get_access_token(self):
"""
判断现有的token是否过期。
用户需要多进程或者多机部署可以手动重写这个函数
来自定义token的存储,刷新策略。
:return: 返回token
"""
if self._token:
now = time.time()
if self.token_expires_at - now > 60:
return self._token
json = self.grant_token()
self._token = json["access_token"]
self.token_expires_at = int(time.time()) + json["expires_in"]
return self._token
@property
def token(self):
return self.get_access_token()
def get_ip_list(self):
"""
获取微信服务器IP地址。
:return: 返回的 JSON 数据包
"""
return self.get(url="https://api.weixin.qq.com/cgi-bin/getcallbackip")
def create_menu(self, menu_data):
"""
创建自定义菜单::
client.create_menu({
"button":[
{
"type":"click",
"name":"今日歌曲",
"key":"V1001_TODAY_MUSIC"
},
{
"type":"click",
"name":"歌手简介",
"key":"V1001_TODAY_SINGER"
},
{
"name":"菜单",
"sub_button":[
{
"type":"view",
"name":"搜索",
"url":"http://www.soso.com/"
},
{
"type":"view",
"name":"视频",
"url":"http://v.qq.com/"
},
{
"type":"click",
"name":"赞一下我们",
"key":"V1001_GOOD"
}
]
}
]})
:param menu_data: Python 字典
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/menu/create",
data=menu_data
)
def get_menu(self):
"""
查询自定义菜单。
:return: 返回的 JSON 数据包
"""
return self.get("https://api.weixin.qq.com/cgi-bin/menu/get")
def delete_menu(self):
"""
删除自定义菜单。
:return: 返回的 JSON 数据包
"""
return self.get("https://api.weixin.qq.com/cgi-bin/menu/delete")
def create_custom_menu(self, menu_data, matchrule):
"""
创建个性化菜单::
button = [
{
"type":"click",
"name":"今日歌曲",
"key":"V1001_TODAY_MUSIC"
},
{
"name":"菜单",
"sub_button":[
{
"type":"view",
"name":"搜索",
"url":"http://www.soso.com/"
},
{
"type":"view",
"name":"视频",
"url":"http://v.qq.com/"
},
{
"type":"click",
"name":"赞一下我们",
"key":"V1001_GOOD"
}]
}]
matchrule = {
"group_id":"2",
"sex":"1",
"country":"中国",
"province":"广东",
"city":"广州",
"client_platform_type":"2",
"language":"zh_CN"
}
client.create_custom_menu(button, matchrule)
:param menu_data: 如上所示的 Python 字典
:param matchrule: 如上所示的匹配规则
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/menu/addconditional",
data={
"button": menu_data,
"matchrule": matchrule
}
)
def delete_custom_menu(self, menu_id):
"""
删除个性化菜单。
:param menu_id: 菜单的 ID
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/menu/delconditional",
data={"menuid": menu_id}
)
def match_custom_menu(self, user_id):
"""
测试个性化菜单匹配结果。
:param user_id: 要测试匹配的用户 ID
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/menu/trymatch",
data={"user_id": user_id}
)
def get_custom_menu_config(self):
"""
获取自定义菜单配置接口。
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info"
)
def add_custom_service_account(self, account, nickname, password):
"""
添加客服帐号。
:param account: 客服账号的用户名
:param nickname: 客服账号的昵称
:param password: 客服账号的密码
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/customservice/kfaccount/add",
data={
"kf_account": account,
"nickname": nickname,
"password": password
}
)
def update_custom_service_account(self, account, nickname, password):
"""
修改客服帐号。
:param account: 客服账号的用户名
:param nickname: 客服账号的昵称
:param password: 客服账号的密码
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/customservice/kfaccount/update",
data={
"kf_account": account,
"nickname": nickname,
"password": password
}
)
def delete_custom_service_account(self, account, nickname, password):
"""
删除客服帐号。
:param account: 客服账号的用户名
:param nickname: 客服账号的昵称
:param password: 客服账号的密码
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/customservice/kfaccount/del",
data={
"kf_account": account,
"nickname": nickname,
"password": password
}
)
def upload_custom_service_account_avatar(self, account, avatar):
"""
设置客服帐号的头像。
:param account: 客服账号的用户名
:param avatar: 头像文件,必须是 jpg 格式
:return: 返回的 JSON 数据包
"""
return self.post(
url="http://api.weixin.qq.com/customservice/kfaccount/uploadheadimg",
params={
"access_token": self.token,
"kf_account": account
},
files={"media": avatar}
)
def get_custom_service_account_list(self):
"""
获取所有客服账号。
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/customservice/getkflist"
)
def get_online_custom_service_account_list(self):
"""
获取状态为"在线"的客服账号列表。
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist"
)
def upload_media(self, media_type, media_file):
"""
上传临时多媒体文件。
:param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
:param media_file: 要上传的文件,一个 File-object
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/media/upload",
params={
"access_token": self.token,
"type": media_type
},
files={"media": media_file}
)
def download_media(self, media_id):
"""
下载临时多媒体文件。
:param media_id: 媒体文件 ID
:return: requests 的 Response 实例
"""
return requests.get(
url="https://api.weixin.qq.com/cgi-bin/media/get",
params={
"access_token": self.token,
"media_id": media_id
}
)
def add_news(self, articles):
"""
新增永久图文素材::
articles = [{
"title": TITLE,
"thumb_media_id": THUMB_MEDIA_ID,
"author": AUTHOR,
"digest": DIGEST,
"show_cover_pic": SHOW_COVER_PIC(0 / 1),
"content": CONTENT,
"content_source_url": CONTENT_SOURCE_URL
}
# 若新增的是多图文素材,则此处应有几段articles结构,最多8段
]
client.add_news(articles)
:param articles: 如示例中的数组
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/material/add_news",
data={"articles": articles}
)
def upload_news_picture(self, file):
"""
上传图文消息内的图片。
:param file: 要上传的文件,一个 File-object
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/media/uploadimg",
params={"access_token": self.token},
files={"media": file}
)
def upload_permanent_media(self, media_type, media_file):
"""
上传其他类型永久素材。
:param media_type: 媒体文件类型,分别有图片(image)、语音(voice)和缩略图(thumb)
:param media_file: 要上传的文件,一个 File-object
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/material/add_material",
params={
"access_token": self.token,
"type": media_type
},
files={"media": media_file}
)
def upload_permanent_video(self, title, introduction, video):
"""
上传永久视频。
:param title: 视频素材的标题
:param introduction: 视频素材的描述
:param video: 要上传的视频,一个 File-object
:return: requests 的 Response 实例
"""
return requests.post(
url="https://api.weixin.qq.com/cgi-bin/material/add_material",
params={
"access_token": self.token,
"type": "video"
},
data={
"description": _json.dumps(
{
"title": title,
"introduction": introduction
},
ensure_ascii=False
).encode("utf-8")
},
files={"media": video}
)
def download_permanent_media(self, media_id):
"""
获取永久素材。
:param media_id: 媒体文件 ID
:return: requests 的 Response 实例
"""
return requests.post(
url="https://api.weixin.qq.com/cgi-bin/material/get_material",
params={"access_token": self.token},
data=_json.dumps({
"media_id": media_id
}, ensure_ascii=False).encode("utf-8")
)
def delete_permanent_media(self, media_id):
"""
删除永久素材。
:param media_id: 媒体文件 ID
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/material/del_material",
data={"media_id": media_id}
)
def update_news(self, update_data):
"""
修改永久图文素材::
update_data = {
"media_id":MEDIA_ID,
"index":INDEX,
"articles": {
"title": TITLE,
"thumb_media_id": THUMB_MEDIA_ID,
"author": AUTHOR,
"digest": DIGEST,
"show_cover_pic": SHOW_COVER_PIC(0 / 1),
"content": CONTENT,
"content_source_url": CONTENT_SOURCE_URL
}
}
client.update_news(update_data)
:param update_data: 更新的数据,要包含 media_id(图文素材的 ID),index(要更新的文章在图文消息中的位置),articles(新的图文素材数据)
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/material/update_news",
data=update_data
)
def get_media_count(self):
"""
获取素材总数。
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/material/get_materialcount"
)
def get_media_list(self, media_type, offset, count):
"""
获取素材列表。
:param media_type: 素材的类型,图片(image)、视频(video)、语音 (voice)、图文(news)
:param offset: 从全部素材的该偏移位置开始返回,0表示从第一个素材返回
:param count: 返回素材的数量,取值在1到20之间
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/material/batchget_material",
data={
"type": media_type,
"offset": offset,
"count": count
}
)
def create_group(self, name):
"""
创建分组。
:param name: 分组名字(30个字符以内)
:return: 返回的 JSON 数据包
"""
name = to_text(name)
return self.post(
url="https://api.weixin.qq.com/cgi-bin/groups/create",
data={"group": {
"name": name
}}
)
def get_groups(self):
"""
查询所有分组。
:return: 返回的 JSON 数据包
"""
return self.get("https://api.weixin.qq.com/cgi-bin/groups/get")
def get_group_by_id(self, openid):
"""
查询用户所在分组。
:param openid: 用户的OpenID
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/groups/getid",
data={"openid": openid}
)
def update_group(self, group_id, name):
"""
修改分组名。
:param group_id: 分组 ID,由微信分配
:param name: 分组名字(30个字符以内)
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/groups/update",
data={"group": {
"id": int(group_id),
"name": to_text(name)
}}
)
def move_user(self, user_id, group_id):
"""
移动用户分组。
:param user_id: 用户 ID,即收到的 `Message` 的 source
:param group_id: 分组 ID
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/groups/members/update",
data={
"openid": user_id,
"to_groupid": group_id
}
)
def move_users(self, user_id_list, group_id):
"""
批量移动用户分组。
:param user_id_list: 用户 ID 的列表(长度不能超过50)
:param group_id: 分组 ID
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate",
data={
"openid_list": user_id_list,
"to_groupid": group_id
}
)
def delete_group(self, group_id):
"""
删除分组。
:param group_id: 要删除的分组的 ID
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/groups/delete",
data={"group": {
"id": group_id
}}
)
def remark_user(self, user_id, remark):
"""
设置备注名。
:param user_id: 设置备注名的用户 ID
:param remark: 新的备注名,长度必须小于30字符
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/user/info/updateremark",
data={
"openid": user_id,
"remark": remark
}
)
def get_user_info(self, user_id, lang="zh_CN"):
"""
获取用户基本信息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/user/info",
params={
"access_token": self.token,
"openid": user_id,
"lang": lang
}
)
def get_users_info(self, user_id_list, lang="zh_CN"):
"""
批量获取用户基本信息。
:param user_id_list: 用户 ID 的列表
:param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/user/info/batchget",
data={
"user_list": [
{
"openid": user_id,
"lang": lang
} for user_id in user_id_list
]
}
)
def get_followers(self, first_user_id=None):
"""
获取关注者列表
详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=获取关注者列表
:param first_user_id: 可选。第一个拉取的OPENID,不填默认从头开始拉取
:return: 返回的 JSON 数据包
"""
params = {"access_token": self.token}
if first_user_id:
params["next_openid"] = first_user_id
return self.get(
"https://api.weixin.qq.com/cgi-bin/user/get", params=params
)
def send_text_message(self, user_id, content, kf_account=None):
"""
发送文本消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param content: 消息正文
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
data = {
"touser": user_id,
"msgtype": "text",
"text": {
"content": content
}
}
if kf_account is not None:
data['customservice'] = {'kf_account': kf_account}
return self.post(
url="https://api.weixin.qq.com/cgi-bin/message/custom/send",
data=data
)
def send_image_message(self, user_id, media_id, kf_account=None):
"""
发送图片消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 图片的媒体ID。 可以通过 :func:`upload_media` 上传。
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
data = {
"touser": user_id,
"msgtype": "image",
"image": {
"media_id": media_id
}
}
if kf_account is not None:
data['customservice'] = {'kf_account': kf_account}
return self.post(
url="https://api.weixin.qq.com/cgi-bin/message/custom/send",
data=data
)
def send_voice_message(self, user_id, media_id, kf_account=None):
"""
发送语音消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 发送的语音的媒体ID。 可以通过 :func:`upload_media` 上传。
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
data = {
"touser": user_id,
"msgtype": "voice",
"voice": {
"media_id": media_id
}
}
if kf_account is not None:
data['customservice'] = {'kf_account': kf_account}
return self.post(
url="https://api.weixin.qq.com/cgi-bin/message/custom/send",
data=data
)
def send_video_message(
self,
user_id,
media_id,
title=None,
description=None,
kf_account=None
):
"""
发送视频消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 发送的视频的媒体ID。 可以通过 :func:`upload_media` 上传。
:param title: 视频消息的标题
:param description: 视频消息的描述
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
video_data = {
"media_id": media_id,
}
if title:
video_data["title"] = title
if description:
video_data["description"] = description
data = {"touser": user_id, "msgtype": "video", "video": video_data}
if kf_account is not None:
data['customservice'] = {'kf_account': kf_account}
return self.post(
url="https://api.weixin.qq.com/cgi-bin/message/custom/send",
data=data
)
def send_music_message(
self,
user_id,
url,
hq_url,
thumb_media_id,
title=None,
description=None,
kf_account=None
):
"""
发送音乐消息。
注意如果你遇到了缩略图不能正常显示的问题, 不要慌张; 目前来看是微信服务器端的问题。
对此我们也无能为力 ( `#197 <https://github.com/whtsky/WeRoBot/issues/197>`_ )
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param url: 音乐链接
:param hq_url: 高品质音乐链接,wifi环境优先使用该链接播放音乐
:param thumb_media_id: 缩略图的媒体ID。 可以通过 :func:`upload_media` 上传。
:param title: 音乐标题
:param description: 音乐描述
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
music_data = {
"musicurl": url,
"hqmusicurl": hq_url,
"thumb_media_id": thumb_media_id
}
if title:
music_data["title"] = title
if description:
music_data["description"] = description
data = {"touser": user_id, "msgtype": "music", "music": music_data}
if kf_account is not None:
data['customservice'] = {'kf_account': kf_account}
return self.post(
url="https://api.weixin.qq.com/cgi-bin/message/custom/send",
data=data
)
def send_article_message(self, user_id, articles, kf_account=None):
"""
发送图文消息::
articles = [
{
"title":"Happy Day",
"description":"Is Really A Happy Day",
"url":"URL",
"picurl":"PIC_URL"
},
{
"title":"Happy Day",
"description":"Is Really A Happy Day",
"url":"URL",
"picurl":"PIC_URL"
}
]
client.send_acticle_message("user_id", acticles)
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param articles: 一个包含至多8个 article 字典或 Article 对象的数组
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
if isinstance(articles[0], Article):
formatted_articles = []
for article in articles:
result = article.args
result["picurl"] = result.pop("img")
formatted_articles.append(result)
else:
formatted_articles = articles
data = {
"touser": user_id,
"msgtype": "news",
"news": {
"articles": formatted_articles
}
}
if kf_account is not None:
data['customservice'] = {'kf_account': kf_account}
return self.post(
url="https://api.weixin.qq.com/cgi-bin/message/custom/send",
data=data
)
def send_news_message(self, user_id, media_id, kf_account=None):
"""
发送永久素材中的图文消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 媒体文件 ID
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
data = {
"touser": user_id,
"msgtype": "mpnews",
"mpnews": {
"media_id": media_id
}
}
if kf_account is not None:
data['customservice'] = {'kf_account': kf_account}
return self.post(
url="https://api.weixin.qq.com/cgi-bin/message/custom/send",
data=data
)
def send_miniprogrampage_message(
self,
user_id,
title,
appid,
pagepath,
thumb_media_id,
kf_account=None
):
"""
发送小程序卡片(要求小程序与公众号已关联)
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param title: 小程序卡片的标题
:param appid: 小程序的 appid,要求小程序的 appid 需要与公众号有关联关系
:param pagepath: 小程序的页面路径,跟 app.json 对齐,支持参数,比如 pages/index/index?foo=bar
:param thumb_media_id: 小程序卡片图片的媒体 ID,小程序卡片图片建议大小为 520*416
:param kf_account: 需要以某个客服帐号来发消息时指定的客服账户
:return: 返回的 JSON 数据包
"""
data = {
"touser": user_id,
"msgtype": "miniprogrampage",
"miniprogrampage": {
"title": title,
"appid": appid,
"pagepath": pagepath,
"thumb_media_id": thumb_media_id
}
}
if kf_account is not None:
data["customservice"] = {"kf_account": kf_account}
return self.post(
url="https://api.weixin.qq.com/cgi-bin/message/custom/send",
data=data
)