罗伯特

#bot.py
from unittest.mock import NonCallableMagicMock
from flask import Flask, request
import requests
import api
app = Flask(__name__)

'''监听端口,获取QQ信息'''
@app.route('/', methods=["POST"])
def post_data():
    '下面的request.get_json().get......是用来获取关键字的值用的,关键字参考上面代码段的数据格式'
    if request.get_json().get('message_type')=='private':
        uid = request.get_json().get('sender').get('user_id')
        message = request.get_json().get('raw_message')
        api.keywordForPerson(message,uid)
    if request.get_json().get('message_type')=='group':
        gid = request.get_json().get('group_id')
        uid = request.get_json().get('sender').get('user_id')
        message = request.get_json().get('raw_message')
        nick=request.get_json().get('sender').get('nickname')
        role=request.get_json().get('sender').get('role')
        api.keywordForGroup(message, gid, uid,nick,role)
    return 'OK'


if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1', port=5701)
#api.py
import person
import group
import requests
import re
import time
import json
import random



def help():
    return "天气:输入天气 地名,获取当地天气,默认为徐州天气\n双色球:输入双色球查看最新一期双色球开奖信息以及奖池累计金额\n扔瓶子:私聊罗伯特并发送以下内容:\n扔瓶子 发送者(可填匿名) 接受者(可填空) 内容\n来扔瓶子\n捞瓶子:发送捞瓶子来捞别人扔的瓶子\n帮助:输入/help,获取帮助"
def weather(message):
    try:
        city=message.split(' ')[1]
    except:
        city='徐州'
    try:
        ercode=requests.get(url='http://wthrcdn.etouch.cn/weather_mini?city='+city,timeout=1).text
    except:
        return "罗伯特被学校关起来了呜呜"
    if "invilad-citykey" in ercode:
        return "抱歉,您的输入有误,请检查后再试"
    weatherInfo=requests.get(url='http://wthrcdn.etouch.cn/weather_mini?city='+city).json()['data']['forecast'][0]
    ganmao=requests.get(url='http://wthrcdn.etouch.cn/weather_mini?city='+city).json()['data']['ganmao']
    fl=re.search(r"[0-9]+",weatherInfo['fengli']).group(0)
    hi=re.search(r"[0-9]+",weatherInfo['high']).group(0)
    lo=re.search(r"[0-9]+",weatherInfo['low']).group(0)
    weatherInfo=f"今日{city}天气{weatherInfo['type']},最高温度{hi}℃,最低温度{lo}℃,{weatherInfo['fengxiang']}{fl}级\n温馨提示,{ganmao}"
    return weatherInfo
def buquan(message,uid):
    #计算括号数量并自动补全
    def countBracket(message):
        countban=0
        for i in message:
            if i=='(':
                countban+=1
            if i==')':
                countban-=1
        countquan=0
        for i in message:
            if i=='(':
                countquan+=1
            if i==')':
                countquan-=1
        return {'ban':countban,'quan':countquan}
    #自动补全括号
    ban=countBracket(message)['ban']
    quan=countBracket(message)['quan']
    bu=""
    if not (ban or quan):
        return
    if ban>0:
        for i in range(ban):
            bu+=')'
    elif ban<0:
        for i in range(-ban):
            bu+='('
    if quan>0:
        for i in range(quan):
            bu+=')'
    elif quan<0:
        for i in range(-quan):
            bu+='('
    print(bu+f"[CQ:at,qq={uid}]帮你补括号")
    return bu+f"[CQ:at,qq={uid}]帮你补括号"
def theDoubleChromosphere(uid):
    tex=requests.get("http://www.cwl.gov.cn/fcpz/yxjs/ssq/").text
    #获取红球
    red=re.search(r"<div class=\"ssqRed-dom\">\[(.*?)\]</div>",tex).group(1)
    red=red.split(',')
    #获取蓝球
    blue=re.search(r"<div class=\"ssqBlue-dom\">\[(.*?)\]</div>",tex).group(1)
    blue=blue.split(',')
    #获取期号
    qh=re.search(r"<div class=\"ssqQh-dom\">(.*?)</div>",tex).group(1)
    #获取奖池
    pool=re.search(r"<div class=\"ssqPool-dom\">(.*?)</div>",tex).group(1)
    return f"第{qh}期开奖结果为:\n红球:{red}\n蓝球:{blue}\n奖池:{pool}\n[CQ:at,qq={uid}]害搁着等着干啥呢,赶紧买彩票去啊"
