Skip to content

Commit

Permalink
edit /pixiv and /miaow (Netease) bot_sendPhoto()
Browse files Browse the repository at this point in the history
  • Loading branch information
eatradish committed Dec 4, 2017
1 parent 69b2b91 commit ac16b4e
Show file tree
Hide file tree
Showing 9 changed files with 466,791 additions and 64 deletions.
92 changes: 92 additions & 0 deletions Netease.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import os
import json
import time
import hashlib
import random
import base64
import binascii
import requests
from Crypto.Cipher import AES

header = {
'Accept': '*/*',
'Accept-Encoding': 'gzip,deflate,sdch',
'Accept-Language': 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'music.163.com',
'Referer': 'http://music.163.com/search/',
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36' # NOQA
}
modulus = ('00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7'
'b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280'
'104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932'
'575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b'
'3ece0462db0a22b8e7')
nonce = '0CoJUm6Qyw8W8jud'
pubKey = '010001'
proxies = {
'http': 'socks5://127.0.0.1:1080',
'https': 'socks5://127.0.0.1:1080'
}
def songs_detail_new_api(music_ids, bit_rate=320000):
action = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token=' # NOQA
#self.session.cookies.load()
#csrf = ''
#for cookie in self.session.cookies:
# if cookie.name == '__csrf':
# csrf = cookie.value
#if csrf == '':
# notify('You Need Login', 1)
#action += csrf
data = {'ids': music_ids, 'br': bit_rate, 'csrf_token': ""}
connection = requests.post(action,
data = encrypted_request(data),
headers = header,
proxies = proxies)
result = json.loads(connection.text)
return result['data']

def encrypted_id(id):
magic = bytearray('3go8&$8*3*3h0k(2)2', 'u8')
song_id = bytearray(id, 'u8')
magic_len = len(magic)
for i, sid in enumerate(song_id):
song_id[i] = sid ^ magic[i % magic_len]
m = hashlib.md5(song_id)
result = m.digest()
result = base64.b64encode(result)
result = result.replace(b'/', b'_')
result = result.replace(b'+', b'-')
return result.decode('utf-8')


# 登录加密算法, 基于https://github.com/stkevintan/nw_musicbox脚本实现
def encrypted_request(text):
text = json.dumps(text)
secKey = createSecretKey(16)
encText = aesEncrypt(aesEncrypt(text, nonce), secKey)
encSecKey = rsaEncrypt(secKey, pubKey, modulus)
data = {'params': encText, 'encSecKey': encSecKey}
return data


def aesEncrypt(text, secKey):
pad = 16 - len(text) % 16
text = text + chr(pad) * pad
encryptor = AES.new(secKey, 2, '0102030405060708')
ciphertext = encryptor.encrypt(text)
ciphertext = base64.b64encode(ciphertext).decode('utf-8')
return ciphertext


def rsaEncrypt(text, pubKey, modulus):
text = text[::-1]
rs = pow(int(binascii.hexlify(text), 16), int(pubKey, 16), int(modulus, 16))
return format(rs, 'x').zfill(256)


def createSecretKey(size):
return binascii.hexlify(os.urandom(size))[:16]

49 changes: 31 additions & 18 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, JobQueue
import bot_feature
from telegram import ParseMode
from pprint import *
import logging
import shlex
#logging.basicConfig(level=logging.DEBUG,
#format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

TOKEN = 'TOKEN'

def args_to_list(msg):
args_lst = msg.split()
for i in args_lst:
if ' ' in i:
i = i.replace(' ', '')
return args_lst
return shlex.split(msg)

def msg_to_arg(msg):
msg = replace_rub_str(msg)
Expand Down Expand Up @@ -64,35 +65,32 @@ def tlen(bot, update):
def miaow(bot, update):
msg = bot_feature.miaow(update.message.text)
if msg != None:
bot.sendMessage(chat_id = update.message.chat_id, text = msg)
if type(msg) is dict:
bot.send_photo(chat_id = update.message.chat_id, photo = msg['photo'], caption = msg['msgs'])
else:
bot.sendMessage(chat_id = update.message.chat_id, text = msg)

def bmi(bot, update):
msg = msg_to_arg(update.message.text)
lst = args_to_list(msg)
if msg == '':
bot.sendMessage(chat_id = update.message.chat_id, text = "用法: /bmi [kg][space][cm] or [kg][space][m]")
bot.sendMessage(chat_id = update.message.chat_id, text = 'Syntax: ```/bmi <Weight in kilogram>kg {<Height in meter>m | <Height in centimeter>cm}```', parse_mode = ParseMode.MARKDOWN)
return
result = bot_feature.bmi(lst)
update.message.reply_text(result)

def kuaidi(bot, update):
msg = msg_to_arg(update.message.text)
lst = args_to_list(msg)
if msg == '':
bot.sendMessage(chat_id = update.message.chat_id, text = "用法: /kuaidi + 运单号")
return
try:
int(lst[0])
msg = bot_feature.kuaidi(lst[0])
except:
typ = lst[0]
num = lst[1]
msg = bot_feature.kuaidi(num, typ)
msg = int(msg)
msg = bot_feature.kuaidi(msg)
update.message.reply_text(msg)

def pixiv(bot, update):
msg = bot_feature.pixiv()
bot.sendMessage(chat_id = update.message.chat_id, text = msg)
bot.send_photo(chat_id = update.message.chat_id, photo = msg, caption = msg)

def couplet(bot, update):
msg = msg_to_arg(update.message.text)
Expand All @@ -117,8 +115,21 @@ def whois(bot, update):
msg = bot_feature.whois(msg)
bot.sendMessage(chat_id = update.message.chat_id, text = msg)

def guess(bot, update):
msg = bot_feature.guess()
update.message.reply_text(msg)

def decided(bot, update):
msg = msg_to_arg(update.message.text)
lst = args_to_list(msg)
print(lst)
if len(lst) == 0 or len(lst) == 1:
msg = '用法: /decided "选项 1""选项 2""选项 3"...'
else:
msg = bot_feature.decided(lst)
update.message.reply_text(msg)

if __name__ == '__main__':
TOKEN = ''
updater = Updater(TOKEN)
# Get the dispatcher to register handlers
dp = updater.dispatcher
Expand All @@ -142,6 +153,8 @@ def whois(bot, update):
dp.add_handler(CommandHandler("pixiv", pixiv))
dp.add_handler(CommandHandler("couplet", couplet))
dp.add_handler(CommandHandler("cur", cur))
dp.add_handler(CommandHandler("guess", guess))
dp.add_handler(CommandHandler("decided", decided))
#dp.add_handler(MessageHandler(Filters.text, qaq))

# log all errors
Expand Down
115 changes: 70 additions & 45 deletions bot_feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,27 @@
import os
import random
import re
import express
import shlex
import urllib.parse
import Netease

moeFish_url = 'https://api.telegram.org/botTOKEN/setChatTitle'
moeFish_dict = {'chat_id':'-1001125312504', 'title':'摸鱼'}

def tadd(msg, title_info):
url = 'https://api.telegram.org/botTOKEN/setChatTitle'
d = {'chat_id':'-1001125312504', 'title':'摸鱼'}
if title_info == d['title']:
d['title'] = d['title'] + ' - ' + msg
if title_info == moeFish_dict['title']:
moeFish_dict['title'] = moeFish_dict['title'] + ' - ' + msg
else:
d['title'] = d['title'] + ' - ' + msg + ' - ' + title_info[4:]
requests.get(url, data = d)
moeFish_dict['title'] = moeFish_dict['title'] + ' - ' + msg + ' - ' + title_info[4:]
requests.get(url = moeFish_url, data = moeFish_dict)

def tclear():
d = {'chat_id': '-1001125312504', 'title': '摸鱼'}
url = 'https://api.telegram.org/botTOKEN/setChatTitle'
requests.get(url, data = d)
requests.get(url = moeFish_url, data = moeFish_dict)

def bmi(lst):
if len(lst) != 2:
return "用法: /bmi kg/cm or kg/m"
return "Syntax: /bmi <Weight in kilogram>kg {<Height in meter>m | <Height in centimeter>cm}"
kg = ''
cm = ''
m = ''
Expand All @@ -32,7 +35,8 @@ def bmi(lst):
if 'm' in i and 'c' not in i:
m = i
if kg == '':
return "用法: /bmi [kg][space][cm] or [kg][space][m]"
return "Syntax: /bmi <Weight in kilogram>kg {<Height in meter>m | <Height in centimeter>cm}"

kg = float(kg.replace('kg', ''))
if m != '':
m = float(m.replace('m', ''))
Expand All @@ -46,48 +50,57 @@ def miaow(msg):
dic = {'q': 'p', 'p': 'q', 'd': 'b', 'b': 'd'}
run = ['a', 'w', 'u']
if re.search(r'[qpbd]+[wau]+[qpbd]', msg) != None:
lst = list(msg)
for i in range(len(lst)):
if lst[i] in dic.keys():
lst[i] = dic[lst[i]]
lst = list(filter(lambda x: x in dic.keys() or x in run, lst))
while lst[0] in run:
lst = lst[1:]
while lst[-1] in run:
lst = lst[:-1]
return "".join(lst)
s = re.findall(r'[A-Za-z]', msg)
s = "".join(s)
f = open('words_dictionary.json', 'r')
d = json.load(f)
f.close()
if s in d.keys():
return
else:
lst = list(msg)
for i in range(len(lst)):
if lst[i] in dic.keys():
lst[i] = dic[lst[i]]
lst = list(filter(lambda x: x in dic.keys() or x in run, lst))
while lst[0] in run:
lst = lst[1:]
while lst[-1] in run:
lst = lst[:-1]
return "".join(lst)
elif msg == "ping":
return "pong"
elif "music.163.com/song" in msg:
r = re.compile(r'(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))')
url_list = r.findall(msg)
lst = list(filter(lambda x: 'music.163.com/song' in x, [i[0] for i in url_list]))
s = "".join(lst)
temp = urllib.parse.urlsplit(s)
id = temp.path.replace('/song/', '')
url = 'http://music.163.com/api/song/detail?ids=[' + id + ']'
req = requests.get(url)
j = json.loads(req.text)
msgs = []
msgs.append(j['songs'][0]['name'])
msgs.append(j['songs'][0]['album']['name'])
artists = [a['name'] for a in [b for b in j['songs'][0]['artists']]]
msgs.append(", ".join(artists))
photo = j['songs'][0]['album']['blurPicUrl']
msgs.append("--")
ids = [id]
msgs.append('320K: ' + Netease.songs_detail_new_api(ids)[0]['url'])
msg = "\n".join(msgs)
return {'msgs': msg, 'photo': photo}
else:
return

def whois(msg):
return os.popen("whois " + msg).read()

def kuaidi(msg, typ = None):
headers = {'Origin': "https://www.kuaidi100.com", 'Accept-Encoding': "gzip, deflate, br", 'Acc ept-Language': "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,ja;q=0.2,zh-TW;q=0.2,uz;q=0.2,vi;q=0.2", "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"}
if typ is None:
comCode_url = 'https://www.kuaidi100.com/autonumber/autoComNum?text=' + msg
try:
c_r = requests.post(comCode_url, headers = headers)
c_r = json.loads(c_r.text)
comCode = c_r['auto'][0]['comCode']
except:
msg = '输入错误或订单号没有信息'
else:
comCode = typ
try:
get_url = 'https://www.kuaidi100.com/query?type=' + comCode + '&postid=' + msg + '&id=1&valicode=&temp=0.21830105590577142'
g_r = requests.get(get_url, headers = headers)
g_r = json.loads(g_r.text)
msgs = []
for i in g_r['data']:
msgs.append('%(time)s %(context)s' % i)
pass
msg = '\n'.join(msgs)
except:
msg = '输入错误或订单号没有信息'
return msg
def kuaidi(msg):
if type(msg) is not int:
msg = int(msg)
return express.tracking(msg)

def pixiv():
url = 'https://public-api.secure.pixiv.net/v1/ranking/all?image_sizes=px_128x128%2Cpx_480mw%2Clarge&include_stats=true&page=1&profile_image_sizes=px_170x170%2Cpx_50x50&mode=daily&include_sanity_level=true&per_page=50'
Expand Down Expand Up @@ -120,5 +133,17 @@ def cur(lst):
except:
return

def guess():
d = None
with open('google-10000-english-usa.json', 'r') as f:
d = json.load(f)
return '你现在适宜 ' + random.choice(list(d.items()))[0] + ', 不适宜 ' + random.choice(list(d.items()))[0]

def decided(lst):
if len(list(set(lst))) == 1:
return '不' + lst[0]
else:
return lst[random.randint(0, len(lst) - 1)]



44 changes: 44 additions & 0 deletions express.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json,sys,time,requests,os

api_addr="https://sp0.baidu.com/9_Q4sjW91Qh3otqbppnN2DJv/pae/channel/data/asyncqury"
ua='User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'

header={
'Cookie':'BAIDUID=',
'User-Agent':ua
}
def mstimestamp():
return int(round(time.time() * 1000))

def tracking(number,retry=0):
try:
payload = {
'cb': '',
'appid': 4001,
'nu': number,
'vcode' : '',
'token' : '',
'_' : mstimestamp()
}
raw_json = requests.get(api_addr,params=payload,headers=header)
track=json.loads(raw_json.text)
if(retry>=5):
return "查询失败!错误:-5"
elif(track['status']=='0'):
lst = []
for i in range(len(track['data']['info']['context']) - 1):
timeArray = time.localtime(int(track['data']['info']['context'][i]['time']))
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
lst.append(otherStyleTime + ', ' + track['data']['info']['context'][i]['desc'])
return '\n'.join(lst)
elif(track['status']=='-5'):
if(len(raw_json.cookies)>=1):
header['Cookie']="BAIDUID=%s"%(raw_json.cookies['BAIDUID'])
return tracking(number,retry+1)
else:
return track['msg']
except ValueError:
return "查询接口爆炸"

1 change: 1 addition & 0 deletions google-10000-english-usa.json

Large diffs are not rendered by default.

Loading

0 comments on commit ac16b4e

Please sign in to comment.