Exemple #1
0
def get_2019_donate_rank():
    """
    获取2019集资排名
    :return:
    """
    rst = mysql_util.select_all("""
        select s.id, s.`name`, sum(o.`backer_money`) as c from `order` o, supporter s where o.`supporter_id` = s.`id` 
        and o.`pro_id` in (44611, 45584, 47645, 47863, 48285, 50755, 51567, 54590, 55194, 57085, 57083, 59267,
        59708, 61410, 62988, 64096, 64735, 65643, 66888, 68067,
        69304, 70158, 70956, 71842, 72535, 73894, 74791, 75412, 79264)
        group by s.`id`
        order by c desc limit 25;
    """)
    cur_rank = 0
    row_tmp = 0
    last_val = -1
    new_rst = []
    for rank in rst:
        row_tmp += 1
        if rank[2] != last_val:
            cur_rank = row_tmp
        if cur_rank > 25:
            continue
        last_val = rank[2]
        rank_tmp = rank + (cur_rank, )
        new_rst.append(rank_tmp)
    logger.debug(new_rst)
    message = ''
    for rank in new_rst:
        sub_message = '%s.%s: %s元\n' % (rank[3], str(rank[1],
                                                     encoding='utf8'), rank[2])
        message += sub_message
    return message
Exemple #2
0
def get_donate_rank(start_date, num):
    """
    获取生日集资排名
    :param start_date:
    :param num:
    :return:
    """

    rst = mysql_util.select_all("""
        select s.id, s.`name`, sum(o.`backer_money`) as c from `order` o, supporter s where o.`supporter_id` = s.`id` 
        and o.`pro_id` in ('4mr9Xz920100009000043331') and o.`pay_time` >= '{}'
        group by s.`id`
        order by c desc limit {};
    """.format(start_date, num))
    cur_rank = 0
    row_tmp = 0
    last_val = -1
    new_rst = []
    for rank in rst:
        row_tmp += 1
        if rank[2] != last_val:
            cur_rank = row_tmp
        if cur_rank > 25:
            continue
        last_val = rank[2]
        rank_tmp = rank + (cur_rank, )
        new_rst.append(rank_tmp)
    logger.debug(new_rst)
    message = ''
    for rank in new_rst:
        sub_message = '%s.%s: %s元\n' % (rank[3], str(rank[1],
                                                     encoding='utf8'), rank[2])
        message += sub_message
    return message
Exemple #3
0
def search_card(context, modian_id):
    """
    查询当前已经获得的卡片
    :param context:
    :param modian_id:
    :return:
    """
    try:
        from modian.modian_card_draw import CardDrawHandler
        card_draw_handler = CardDrawHandler()
        card_draw_handler.read_config()
        from utils import util
        # is_digit = util.is_positive_integer(modian_id)
        # if not is_digit:
        #     bot.send('摩点ID为纯数字,请重试~')
        #     return
        report = card_draw_handler.get_cards(modian_id)
        bot.send(context, report)
        if '当前暂未抽中任何卡片' not in report:
            pic = '[CQ:image,file=%s]' % 'result.jpg'
            logger.debug(pic)
            bot.send(context, pic)
    except Error as e:
        logger.error(e)
        # bot.send(context, '查询出现错误!\n{}'.format(traceback.print_exc()))
    except Exception as exp:
        logger.exception(exp)
        logger.exception(traceback.print_exc())
Exemple #4
0
 def get_login_info(cls):
     """
     获取登录号信息
     :return:
     """
     login_info = bot.get_login_info()
     logger.debug('login_info: %s', login_info)
     return login_info
Exemple #5
0
    def select_all(self, sql, param=None):
        """ 获取所有信息 """
        logger.debug('sql: %s, param: %s', sql, param)
        conn = self.get_conn()
        cursor = conn.cursor()
        rowcount = cursor.execute(sql, param)
        if rowcount > 0:
            res = cursor.fetchall()
        else:
            res = None
        cursor.close()
        conn.close()

        return res
Exemple #6
0
    def query(self, sql, param=None):
        """ 删除,更新,插入, 执行sql语句 """
        logger.debug('sql: %s, param: %s', sql, param)
        conn = self.get_conn()
        cursor = conn.cursor()
        if param is None:
            rowcount = cursor.execute(sql)
        else:
            rowcount = cursor.execute(sql, param)
        conn.commit()
        cursor.close()
        conn.close()

        return rowcount