def sign(gid,uid,nick):
    today=time.strftime("%Y-%m-%d",time.localtime())
    groupUserInfo=group.readGroupUserInfo()
    try:
        thisGroupUserInfo=groupUserInfo[str(gid)]
    except:
        thisGroupUserInfo={}
        thisGroupUserInfo[str(uid)]={"nick": nick, "point": 0, "signTime": "", "ban": False}
    groupUserInfo[str(gid)]=thisGroupUserInfo
    try:
        thisUser=thisGroupUserInfo[str(uid)]
    except:
        thisUser={"nick": nick, "point": 0, "signTime": "", "ban": False}
        thisGroupUserInfo[str(uid)]=thisUser
    if thisUser['signTime']==today:
        return f"[CQ:at,qq={uid}]您今天已经签到过了,明天再来吧"
    else:
        thisUser['point']+=1
        thisUser['signTime']=today
        group.saveGroupUserInfo(groupUserInfo)
        return f"[CQ:at,qq={uid}]签到成功,您的积分为{thisUser['point']},明天再来吧"
def getQQ(message):
    try:
        qq=re.search(r"qq=(\d+)",message).group(1)
    except:
        qq=None
    return qq
def ban(gid,uid):
    groupUserInfo=group.readGroupUserInfo()
    thisGroupUserInfo=groupUserInfo[str(gid)]
    thisUser=thisGroupUserInfo[str(uid)]
    thisUser['ban']=True
    groupUserInfo[str(gid)]=thisGroupUserInfo
    group.saveGroupUserInfo(groupUserInfo)
    return f"好,我们不和[CQ:at,qq={uid}]玩"
def unban(gid,uid):
    groupUserInfo=group.readGroupUserInfo()
    thisGroupUserInfo=groupUserInfo[str(gid)]
    thisUser=thisGroupUserInfo[str(uid)]
    thisUser['ban']=False
    groupUserInfo[str(gid)]=thisGroupUserInfo
    group.saveGroupUserInfo(groupUserInfo)
    return f"好吧,我原谅你了[CQ:at,qq={uid}]"
def keywordForPerson(message, uid):
    if message[0:2]=='天气':
        person.sendMessage(weather(message),uid)
def isBan(gid,uid):
    groupUserInfo=group.readGroupUserInfo()
    thisGroupUserInfo=groupUserInfo[str(gid)]
    try:
        thisUser=thisGroupUserInfo[str(uid)]
        if thisUser['ban']:
            return True
        else:
            return False
    except:
        return False
def point(gid,uid):
    groupUserInfo=group.readGroupUserInfo()
    thisGroupUserInfo=groupUserInfo[str(gid)]
    try:
        thisUser=thisGroupUserInfo[str(uid)]
        return f"[CQ:at,qq={uid}]您的积分为{thisUser['point']}"
    except:
        return f"[CQ:at,qq={uid}]请先签到后重试"
def isAdmin(gid,uid):
    groupUserInfo=group.readGroupUserInfo()
    thisGroupUserInfo=groupUserInfo[str(gid)]
    try:
        thisUser=thisGroupUserInfo[str(uid)]
        if thisUser['admin']:
            return True
        else:
            return False
    except:
        return False
def giveAdmin(gid,uid):
    groupUserInfo=group.readGroupUserInfo()
    thisGroupUserInfo=groupUserInfo[str(gid)]
    try:
        thisUser=thisGroupUserInfo[str(uid)]
    except:
        thisUser={"nick": "nick", "point": 0, "signTime": "", "ban": False}
    thisUser['admin']=True
    thisGroupUserInfo[str(uid)]=thisUser
    groupUserInfo[str(gid)]=thisGroupUserInfo
    group.saveGroupUserInfo(groupUserInfo)
    return f"没问题,以后我就听你的啦[CQ:at,qq={uid}]"
def today(message):
    try:
        message=message.split(' ')
        message=message[1]
    except:
        message=None
        return f"请输入运势 星座来查询今日运势"
    if len(message)==2:
        message=message+"座"
    url="http://web.juhe.cn:8080/constellation/getAll"
    params={
        "key":"4a11bbcbf089edaf14c2d9bdb80c2ec4",
        "consName":message,
        "type":"today"
    }
    ys=requests.get(url=url,params=params).json()
    return f"{ys['name']}今日运势:\n综合指数:{ys['all']}%\n幸运色:{ys['color']}\n健康指数:{ys['health']}%\n爱情指数:{ys['love']}%\n财运指数:{ys['money']}%\n工作指数:{ys['work']}%\n幸运数字:{ys['number']}\n适配星座:{ys['QFriend']}\n总结:{ys['summary']}"
def minusPoint(gid,uid,point):
    groupUserInfo=group.readGroupUserInfo()
    thisGroupUserInfo=groupUserInfo[str(gid)]
    try:
        thisUser=thisGroupUserInfo[str(uid)]
    except:
        return f"[CQ:at,qq={uid}]请先签到后重试"
    if thisUser['point']-point < 0:
        return f"[CQ:at,qq={uid}]您的积分不足"
    thisUser['point']-=point
    thisGroupUserInfo[str(uid)]=thisUser
    groupUserInfo[str(gid)]=thisGroupUserInfo
    group.saveGroupUserInfo(groupUserInfo)
    return "OK"
