예제 #1
0
class MsgService(Service):
    def __init__(self):
        # 初始化变量
        self.config = Config()
        self.cookies = self.config.getCookies()

        self.log = Log('service/Msg')
        self.msg = Msg(self.cookies)
        self.robot = Robot(self.config.get('api_keys'))

        self.uid = int(self.cookies['DedeUserID'])
        self.admin_ids = self.config.get('admin_ids')
        self.receiver_ids = self.config.get('receiver_ids')
        self.cookies_str = self.config.get('cookies')
        self.userList = {}
        self.groupList = {}

        self.is_private = self.config.get('is_private')
        # self.msg.send('start')

    def run(self):
        try:
            self.parseMsg()
            time.sleep(2)
        except Exception as e:
            self.log.error(e)

    # 解析消息
    def parseMsg(self):
        msgList = self.msg.get()
        for msg in msgList:
            self.log.debug(msg)
            # 私信
            if msg['receiver_type'] == 1:
                if msg['msg_type'] == 1:
                    text = json.loads(msg['content'])['content'].lstrip()
                    self.handler(text, msg['sender_uid'], 0)
                pass
            # 应援团
            elif msg['receiver_type'] == 2:
                if (0 in self.receiver_ids or int(msg['receiver_id'] in self.receiver_ids)) \
                        and msg['msg_type'] == 1 and 'at_uids' in msg and self.uid in msg['at_uids']:
                    # 处理@
                    text = json.loads(msg['content'])['content'].lstrip()
                    text = text.replace('\u0011', '')  # IOS客户端的@前后有这两个控制字符
                    text = text.replace('\u0012', '')
                    if text.find('@' + self.getUserName(self.uid)) == 0:
                        text = text[len(self.getUserName(self.uid)) +
                                    1:].lstrip()
                        self.handler(text, msg['sender_uid'],
                                     msg['receiver_id'])
                pass
        pass

    # 消息处理函数
    def handler(self, text, user_id, group_id):
        # 管理员命令
        ot = ''
        if text.find('#') == 0 \
                and (user_id == self.groupList[group_id]['admin'] or user_id in self.admin_ids):
            text = text[1:]
            if user_id in self.admin_ids:
                if text == '切换':
                    old = self.robot.swiRobot()
                    ot = '已从%d号切换到%d号(我比前一位聪明哦~)' % (old, self.robot.apiKeyNo)
            if text == '睡觉':
                self.groupList[group_id]['off'] = 1
                ot = '已准备睡觉,各位晚安~'
            elif text == '醒醒':
                self.groupList[group_id]['off'] = 0
                ot = '又是全新的一天,早安!'
            if ot == '':
                ot = '对方不想理你,并抛出了个未知的异常(◔◡◔)'
        # 聊天
        else:
            # 私信关闭状态
            if group_id == 0 and self.is_private == 0:
                return
            # 睡觉
            if group_id not in self.groupList:
                self.getGroupDetail(group_id)
            if self.groupList[group_id]['off'] == 1:
                return
            if text == '':
                text = '?'
            # 转发消息给机器人
            self.log.success('[in][%s][%s] %s' %
                             (self.groupList[group_id]['name'],
                              self.getUserName(user_id), text))
            ot = self.robot.send(text, user_id, group_id)
            self.log.success('[out][%s][%s] %s' %
                             (self.groupList[group_id]['name'],
                              self.getUserName(user_id), ot))
        # 回复
        # 私信
        if group_id == 0:
            self.msg.send(ot, user_id, receiver_type=1)
        # 群聊
        else:
            self.msg.send('@%s %s' % (self.getUserName(user_id), ot),
                          group_id,
                          receiver_type=2,
                          at_uid=user_id)

    # 获取用户名 uid -> 昵称
    def getUserName(self, user_id):
        # 每300s(5min)更新一次昵称
        if user_id not in self.userList or self.userList[user_id][1] - int(
                time.time()) > 300:
            url = 'http://api.live.bilibili.com/user/v2/User/getMultiple'
            postData = {
                'uids[0]': user_id,
                'attributes[0]': 'info',
                'csrf_token': self.msg.cookies['bili_jct']
            }
            response = requests.post(url, data=postData,
                                     cookies=self.cookies).json()
            self.log.debug('[查询用户]' + str(response))
            self.userList[user_id] = [
                response['data'][str(user_id)]['info']['uname'],
                int(time.time())
            ]
        return self.userList[user_id][0]

    # 获取群信息 群主&勋章名(替代群名)
    def getGroupDetail(self, group_id):
        if group_id not in self.groupList:
            if group_id == 0:
                self.groupList[group_id] = {'admin': 0, 'name': '私信', 'off': 0}
            else:
                url = 'https://api.vc.bilibili.com/link_group/v1/group/detail?group_id=%s' % str(
                    group_id)
                response = requests.get(url).json()
                self.log.debug('[查询群]' + str(response))
                self.groupList[group_id] = {
                    'admin': response['data']['owner_uid'],
                    'name': response['data']['fans_medal_name'],
                    'off': 0
                }