Exemple #7
0
 def execute_and_get_id(self, sql, param=None):
     """ 执行插入语句并获取自增id """
     logger.debug('sql: %s, param: %s', sql, param)
     conn = self.get_conn()
     cursor = conn.cursor()
     if param is None:
         cursor.execute(sql)
     else:
         cursor.execute(sql, param)
     row_id = cursor.lastrowid
     conn.commit()
     cursor.close()
     conn.close()
     return row_id
Exemple #8
0
 def make_sign(self, post_fields):
     """
     计算签名
     1.将<key, value>请求参数对按key进行字典升序排序,得到有序的参数对列表N
     2.将列表N中的参数对按URL键值对的格式拼接成字符串,得到字符串T(如:key1=value1&key2=value2),URL键值拼接过程value部分需要URL编码,URL编码算法用大写字母,例如%E8,而不是小写%e8
     3.将应用密钥以app_key为键名,组成URL键值拼接到字符串T末尾,得到字符串S(如:key1=value1&key2=value2&app_key=密钥)
     4.对字符串S进行MD5运算,将得到的MD5值所有字符转换成大写,得到接口请求签名
     :param post_fields:
     :return:
     """
     post_fields_sorted = util.ksort(post_fields)
     url_string = urllib.parse.urlencode(post_fields_sorted)
     url_string += '&app_key=%s' % self.appkey
     logger.debug('md5 string: %s' % url_string)
     sign = hashlib.md5(url_string.encode('utf-8')).hexdigest()
     sign = sign.upper()
     logger.debug('sign: %s' % sign)
     return sign
Exemple #9
0
def __get_jizi_ranking_list_by_date_diff(pro_id, day_diff=0):
    """
    获取当日集资排名
    :param pro_id:
    :param day_diff:与今天相差的天数
    :return: 排名tuple 格式(supporter_id, supporter_name, total_amount, rank)
    """
    # 总额
    rst2 = mysql_util.select_one(
        """
                    select SUM(`order`.backer_money) as total 
                    from `order`
                    where `order`.pro_id = %s
                        and CURDATE()-%s=DATE(`order`.pay_time);
                """, (pro_id, day_diff))
    total = rst2[0]

    # 集资排名
    rst = mysql_util.select_all(
        """
            select `supporter`.id, `supporter`.name, SUM(`order`.backer_money) as total 
            from `order`, `supporter` 
            where `supporter`.id=`order`.supporter_id 
                and `order`.pro_id = %s
                and CURDATE()-%s=DATE(`order`.pay_time) 
            group by `order`.supporter_id 
            order by total desc;
        """, (pro_id, day_diff))
    cur_rank = 0
    row_tmp = 0
    last_val = -1
    new_rst = []
    for rank in rst:
        row_tmp += 1
        if rank[2] != last_val:
            cur_rank = row_tmp
        if cur_rank > 10:
            continue
        last_val = rank[2]
        rank_tmp = rank + (cur_rank, )
        new_rst.append(rank_tmp)
    logger.debug(new_rst)
    return new_rst
Exemple #10
0
 def nlp_textchat(self, question, session):
     """
     基础闲聊接口
     :param question:
     :return:
     """
     url = 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat'
     logger.info('调用QQ基础闲聊接口: %s' % url)
     params = {
         "app_id": self.appid,
         "time_stamp": int(time.time()),
         "nonce_str": self.generate_random_str(randomlength=16),
         "session": session,
         'question': question
     }
     r = requests.post(url,
                       self.make_post_params(params),
                       headers=self.header()).json()
     logger.debug(r)
     if r['ret'] == 0:
         logger.debug('回复: %s' % r['data']['answer'])
         return r['data']['answer']
     else:
         logger.error('调用基础闲聊接口出错,错误码: %s, msg: %s' % (r['ret'], r['msg']))
Exemple #11
0
def get_huitui_rank(context):
    """
    获取排行榜
    :return:
    """
    logger.debug('获取排行榜')
    rst = mysql_util.select_all("""
    select s.`name`, tc.`name`, CONVERT((tc.prop1 * 1.5 + tc.prop2 + tc.prop3 * 1.2 + tc.prop5 * 0.9) * (1 + tc.prop4 / 100), SIGNED) as ce
from `t_character` tc, `supporter` s where tc.`modian_id` = s.`id`
order by ce desc limit 10;
            """)
    rank = 1
    result_str = '灰推群侠传排行榜: \n'
    logger.debug(rst)
    for name, c_name, ce in rst:
        result_str += '{}.{}({}): {}\n'.format(rank, str(name,
                                                         encoding='utf-8'),
                                               str(c_name, encoding='utf-8'),
                                               ce)
        rank += 1
    logger.debug(result_str)
    bot.send(context, result_str)