def throwBottle(uid,message):
    try:
        me=message.split(" ",3)
        send=me[1]
        rec=me[2]
        con=me[3]
        with open('bottle.json','r') as f:
            bottle = json.load(f)
        nb={
            "QQ":str(uid),
            "send":send,
            "rec":rec,
            "con":con
        }
        bottle.append(nb)
        with open('bottle.json','w') as f:
            json.dump(bottle,f)
        return f"biu~~~瓶子被扔走啦,坐等被人打捞吧~~~"
    except:
        return "扔瓶子失败了,请检查内容格式是否为:\n扔瓶子 发送者(可填匿名) 接受者(可填空) 内容"
def getBottle(uid):
    with open('myBottles.json','r') as f:
        myBottles = json.load(f)      
    with open('bottle.json','r') as f:
        bottle = json.load(f)
    num=random.randint(0,len(bottle)-1)
    nb=bottle[num]
    bottle.remove(nb)
    try:
        myBottles[str(uid)].append(nb)
    except:
        myBottles[str(uid)]=[nb]
    with open('bottle.json','w') as f:
        json.dump(bottle,f)
    with open('myBottles.json','w') as f:
        json.dump(myBottles,f)
    return f"{nb['send']}扔给了{nb['rec']}一个瓶子,内容是:{nb['con']}"
def myBottles(uid):
    with open('myBottles.json','r') as f:
        myBottles = json.load(f)
    try:
        myBottles[str(uid)]
    except:
        return "您还没有瓶子呢,快去捞瓶子吧~~~"
    me=""
    for i in myBottles[str(uid)]:
        me+=f"{i['send']}扔给了{i['rec']}一个瓶子,内容是:{i['con']}\n"
    return f"[CQ:at,qq={uid}]您的瓶子有:\n{me}"
def cleanBottles(message,uid):
    num=message.split(" ")[1]
    with open('myBottles.json','r') as f:
        myBottles = json.load(f)
    try:
        myBottles[str(uid)]
    except:
        return f"[CQ:at,qq={uid}]您还没有瓶子呢,快去捞瓶子吧~~~"
    try:
        nb=myBottles[str(uid)].pop(int(num)-1)
        with open('myBottles.json','w') as f:
            json.dump(myBottles,f)
        return f"[CQ:at,qq={uid}]您摔碎了{nb['send']}扔给{nb['rec']}一个瓶子,内容是:{nb['con']}"
    except:
        return f"[CQ:at,qq={uid}]您还没有这个瓶子,快去捞一个吧"


def keywordForGroup(message, gid, uid,nick,role):
    if isBan(gid,uid) and not isAdmin(gid,uid):
        return
    if message[0:2]=='天气':
        group.sendMessage(weather(message),gid)
    elif message[0:2]=='运势':
        group.sendMessage(today(message),gid)
    elif message=="积分":
        group.sendMessage(point(gid,uid),gid)
    elif message[0:4]=="听他的话" and uid==405454586:
        group.sendMessage(giveAdmin(gid,getQQ(message)),gid)
    elif message[0:3]=='ban' and isAdmin(gid,uid):
        group.sendMessage(ban(gid,getQQ(message)),gid)
    elif message[0:5]=='unban' and isAdmin(gid,uid):
        group.sendMessage(unban(gid,getQQ(message)),gid)
    elif message=='/help':
        group.sendMessage(help(),gid)
    elif message[0:3]=='双色球':
        group.sendMessage(theDoubleChromosphere(uid),gid)
    elif message=="签到":
        group.sendMessage(sign(gid,uid,nick),gid)
    elif message=="捞瓶子":
        group.sendMessage(getBottle(uid),gid)
    elif message=="我的瓶子":
        group.sendMessage(myBottles(uid),gid)
    elif message[0:3]=="摔瓶子":
        group.sendMessage(cleanBottles(message,uid),gid)
    elif message=="无内鬼":
        group.sendMessage(f"[CQ:at,qq={uid}]穿件衣服吧你!你自己不恶sin吗?",gid)
    if re.search(r"[\(\)()]",message):
        group.sendMessage(buquan(message,uid),gid)
def keywordForPerson(message,uid):
    if message[0:3]=="扔瓶子":
        person.sendMessage(throwBottle(uid,message),uid)
#group.py
import json
import requests

#保存用户信息
def saveGroupUserInfo(userInfo):
    with open('userInfoOfGroup.json','w') as f:
        json.dump(userInfo,f)
#读取用户信息
def readGroupUserInfo():
    with open('userInfoOfGroup.json','r') as f:
        userInfo = json.load(f)
    return userInfo
#发送信息
def sendMessage(message,gid):
    url="http://127.0.0.1:5700/send_msg?group_id="+str(gid)+"&message="+message
    requests.get(url)