예제 #2
0
class MediaService(Service):

    def __init__(self):
        self.danmu = Danmu()
        self.log = Log('Media Service')
        self.config = Config()

    def run(self):
        try:
            # 判断队列是否为空
            if PlayQueue.empty():
                # 获取随机文件,播放
                musicPath = './resource/music/'
                randomMusic = self.getRandomFile(musicPath)

                musicName = os.path.basename(randomMusic)
                musicName = musicName.replace(os.path.splitext(randomMusic)[1], '')

                self.playMusic({
                    'username': '******',
                    'name': musicName,
                    'filename': musicPath + randomMusic
                }, True)
                return

            # 获取新的下载任务
            task = PlayQueue.get()
            if task and 'type' in task:
                if task['type'] == 'music':
                    self.playMusic(task)
                elif task['type'] == 'vedio':
                    pass

        except Exception as e:
            self.log.error(e)

    # 播放音乐
    def playMusic(self, music, autoPlay=False):
        imagePath = './resource/img/'
        randomImage = imagePath + self.getRandomFile(imagePath)
        self.log.info('[Music] 开始播放[%s]点播的[%s]' % (music['username'], music['name']))
        self.danmu.send('正在播放 %s' % music['name'])

        # 获取歌词
        assPath = './resource/lrc/default.ass'
        if 'lrc' in music:
            assPath = music['lrc']

        # 开始播放
        command = ffmpeg().getMusic(music=music['filename'], output=self.getRTMPUrl(), image=randomImage, ass=assPath)
        command = "%s 2>> ./log/ffmpeg.log" % command
        self.log.debug(command)
        process = subprocess.Popen(args=command, cwd=os.getcwd(), shell=True)
        process.wait()

        # 播放完毕
        if not autoPlay:
            os.remove(path=music['filename'])
        self.log.info('[Music] [%s]播放结束' % music['name'])

    # 获取推流地址
    def getRTMPUrl(self):
        url = self.config.get(module='rtmp', key='url')
        code = self.config.get(module='rtmp', key='code')
        return url + code

    # 获取随机文件
    def getRandomFile(self, path):
        fileList = os.listdir(path)
        if len(fileList) == 0:
            raise Exception('无法获取随机文件,%s为空' % path)

        index = random.randint(0, len(fileList) - 1)
        return fileList[index]
예제 #3
0
class Danmu(object):
    def __init__(self):
        self.config = Config()
        self.httpConfig = {
            'getUrl': 'http://api.live.bilibili.com/ajax/msg',
            'sendUrl': 'http://api.live.bilibili.com/msg/send',
            'header': {
                "Accept":
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                "Accept-Encoding":
                "utf-8",
                "Accept-Language":
                "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3",
                "Connection":
                "keep-alive",
                "Cookie":
                self.config.get('cookie'),
                "Host":
                "api.live.bilibili.com",
                "Referer":
                "http://live.bilibili.com/" + self.config.get('roomId'),
                "User-Agent":
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0"
            }
        }
        self.sendLock = False

    def get(self):
        # 准备数据
        roomId = self.config.get('roomId')
        postData = urllib.parse.urlencode({
            'token:': '',
            'csrf_token:': '',
            'roomid': roomId
        }).encode('utf-8')

        # 发送请求
        request = urllib.request.Request(self.httpConfig['getUrl'], postData,
                                         self.httpConfig['header'])
        response = json.loads(
            urllib.request.urlopen(request).read().decode('utf-8'))

        # 获取最后的弹幕时间
        configTimestamp = self.config.get(module='danmu', key='timestamp')
        if configTimestamp == None:
            configTimestamp = 0
        else:
            configTimestamp = float(configTimestamp)

        if 'code' in response and response['code'] == 0:
            # 解析弹幕
            result = []
            for danmu in response['data']['room']:

                # 判断弹幕是否被处理过
                thisTimestamp = time.mktime(
                    time.strptime(danmu['timeline'], "%Y-%m-%d %H:%M:%S"))
                if configTimestamp >= thisTimestamp:
                    continue

                self.config.set(module='danmu',
                                key='timestamp',
                                value=thisTimestamp)

                result.append({
                    'name': danmu['nickname'],
                    'time': danmu['timeline'],
                    'uid': str(danmu['uid']),
                    'text': danmu['text']
                })
                pass
            return result
        else:
            raise Exception('Cookie 无效')

    #发送弹幕函数
    def send(self, text):
        elapsedTime = 0
        while self.sendLock:
            time.sleep(1)
            # 判断等待超时
            elapsedTime += 1
            if (elapsedTime > 30):
                return None

        # 判断长度
        lengthLimit = 20
        if len(text) > lengthLimit:
            for i in range(0, len(text), lengthLimit):
                self.send(text[i:i + lengthLimit])
                time.sleep(1.5)
            return True

        # 准备数据
        self.sendLock = True
        try:
            roomId = self.config.get('roomId')
            csrf = self.config.get('csrf')
            postData = (urllib.parse.urlencode({
                'color': '16777215',
                'fontsize': '25',
                'mode': '1',
                'msg': text,
                'rnd': '1616330701',
                'roomid': roomId,
                'csrf_token': csrf,
                'csrf': csrf
            }).encode('utf-8'))

            # 发送请求
            request = urllib.request.Request(self.httpConfig['sendUrl'],
                                             postData,
                                             self.httpConfig['header'])
            response = json.loads(
                urllib.request.urlopen(request).read().decode('utf-8'))
            print(response)
            print("发送弹幕结束,弹幕 " + text)

            return 'code' in response and response['code'] == 0
        except Exception as e:
            raise e
        finally:
            self.sendLock = False
class MediaService(Service):
    def __init__(self):
        self.danmu = Danmu()
        self.log = Log('Media Service')
        self.config = Config()
        self.ass = AssMaker()

    def run(self):
        try:
            # 判断队列是否为空
            if PlayQueue.empty():
                time.sleep(3)
                # 获取随机文件,播放
                musicPath = './resource/music/'
                musicName = self.getRandomFile(musicPath, '.mp3')
                # musicName = os.path.basename(musicName)
                musicName = os.path.splitext(musicName)[0]
                task = {}
                # 存在详情文件
                if os.path.isfile('%s%s.mp3.json' % (musicPath, musicName)):
                    f = open('%s%s.mp3.json' % (musicPath, musicName), 'rt')
                    task = json.loads(f.read())
                    f.close()
                else:
                    pass
                self.playMusic(task)
            else:
                # 获取新的下载任务
                task = PlayQueue.get()
                if task and 'type' in task:
                    if task['type'] == 'id':
                        self.playMusic(task)
                    elif task['type'] == 'mv':
                        self.playVedio(task)
                        pass
        except Exception as e:
            self.log.error(e)

    # 播放音乐
    def playMusic(self, music):
        self.log.info('[Music] 开始播放[%s]点播的[%s]' %
                      (music['username'], music['info']['name']))
        self.danmu.send('正在播放%s' % music['info']['name'])
        # 生成背景字幕
        self.ass.make_ass(music, './resource/bak.ass')
        # 处理图片
        imagePath = './resource/img/'
        randomImage = imagePath + self.getRandomFile(imagePath)
        command = ffmpeg().getImage(image=randomImage,
                                    output='./resource/bak.jpg',
                                    ass='./resource/bak.ass')
        command = "%s 2>> ./log/ffmpeg_img.log" % command
        self.log.debug(command)
        process = subprocess.Popen(args=command, cwd=os.getcwd(), shell=True)
        process.wait()
        # 获取歌词
        assPath = ''
        if 'lrc' in music['info']:
            assPath = './resource/music/%s.mp3.ass' % music['info']['id']
        # 开始播放
        mp3Path = './resource/music/%s.mp3' % music['info']['id']
        command = ffmpeg().getMusic(music=mp3Path,
                                    output=self.getRTMPUrl(),
                                    image='./resource/bak.jpg',
                                    ass=assPath)
        command = "%s 2>> ./log/ffmpeg.log" % command
        self.log.debug(command)
        process = subprocess.Popen(args=command, cwd=os.getcwd(), shell=True)
        process.wait()
        self.log.info('[Music] [%s]播放结束' % music['info']['name'])

    # 播放视频
    def playVedio(self, music):
        self.log.info('[Music] 开始播放[%s]点播的[%s]' %
                      (music['username'], music['info']['name']))
        self.danmu.send('正在播放%s' % music['info']['name'])
        # 开始播放
        vedioPath = './resource/video/%s_mv.flv' % music['info']['id']
        command = ffmpeg().getVedio(vedio=vedioPath, output=self.getRTMPUrl())
        command = "%s 2>> ./log/ffmpeg.log" % command
        self.log.debug(command)
        process = subprocess.Popen(args=command, cwd=os.getcwd(), shell=True)
        process.wait()
        self.log.info('[Music] [%s]播放结束' % music['info']['name'])

    # 获取推流地址
    def getRTMPUrl(self):
        url = self.config.get(module='rtmp', key='url')
        code = self.config.get(module='rtmp', key='code')
        return url + code

    # 获取随机文件
    def getRandomFile(self, path, type=None):
        fileList = []
        if type:
            for filename in os.listdir(path):
                if os.path.splitext(filename)[1] == type:
                    fileList.append(filename)
        else:
            fileList = os.listdir(path)
        if len(fileList) == 0:
            raise Exception('无法获取随机文件,%s为空' % path)
        index = random.randint(0, len(fileList) - 1)
        return fileList[index]
class DanmuService(Service):
    def __init__(self):
        self.danmu = Danmu()
        self.config = Config()
        self.neteaseMusic = NeteaseMusic()
        self.log = Log('Danmu Service')
        self.commandMap = {
            '点歌=': 'selectSongAction',
            'id=': 'selectSongByIdAction',
            'mv=': 'selectMvByIdAction',
            '切歌': 'DebugAction'
        }
        pass

    def run(self):
        try:
            self.parseDanmu()
            time.sleep(1.5)
        except Exception as e:
            self.log.error(e)

    # 解析弹幕
    def parseDanmu(self):
        danmuList = self.danmu.get()
        if danmuList:
            for danmu in danmuList:
                self.log.debug('%s: %s' % (danmu['name'], danmu['text']))
                if danmu['name'] != self.config.get('miaoUser'):  # 不响应弹幕姬的弹幕
                    danmu['text'] = danmu['text'].replace(' ', '')  # 删除空格防和谐
                    self.danmuStateMachine(danmu)
        pass

    # 将对应的指令映射到对应的Action上
    def danmuStateMachine(self, danmu):
        text = danmu['text']
        commandAction = ''
        for key in self.commandMap:
            # 遍历查询comand是否存在 若存在则反射到对应的Action
            if text.find(key) == 0 and hasattr(self, self.commandMap[key]):
                danmu['command'] = danmu['text'][len(key):len(danmu['text'])]
                getattr(self, self.commandMap[key])(danmu)
                break
        pass

    # 歌曲名点歌
    def selectSongAction(self, danmu):
        self.log.info('%s 点歌 [%s]' % (danmu['name'], danmu['command']))
        command = danmu['command']
        song = []
        # 按歌曲名-歌手点歌
        if command.find('-') != -1:
            detail = command.split('-')
            if len(detail) == 2:
                song = self.neteaseMusic.searchSingle(detail[0], detail[1])
            else:
                # 查询失败
                song = {}
        # 直接按歌曲名点歌
        else:
            song = self.neteaseMusic.searchSingle(danmu['command'])

        if song:
            self.danmu.send('%s点歌成功' % song['name'])
            DownloadQueue.put({
                'type': 'id',
                'info': song,
                'username': danmu['name'],
                'time': danmu['time']
            })
        else:
            # 未找到歌曲
            self.danmu.send('找不到%s' % danmu['command'])
            self.log.info('找不到%s' % danmu['command'])

    # 通过Id点歌
    def selectSongByIdAction(self, danmu):
        self.log.info('%s ID [%s]' % (danmu['name'], danmu['command']))
        command = danmu['command']
        try:
            song = self.neteaseMusic.getInfo(command)
            if song:
                self.danmu.send('%s点歌成功' % song['name'])
                DownloadQueue.put({
                    'type': 'id',
                    'info': song,
                    'username': danmu['name'],
                    'time': danmu['time']
                })
            else:
                # 未找到歌曲
                raise Exception('未找到歌曲')
        except Exception as e:
            self.danmu.send('找不到%s' % danmu['command'])
            self.log.info('找不到%s' % danmu['command'])

    # 通过Id点Mv
    def selectMvByIdAction(self, danmu):
        self.log.info('%s MV [%s]' % (danmu['name'], danmu['command']))
        command = danmu['command']
        try:
            mv = self.neteaseMusic.getMv(command)
            if mv:
                self.danmu.send('%s点播成功' % mv['name'])
                DownloadQueue.put({
                    'type': 'mv',
                    'info': mv,
                    'username': danmu['name'],
                    'time': danmu['time']
                })
            else:
                # 未找到歌曲
                raise Exception('未找到MV')
        except Exception as e:
            self.danmu.send('找不到%s' % danmu['command'])
            self.log.info('找不到%s' % danmu['command'])

    def DebugAction(self, danmu):
        if danmu['name'] in self.config.get('adminUser'):
            if danmu['text'] == '切歌':
                os.system(
                    "kill `ps a|grep 'ffmpeg -re'|grep -v 'sh'|grep -v 'grep'|awk '{print $1}'`"
                )
                self.danmu.send('切歌成功')
