Skip to content

Commit

Permalink
增加云贝任务:发布Mlog
Browse files Browse the repository at this point in the history
  • Loading branch information
chen310 committed Dec 14, 2021
1 parent 460eab9 commit 432c5d5
Show file tree
Hide file tree
Showing 3 changed files with 158 additions and 4 deletions.
75 changes: 74 additions & 1 deletion api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import requests
from http.cookiejar import Cookie, LWPCookieJar
from encrypt import encrypted_request
import random
from hashlib import md5

DEFAULT_TIMEOUT = 10

Expand Down Expand Up @@ -225,7 +227,7 @@ def songs_detail(self, ids):
path = "/weapi/v3/song/detail"
params = dict(c=json.dumps([{"id": _id}
for _id in ids]), ids=json.dumps(ids))
return self.request("POST", path, params).get("songs", [])
return self.request("POST", path, params)

# 关注用户
def user_follow(self, id):
Expand Down Expand Up @@ -410,3 +412,74 @@ def signin_progress(self, moduleId):
path = "/weapi/act/modules/signin/v2/progress"
params = dict(moduleId=moduleId)
return self.request("POST", path, params)

def mlog_nos_token(self, filepath):
path = "/weapi/nos/token/whalealloc"
bizKey = ''
for i in range(8):
bizKey += hex(random.randint(0, 15)).replace('0x', '')
_, filename = os.path.split(filepath)
with open(filepath, 'rb') as f:
contents = f.read()
file_md5 = md5(contents).hexdigest()
params = dict(
bizKey=bizKey,
filename=filename,
bucket='yyimgs',
md5=file_md5,
type='image',
fileSize=os.path.getsize(filepath),
)
return self.request("POST", path, params)

def upload_file(self, filepath, token):
data = token['data']
path = "http://45.127.129.8/{}/{}?offset=0&complete=true&version=1.0".format(
data['bucket'], data['objectKey'])
content_type = ''
if filepath.endswith('jpg'):
content_type = 'image/jpeg'
elif filepath.endswith('png'):
content_type = 'image/png'
elif filepath.endswith('gif'):
content_type = 'image/gif'
elif filepath.endswith('mpg'):
content_type = 'audio/mp3'
elif filepath.endswith('flac'):
content_type = 'audio/mpeg'
headers = {
'x-nos-token': data['token'],
'Content-Type': content_type,
}
file = open(filepath, 'rb')
return requests.post(url=path, data=file, headers=headers)

def mlog_pub(self, token, height, width, songId, songName='', text='share'):
path = "/weapi/mlog/publish/v1"

params = {
'type': 1,
'mlog': json.dumps({
'content': {
'image': [{
'height': height,
'width': width,
'more': False,
'nosKey': token['data']['bucket'] + '/' + token['data']['objectKey'],
'picKey': token['data']['resourceId']

}],
'needAudio': False,
'song': {
'endTime': 0,
'name': songName,
'songId': songId,
'startTime': 30000
},
'text': text,
},
'from': 0,
'type': 1,
})
}
return self.request("POST", path, params)
17 changes: 17 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,23 @@
"希望找到和我一样喜欢这首歌的朋友",
"人间好声音,推荐给你听"
]
},
/* 发布Mlog:根据填写的歌曲ID,自动下载歌曲的专辑图,并上传 */
"发布Mlog": {
/* 是否开启任务 */
"enable": false,
"taskName": "发布Mlog",
/* 填写歌曲id,随机选取一个,如[65528, 64634] */
"songId": [],
/* 动态内容,随机选取一个,其中$artist会被替换为歌手名,$song会被替换为歌曲名 */
"text": [
"分享$artist的歌曲: $song",
"分享歌曲: $song"
],
/* 图片大小,越大则消耗的外网出流量越多 */
"size": 500,
/* 发布成功后是否自动删除该动态 */
"delete": true
}
},
/* 其他任务 */
Expand Down
70 changes: 67 additions & 3 deletions user.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import re
from hashlib import md5
from api import NetEase
import os
import requests


class User(object):
Expand Down Expand Up @@ -282,12 +284,68 @@ def taskRcmdSong(self, task):
reason = random.choice(task['reason'])
resp = self.music.yunbei_rcmd_submit(songId, yunbeiNum, reason)
if resp['code'] == 200:
self.taskInfo(task['taskName'], '推歌成功,歌曲id为'+str(songId))
self.taskInfo(task['taskName'], '推歌成功,歌曲ID为'+str(songId))
elif resp['code'] == 400:
self.taskInfo(task['taskName'], '推歌失败,歌曲id为' +
self.taskInfo(task['taskName'], '推歌失败,歌曲ID为' +
str(songId)+',失败原因为'+resp.get('message', '未知'))
else:
self.taskInfo(task['taskName'], '推歌失败,歌曲id为'+str(songId))
self.taskInfo(task['taskName'], '推歌失败,歌曲ID为'+str(songId))

def taskMlog(self, task):
if len(task['songId']) == 0:
self.taskInfo(task['taskName'], '请填写歌曲ID')
return
songId = random.choice(task['songId'])

song_resp = self.music.songs_detail([songId])
if song_resp.get('code', -1) == 200 and len(song_resp['songs']) > 0:
song = song_resp['songs'][0]
songName = song['name']
artists = song['ar']
if artists is None or len(artists) == 0:
artistName = '未知'
else:
artistName = '/'.join([a['name'] for a in artists])
url = song.get('al', {}).get('picUrl', '')
else:
self.taskInfo(task['taskName'], '歌曲信息获取失败,请检查ID是否正确')
return
if len(url) == 0:
self.taskInfo(task['taskName'], '专辑图片获取失败')
return

path = '/tmp'
if not os.path.exists(path):
path = './'

filepath = os.path.join(path, 'album.jpg')
size = task.get('size', 500)
url += '?param='+str(size)+'y'+str(size)

r = requests.get(url)
with open(filepath, 'wb') as f:
f.write(r.content)

token = self.music.mlog_nos_token(filepath)
time.sleep(0.2)
self.music.upload_file(filepath, token)
time.sleep(0.2)

text = random.choice(task['text'])
text = text.replace('$artist', artistName)
text = text.replace('$song', songName)
resp = self.music.mlog_pub(token, size, size, songId, songName, text)
if resp.get('code', -1) != 200:
self.taskInfo(task['taskName'], 'Mlog发布失败')

if task.get('delete', True) == True:
time.sleep(0.5)
resourceId = resp['data']['event']['info']['resourceId']
delete_result = self.music.event_delete(resourceId)
self.taskInfo(task['taskName'], '发布成功,已删除Mlog动态')
else:
self.taskInfo(task['taskName'], '发布成功')
os.remove(filepath)

def yunbei_task(self):
user_setting = self.user_setting
Expand Down Expand Up @@ -317,6 +375,12 @@ def yunbei_task(self):
continue
self.taskRcmdSong(tasks[desp])
count += 1
if '发布Mlog' in desp:
desp = '发布Mlog'
if (desp not in tasks) or (tasks[desp]['enable'] == False):
continue
self.taskMlog(tasks[desp])
count += 1

if count == 0:
self.taskInfo('无可执行的任务')
Expand Down

0 comments on commit 432c5d5

Please sign in to comment.