Exemple #12
0
# 读取口袋48的配置
global_config.MEMBER_JSON = json.load(open('data/pocket48/member.json', encoding='utf8'))
global_config.POCKET48_JSON = json.load(open('data/pocket48/pocket48.json'), encoding='utf8')
global_config.POCKET48_VERSION = global_config.POCKET48_JSON['version']
global_config.IMEI = global_config.POCKET48_JSON['IMEI']

global_config.AUTO_REPLY_GROUPS = ConfigReader.get_property('qq_conf', 'auto_reply_groups').split(';')
global_config.TEST_GROUPS = ConfigReader.get_property('qq_conf', 'test_groups').split(';')
global_config.PERFORMANCE_NOTIFY = ConfigReader.get_property('profile', 'performance_notify')
global_config.LIVE_LINK = ConfigReader.get_property('auto_reply', '公演直播')

using_pro = ConfigReader.get_property('root', 'using_coolq_pro')
if using_pro == 'yes':
    global_config.USING_COOLQ_PRO = True

logger.debug('读取成员信息')
members_list = global_config.POCKET48_JSON['monitor_members']
for member in members_list:
    member_pinyin = member['name']
    if member_pinyin in global_config.MEMBER_JSON:
        # 如果成员名在数据文件中,创建监听任务
        member_json = global_config.MEMBER_JSON[member_pinyin]
        member_obj = Member(name=member_json['chinese_name'], member_id=member_json['member_id'],
                            room_id=member_json['room_id'], weibo_uid=member_json['weibo_uid'],
                            pinyin=member_pinyin)
        task = Pocket48ListenTask(member_obj)
        task.member_live_groups = member['broadcast_message_lite_groups']
        task.member_room_msg_groups = member['broadcast_message_detail_groups']
        task.member_room_msg_lite_groups = member['broadcast_message_lite_groups']
        task.room_comment_groups = member['broadcast_room_comment_groups']
        logger.debug('room_msg_lite_groups: {}'.format(task.member_room_msg_lite_groups))
Exemple #13
0
 def get_group_list(cls):
     group_list = bot.get_group_list()
     logger.debug('group list: %s', group_list)
     return group_list
Exemple #14
0
def handle_msg(context):
    # 下面这句等价于 bot.send_private_msg(user_id=context['user_id'], message='你好呀,下面一条是你刚刚发的:')
    try:
        message = context['message']
        group_id = context['group_id']
        user_id = context['user_id']
        logger.info('收到一条消息: 群: %s, 发送人: %s, %s', group_id, user_id, message)
        if user_id == context['self_id']:
            logger.debug('不处理自己发送的消息')
            return

        logger.info(AUTO_REPLY)

        # 关键词自动回复
        for k, v in AUTO_REPLY.items():
            if k in message.lower():
                logger.info('命中关键词: %s', k)
                bot.send(context, v)
                break

        if str(group_id) in test_groups:
            # AI智能回复
            logger.debug('AI智能回复')
            if len(message) > 1 and message.startswith('%'):
                content = message[1:]
                logger.debug('提问内容: %s' % content)
                reply = ai_bot.nlp_textchat(content, user_id)
                bot.send(context, reply)
            elif message == '-express':
                express_message = '[CQ:image,file=%s]' % ('lt_020.png')
                express_message2 = '[CQ:image,file=%s]' % ('tsj_013.gif')
                express_message3 = '[CQ:image,file=%s]' % ('xxy_040.png')
                logger.debug(express_message)
                logger.debug(express_message2)
                logger.debug(express_message3)
                bot.send(context, express_message)
                bot.send(context, express_message2)
                bot.send(context, express_message3)
            elif message == '-audio':
                import random
                files = ['1.aac', '2.aac', '3.aac', '4.aac', '5.aac']
                express_message = '[CQ:record,file=%s]'.format(
                    random.choice(files))
                bot.send(context, express_message)
            elif message == '抽签':
                try:
                    message = draw_lottery(user_id, group_id)
                    bot.send(context, message)
                except Error as err:
                    logger.exception(err)
                except Exception as e:
                    logger.exception(e)
                    bot.send(context, '抽签出现错误!')
            elif message == '解签':
                try:
                    message = solve_lottery(user_id, group_id)
                    bot.send(context, message)
                except Error as err:
                    logger.exception(err)
                except Exception as e:
                    logger.exception(e)
                    bot.send(context, '解签出现错误!')

        # 查询集资
        if str(group_id) in groups:
            if len(modian_array) > 0:
                if message == '-today':
                    get_jizi_ranking_list_by_date(context, 0)
                elif message == '-yesterday':
                    get_jizi_ranking_list_by_date(context, 1)
                elif message.startswith('-集资排名'):
                    from utils import util
                    admins = util.read_txt(
                        os.path.join(BASE_DIR, 'data', 'card_draw',
                                     'admin.txt'))
                    if str(user_id) not in admins:
                        logger.info('QQ:{} 无权限操作!')
                        return
                    strs = message.split(' ')
                    if len(strs) != 3:
                        num = 25
                        start_date = '1970-01-01'
                    else:
                        start_date = strs[1]
                        num = int(strs[2])
                    message = get_donate_rank(start_date, num)
                    bot.send(context, message)
                elif message == '-2019':
                    from utils import util
                    admins = util.read_txt(
                        os.path.join(BASE_DIR, 'data', 'card_draw',
                                     'admin.txt'))
                    if str(user_id) not in admins:
                        logger.info('QQ:{} 无权限操作!')
                        return
                    message = get_2019_donate_rank()
                    bot.send(context, message)
                elif message == '-战况':
                    from utils import util
                    admins = util.read_txt(
                        os.path.join(BASE_DIR, 'data', 'card_draw',
                                     'admin.txt'))
                    if str(user_id) not in admins:
                        logger.info('QQ:{} 无权限操作!')
                        return
                    message = get_modian_pk()
                    bot.send(context, message)
                # elif message == '-排行榜':
                #     get_huitui_rank(context)
                elif message == '-help':
                    help_msg = """查询当前集卡情况: 【-查询 桃叭ID】,
                        积分抽卡(积分数量必须是15的倍数): 【-积分抽 摩点ID 桃叭数量】,
                        补抽卡: 【-补抽 桃叭ID 补抽金额】,
                        消息以"%"开头,机器人可免费陪聊,每日数额有限
                    """
                    bot.send(context, help_msg)
                elif message.startswith('-查询'):
                    strs = message.split(' ')
                    if len(strs) == 2:
                        search_card(context, strs[1])
                    else:
                        bot.send(context, '格式为【-查询 桃叭ID】的形式,请重试~')
                elif message.startswith('-积分抽'):
                    from utils import util
                    admins = util.read_txt(
                        os.path.join(BASE_DIR, 'data', 'card_draw',
                                     'admin.txt'))
                    if str(user_id) not in admins:
                        logger.info('QQ:{} 无权限操作积分抽卡!')
                        return
                    strs = message.split(' ')
                    if len(strs) == 3:
                        draw_card_using_score(context, strs[1], strs[2])
                    else:
                        bot.send(context, '格式为【-积分抽 桃叭ID 积分数量】的形式,请重试~')
                elif message.startswith('-补抽'):
                    from utils import util
                    admins = util.read_txt(
                        os.path.join(BASE_DIR, 'data', 'card_draw',
                                     'admin.txt'))
                    if str(user_id) not in admins:
                        logger.info('QQ:{} 无权限操作补抽卡!')
                        return
                    strs = message.split(' ')
                    if len(strs) == 3:
                        draw_missed_card(context, strs[1], strs[2])
                    else:
                        bot.send(context, '格式为【-补抽 桃叭ID 补抽金额】的形式,请重试~')
                # elif message.upper() == '-PK':
                #     try:
                #         from modian_plugin import modian_handler
                #         message = modian_handler.pk_modian_activity()
                #         bot.send(context, message)
                #     except Error as e:
                #         logger.exception(e)
                #     except Exception as e:
                #         logger.exception(e)
                #         bot.send(context, '查询PK出现错误!')
            else:
                bot.send(context, '目前并没有正在进行的集资项目T_T')
    except Error:
        pass
Exemple #15
0
from log.my_logger import logger
from utils.bot import bot
from utils.config_reader import ConfigReader
# from utils import global_config
# from modian_plugin import modian_handler
from qq.ai_reply import QQAIBot
from utils import util
import os
import sqlite3
import datetime
from datetime import date
import traceback

AUTO_REPLY = {}
items = ConfigReader.get_section('auto_reply')
logger.debug('items: %s', items)
for k, v in items:
    logger.debug('k: %s, v: %s', k, v)
    AUTO_REPLY[k] = v
    logger.debug('k in global_config.AUTO_REPLY: %s', k in AUTO_REPLY)
    logger.debug(AUTO_REPLY)

# groups = [483548995]
groups = ConfigReader.get_property('qq_conf', 'jizi_notify_groups').split(';')
test_groups = ConfigReader.get_property('qq_conf',
                                        'auto_reply_groups').split(';')
print(groups)
logger.debug('test groups: %s' % test_groups)
modian_json = json.load(open("data/modian.json", encoding='utf8'))

modian_array = []