Skip to content

Instantly share code, notes, and snippets.

@TTTPOB
Created May 13, 2021 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TTTPOB/aae107d720183bb5a7d4fab21561b1b0 to your computer and use it in GitHub Desktop.
Save TTTPOB/aae107d720183bb5a7d4fab21561b1b0 to your computer and use it in GitHub Desktop.
send message to wecom (企业微信) by phone number
#!/bin/env python3
## the reason why i use urllib is to minimize dependency requiremnts
## the reason i dont user serverchan (https://sc.ftqq.com/) is that i want a multiuser support
from urllib import request
import sys
import json
## Please Change xxxxxx to the value you have
CORPID="xxxxxx"
MSGSECRET="xxxxxx"
PHONE="xxxxxx"
HEADERS={'Content-Type': 'application/json','User-Agent':'fake'}
AGENTID=xxxxxx
## Variable SERVER and TEXT are just to construct the message to be sent, you can modify this part
try:
TEXT=sys.argv[1]
except:
TEXT="done"
SERVER="LLAB"
BASEURL="https://qyapi.weixin.qq.com/cgi-bin/"
## get token
gettoken_url=BASEURL+"gettoken?corpid={0}&corpsecret={1}".format(CORPID,MSGSECRET)
req=request.Request(url=gettoken_url,headers=HEADERS)
token_resp=request.urlopen(req).read().decode(encoding='utf-8')
token_json=json.loads(token_resp)
TOKEN=token_json['access_token']
## get userid by phone
content={
"mobile": PHONE
}
content=json.dumps(content).encode(encoding="utf-8")
getuserid_url=BASEURL+"user/getuserid?access_token={0}".format(TOKEN)
req=request.Request(url=getuserid_url,data=content,headers=HEADERS)
userid_json=json.loads(
request.urlopen(req).read().decode(encoding='utf-8')
)
CHATID=userid_json['userid']
## real send
### construct message
CONTENT="server: "+SERVER+"\n\n"+TEXT
send_url=BASEURL+"message/send?access_token={0}".format(TOKEN)
## change xxxx to your own id
content={
'touser':CHATID,
'msgtype':'text',
'agentid': AGENTID,
'text':{
'content': CONTENT
}
}
content=json.dumps(content).encode(encoding="utf-8")
req=request.Request(url=send_url,data=content,headers=HEADERS)
print(request.urlopen(req).read().decode(encoding='utf-8'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment