让代码更简单

使用Python实现网易云音乐自动挂机听歌打卡附源码

重要:本文最后更新于2021-09-06 10:06:46,某些文章具有时效性,若有错误或已失效,请在下方留言或联系代码狗

最近狗哥基金亏大了,想办法搞点收入,于是搭建了一个网易云音乐自动挂机打卡的网站,可惜没有用户,欢迎老板使用,每天低至2分钱不到。为了能让普通人用上自动打卡听歌程序,狗哥找到一个开源项目,据测试还能使用,于是稍微修改了下,大家可以用自己的电脑运行,只需要几十秒即可完成每日300首听歌任务。

使用Python实现网易云音乐自动挂机听歌打卡附源码

使用Python实现网易云音乐自动挂机听歌打卡附源码

代码运行环境需要Python3支持,并需要requestspycrypto扩展支持,建议在Centos系统上运行,没有的可以用VM虚拟机安装。环境配置请参阅:Centos7.X升级默认Python到3.X并安装pip3扩展管理

代码如下:

复制
# -*- coding: UTF-8 -*-
#!/usr/bin/python3
import os
import sys
import requests
import base64
import json
import hashlib
import binascii
import codecs
import argparse
import random
from Crypto.Cipher import AES

class Encrypt:
    def __init__(self):
        self.modulus = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7'
        self.nonce = '0CoJUm6Qyw8W8jud'
        self.pubKey = '010001'

    # Random String Generator
    def createSecretKey(self, size):
        return str(binascii.hexlify(os.urandom(size))[:16], encoding='utf-8')

    # AES Encrypt
    def aesEncrypt(self, text, secKey):
        pad = 16 - len(text) % 16
        text = text + pad * chr(pad)
        encryptor = AES.new(secKey.encode('utf8'), 2, b'0102030405060708')
        ciphertext = encryptor.encrypt(text.encode('utf8'))
        ciphertext = str(base64.b64encode(ciphertext), encoding='utf-8')
        return ciphertext

    # RSA Encrypt
    def rsaEncrypt(self, text, pubKey, modulus):
        text = text[::-1]
        rs = int(text.encode('utf-8').hex(), 16)**int(pubKey, 16) % int(
            modulus, 16)
        return format(rs, 'x').zfill(256)

    def encrypt(self, text):
        secKey = self.createSecretKey(16)
        encText = self.aesEncrypt(self.aesEncrypt(text, self.nonce), secKey)
        encSecKey = self.rsaEncrypt(secKey, self.pubKey, self.modulus)
        return {'params': encText, 'encSecKey': encSecKey}


class CloudMusic:
    def __init__(self):
        self.session = requests.Session()
        self.enc = Encrypt()
        self.headers = {
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
            "Referer": "http://music.163.com/",
            "Accept-Encoding": "gzip, deflate",
        }

    def login(self, phone, password):
        loginUrl = "https://music.163.com/weapi/login/cellphone"
        self.loginData = self.enc.encrypt(
            json.dumps({
                'phone': phone,
                'countrycode': '86',
                'password': password,
                'rememberLogin': 'true'
            }))
        headers = {
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
            "Referer":
            "http://music.163.com/",
            "Accept-Encoding":
            "gzip, deflate",
            "Cookie":
            "os=pc; osver=Microsoft-Windows-10-Professional-build-10586-64bit; appver=2.0.3.131777; channel=netease; __remember_me=true;"
        }
        res = self.session.post(url=loginUrl,
                                data=self.loginData,
                                headers=headers)
        ret = json.loads(res.text)
        if ret['code'] == 200:
            self.cookie = res.cookies
            self.csrf = requests.utils.dict_from_cookiejar(
                self.cookie)['__csrf']
            self.nickname = ret["profile"]["nickname"]
            self.beforeCount = self.getLevel()["nowPlayCount"]

            retext = "\"{nickname}\" 登录成功,当前等级:{level}\n\n".format(
                nickname=self.nickname, level=self.getLevel()
                ["level"]) + "距离升级还需听{beforeCount}首歌".format(
                    beforeCount=self.getLevel()["nextPlayCount"] -
                    self.getLevel()["nowPlayCount"])
            return retext
        else:
            return ("登录失败 " + str(ret['code']) + ":" + ret['message'])
            exit()
    def getLevel(self):
        url = "https://music.163.com/weapi/user/level?csrf_token=" + self.csrf
        res = self.session.post(url=url,
                                data=self.loginData,
                                headers=self.headers)
        ret = json.loads(res.text)
        return ret["data"]

    # def refresh(self):
    #     url = "https://music.163.com/weapi/login/token/refresh?csrf_token=" + self.csrf
    #     res = self.session.post(url=url,
    #                             data=self.loginData,
    #                             headers=self.headers)
    #     ret = json.loads(res.text)
    #     print(ret)
    #     return ret["code"]

    def sign(self):
        signUrl = "https://music.163.com/weapi/point/dailyTask"
        res = self.session.post(url=signUrl,
                                data=self.enc.encrypt('{"type":0}'),
                                headers=self.headers)
        ret = json.loads(res.text)
        if ret['code'] == 200:
            return ("签到成功,经验+" + str(ret['point']))
        elif ret['code'] == -2:
            return ("今天已经签到过了")
        else:
            return ("签到失败 " + str(ret['code']) + ":" + ret['message'])

    def task(self, custom):
        url = "https://music.163.com/weapi/v6/playlist/detail?csrf_token=" + self.csrf
        recommendUrl = "https://music.163.com/weapi/v1/discovery/recommend/resource"
        if not custom:
            res = self.session.post(url=recommendUrl,
                                    data=self.enc.encrypt('{"csrf_token":"' +
                                                          self.csrf + '"}'),
                                    headers=self.headers)
            ret = json.loads(res.text)
            if ret['code'] != 200:
                print("获取推荐歌曲失败 " + str(ret['code']) + ":" + ret['message'])
            else:
                lists = ret['recommend']
                musicLists = [(d['id']) for d in lists]
        else:
            musicLists = custom
        musicId = []
        for m in musicLists:
            res = self.session.post(url=url,
                                    data=self.enc.encrypt(
                                        json.dumps({
                                            'id': m,
                                            'n': 1000,
                                            'csrf_token': self.csrf
                                        })),
                                    headers=self.headers)
            ret = json.loads(res.text)
            for i in ret['playlist']['trackIds']:
                musicId.append(i['id'])
        # print("歌单大小:{musicCount}首\n".format(musicCount=len(musicId)))
        postData = json.dumps({
            'logs':
            json.dumps(
                list(
                    map(
                        lambda x: {
                            'action': 'play',
                            'json': {
                                'download': 0,
                                'end': 'playend',
                                'id': x,
                                'sourceId': '',
                                'time': 240,
                                'type': 'song',
                                'wifi': 0
                            }
                        },
                        random.sample(
                            musicId,
                            420 if len(musicId) > 420 else len(musicId)))))
        })
        res = self.session.post(
            url="http://music.163.com/weapi/feedback/weblog",
            data=self.enc.encrypt(postData))
        ret = json.loads(res.text)
        if ret['code'] == 200:
            return ("刷听歌量成功")
        else:
            return ("刷听歌量失败 " + str(ret['code']) + ":" + ret['message'])
            exit(ret['code'])

    # Server Chan Turbo
    def server_chan_turbo(self, sendkey, text):
        url = 'https://sctapi.ftqq.com/%s.send' % sendkey
        headers = {"Content-type": "application/x-www-form-urlencoded"}
        content = {"title": "网易云打卡脚本", "desp": text}
        ret = requests.post(url, headers=headers, data=content)
        print(ret.text)
if __name__ == "__main__":
    # Get Args
#    info = getArgs()
    # Start
    app = CloudMusic()
    print(30 * "=")
    # Login
    res_login = app.login('账号', 'MD5加密的密码')
    # Sign In
    res_sign = app.sign()
    # Music Task
    res_task = app.task('')
    # Print Response
    res = res_login + "\n\n" + res_sign + "\n\n" + res_task
    print(res)
    print(30 * "=")
#    try:
      # 调用Server酱
#        app.server_chan_turbo('方糖key', res)
#    except Exception as err:
#        print("Server酱调用失败:" + err)
#    print(30 * "=")

保存上面的代码为XXX.py文件,然后通过python3 XXX.py命令执行即可。

如果你不会代码,并且不会搞这些东西,只想要解放双手,那么可以使用狗哥搭建的网易云音乐全自动听歌打卡服务,每天低至2分钱,欢迎老板使用,购买地址:http://wyy.daimadog.org

为了让大家感受到狗哥的诚意,下面提供10个价值0.22元的网易云音乐7天体验卡卡密,复制卡密到http://163.daimadog.org使用,即可体验网易云音乐全自动听歌打卡服务。

使用教程请看:网易云音乐全自动打卡,每日签到刷听歌量快速升级

  • 226d98cf56f5c70a27bbd10ed4b67fb520210305
  • ff956c7bb8e0b7e2f99b7a8b30aa402f20210305
  • 405b5357f75c316d185b2ce252674c2720210305
  • ba0315a861a686b41bed7accae9f7f9b20210305
  • a90aefa6f9010c771d24260fefd765fb20210305
  • bc8061938ff883b6dfc6b71fc846e81320210305
  • bbc64e9b0aa60ce7256229dffe6d67c920210305
  • 76f19896df4d8ec143aeb5767e3843ad20210305
  • f2f9a475f8bd15fee5334b02992821ca20210305
  • b228e9a6bb90dd92f69697f9390de34b20210305

至于PHP版本的代码,改天再分享吧,先把基金亏的钱挣回来再说。

感觉很棒!可以赞赏支持我哟~

12 打赏

评论 (12)

登录后评论
这加密方式是不是不能用了
狗哥 ,想购买支持你,买不了啊
正在努力,最近网易云封ip封得厉害。
网易云音乐恢复了,来支持啊!
买不了呀
网易云封ip了
网易云音乐恢复了,http://163.daimadog.com
狗哥这个网站用的wordpress搭建的?
是的
这个用来干啥的?怎么挣钱啊?
我也想知道怎么挣钱
这个很实用,谢谢狗哥分享~
QQ咨询 邮件咨询 狗哥推荐