예제 #6
0
 def __init__(self):
     all_config = Config()
     self.headers = {
         'User-Agent': all_config.get(key='User-Agent', module='headers'),
         'Cookie':     all_config.get(key='Cookie',     module='headers')
     }
예제 #7
0
class Danmu(object):
    def __init__(self):
        self.config = Config()
        self.http_config = {
            'getUrl': 'http://api.live.bilibili.com/ajax/msg',
            'sendUrl': 'http://api.live.bilibili.com/msg/send',
            'header': {
                "Accept": "application/json, text/javascript, */*; q=0.01",
                "Accept-Encoding": "gzip, deflate, br",
                "Accept-Language":
                "zh,en-US;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-CN;q=0.6",
                "Connection": "keep-alive",
                "Cookie": self.config.get('cookie', 'danmu'),
                "Host": "api.live.bilibili.com",
                "Referer":
                "http://live.bilibili.com/" + self.config.get('roomId'),
                "User-Agent": self.config.get('User-Agent', 'headers')
            }
        }
        self.send_lock = False

    def get(self):
        """获取弹幕(单次上限10条)"""
        room_id = self.config.get('roomId')
        post_data = {'token:': '', 'csrf_token:': '', 'roomid': room_id}
        response = requests.post(url=self.http_config['getUrl'],
                                 data=post_data,
                                 headers=self.http_config['header']).json()
        # 获取最后的弹幕时间
        config_time = self.config.get(module='danmu', key='timestamp')
        config_time = float(config_time) if config_time else 0

        if 'code' in response and response['code'] == 0:
            # 解析弹幕
            result = []
            for danmu in response['data']['room']:
                # 判断弹幕是否被处理过
                current_time = time.mktime(
                    time.strptime(danmu['timeline'], "%Y-%m-%d %H:%M:%S"))
                if config_time >= current_time:
                    continue

                self.config.set(module='danmu',
                                key='timestamp',
                                value=current_time)
                result.append({
                    'name': danmu['nickname'],
                    'time': danmu['timeline'],
                    'uid': str(danmu['uid']),
                    'text': danmu['text']
                })
            return result
        else:
            raise Exception('Cookie 无效')

    def send(self, text):
        """发送弹幕"""
        elapsed_time = 0
        while self.send_lock:
            time.sleep(1)
            # 判断等待超时
            elapsed_time += 1
            if (elapsed_time > 30):
                return None

        # 将超过20字的弹幕切片后发送
        length_limit = 20
        if len(text) > length_limit:
            for i in range(0, len(text), length_limit):
                self.send(text[i:i + length_limit])
                time.sleep(1.5)
            return True

        # 准备数据
        self.send_lock = True
        try:
            room_id = self.config.get('roomId')
            post_data = {
                'color': '16777215',
                'csrf_token': self.config.get("csrf_token", 'danmu'),
                'fontsize': '25',
                'mode': '1',
                'msg': text,
                'rnd': '1543573073',
                'roomid': room_id
            }
            # 发送请求
            response = requests.post(
                url=self.http_config['sendUrl'],
                data=post_data,
                headers=self.http_config['header']).json()
            return 'code' in response and response['code'] == 0
        except Exception as e:
            raise e
        finally:
            self.send_lock = False