Python教程

基于mirai的pythonqq机器人(graia的使用)

本文主要是介绍基于mirai的pythonqq机器人(graia的使用),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

#writen by 10班14号
graia是mirai的一个python库
网上也有很多配置教程但我在使用的过程中任然会碰到许多他们没有讲到的问题,在找到官方群问明白之后觉得和大家分享一下如何解决这些问题

1.mah和mcl版本不适配问题
在这里插入图片描述
为了演示错误找了1.0.3的mcl和2.0.2的mah
目前最稳定的版本是1.0.5的mcl和1.12.0mah
下载地址为https://github.com/iTXTech/mirai-console-loader/releases/tag/v1.0.5和https://github.com/project-mirai/mirai-api-http/releases/tag/v1.12.0
使用的话个人看来好像不需要有些教程那么麻烦
将正确的版本的mcl和mah下载之后,cd到mcl路径输入mcl,看到最后mirai-console started successfully.输入exit关闭。然后把mah放到plugins里面之后再次启动mcl就可以了

2.控制台里正常输出没有红字报错,但在python运行实例时出现导入错误
请使用在这里插入图片描述
这个对python版本好像也有要求,选择python3.8以上的版本比较好,否则会出现导入错误比如她的这个ImportError: cannot import name ‘BaseDispatcher’ from ‘graia.broadcast.entities.event’ 在这里插入图片描述
pip下载graia-application-mirai的时候不要懒请手动指定版本

3下面是我个人写的机器人

# -*- coding: UTF-8 -*-
import os, random, time,json
from lxml import etree
from graia.broadcast import Broadcast, BaseEvent
from graia.application.entry import *
from graia.application.message.elements.internal import *
import requests
from graia.scheduler import timers
import graia.scheduler
from graia.application.event.mirai import FriendRecallEvent, GroupRecallEvent
import random
accout=234654570
def getchat(msg):#智能聊天接口,自己找
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'userid': '*****',
        'key': '71c13002104340c58**********************',
        'info': msg,
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        return r.get('text')
    except:
        return
def cos():
    #cos
    res=requests.get('http://ovooa.com/API/cosplay/api.php?type=text')
    return res.text
def meizi():
    #随机妹子
    src=random.choice(['http://ovooa.com/API/meinv/api.php?m=1','http://ovooa.com/API/meizi/api.php/?type=text'])
    s = requests.get(src)
    return s.text
def lovehouse():
    #爱情公寓名言
    res=requests.get('http://ovooa.com/API/aiqing/api.php')
    html = etree.HTML(res.text)
    return html.xpath('//body//text()')[0]
def dujitang():
    #毒鸡汤
    res = requests.get('http://ovooa.com/API/du/api.php')
    html = etree.HTML(res.text)
    return html.xpath('//body//text()')[0]
def xiaohua():
    #笑话
    res = requests.get('http://ovooa.com/API/xiaohua/api.php')
    html = etree.HTML(res.text)
    return html.xpath('//body//text()')[0]
def raokouling():
    #绕口令
    res = requests.get('http://ovooa.com/API/rao/api.php?type=text')
    html = etree.HTML(res.text)
    return html.xpath('//body//text()')[0]
def get_url(picurl):
    res=requests.get(f'http://ovooa.com/API/QR/api.php?url={picurl}',timeout=(4,4))
    return res.text
def vipmusic(name,n=1):
    res=requests.get(f'http://ovooa.com/API/QQ_Music/?Skey=&uin=&msg={name.strip()}&n={n}')
    html=etree.HTML(res.text)
    print(f'http://ovooa.com/API/QQ_Music/?Skey=&uin=&msg={name}&n={n}')
    return json.loads(html.xpath('/html//text()')[0])['data']['music']
def qqkandian(key):
    url = "https://cgi.kandian.qq.com/trpc.tkdqq.kd_share_video_recommend.ShareVideoRecommend/GetFeed?g_tk=0&bkn=0"
    data = {"user": {"account": {"account_type": 1, "user_id": "0", "req_recommend_flag": 0}},
            "device": {"app_version": "0", "qua": "", "os": 3, "device_id": "", "terminal_id": "", "app_type": 3,
                       "guid": "", "ip": "", "network": 0}, "share_rowkey": key,
            "page": {"tab_id": "", "rowkeys": [key], "load_more_count": 0, "refresh_count": 0,
                     "load_type": 1}, "cookie": "", "ext": {}}
    return requests.post(url, json=data).json()['result']['feedData']['feeds'][0]['card']['feed']['tweet']['post']['video']['url']
loop = asyncio.get_event_loop()
bcc = Broadcast(loop=loop)
sche = graia.scheduler.GraiaScheduler(loop=loop, broadcast=bcc)
app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host="http://localhost:10008",  # 填入 httpapi 服务运行的地址
        authKey="yszzsyszzs",  # 填入 authKey
        account=accout,  # 你的机器人的 qq 号
        websocket=True  # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
    )
)

s_group=[1028646382]
s_friend=[1653490853,2043467698]
@bcc.receiver("FriendMessage")
async def friend_message_listener(message: MessageChain, app: GraiaMiraiApplication, friend: Friend):
    if message.get(FlashImage):
        URL = message.get(FlashImage)[0].url
        await app.sendFriendMessage(friend, MessageChain.create([Plain('机器人检测到你发送闪照'), Image.fromNetworkAddress(URL)]))
    if message.get(App):
        con=message.get(App)[0].content
        con=json.loads(con)
        url=con['meta']['data']['contentJumpUrl']
        key=url.split('&')[3].split('=')[1]
        await  app.sendFriendMessage(friend, MessageChain.create([Plain(qqkandian(key))]))
    if 'help' in message.asDisplay():
        await app.sendFriendMessage(friend, MessageChain.create(
            [Plain('1.cos图一张\n2.随机妹子图一张\n3.爱情公寓名言\n4.毒鸡汤\n5.笑话\n6.绕口令\n(输入前面数字序号即可)')]))
    elif '1' in message.asDisplay():
        await  app.sendFriendMessage(friend, MessageChain.create([Image.fromNetworkAddress(cos())]))
    elif '2' in message.asDisplay():
        await  app.sendFriendMessage(friend, MessageChain.create([Image.fromNetworkAddress(meizi())]))
    elif '3' in message.asDisplay():
        await  app.sendFriendMessage(friend, MessageChain.create([Plain(lovehouse())]))
    elif '4' in message.asDisplay():
        await  app.sendFriendMessage(friend, MessageChain.create([Plain(dujitang())]))
    elif '5' in message.asDisplay():
        await  app.sendFriendMessage(friend, MessageChain.create([Plain(xiaohua())]))
    elif '6' in message.asDisplay():
        await  app.sendFriendMessage(friend, MessageChain.create([Plain(raokouling())]))
    elif '点歌'in message.asDisplay():
        mname=message.asDisplay().split('点歌')[-1]
        res=vipmusic(mname)
        await app.sendFriendMessage(friend,MessageChain.create([Plain(res)]))
    elif message.get(Image):
        await app.sendFriendMessage(friend,MessageChain.create([Plain(get_url(message.get(Image)[0].url))]))
    else:
        await app.sendFriendMessage(friend, MessageChain.create([Plain(getchat(message.asDisplay()) + '(智能回复)')]))


@bcc.receiver("GroupMessage")
async def group_message_listener(message: MessageChain, app: GraiaMiraiApplication, group: Group, member: Member):
    message.get(Voice)
    if message.get(FlashImage):
        URL = message.get(FlashImage)[0].url
        await app.sendFriendMessage(1653490853, MessageChain.create(
            [Plain(f'{member.id}在{group.name}发送闪照:'), Image.fromNetworkAddress(URL)]))
    if message.get(App):
        con=message.get(App)[0].content
        con=json.loads(con)
        url=con['meta']['data']['contentJumpUrl']
        key=url.split('&')[3].split('=')[1]
        await  app.sendGroupMessage(group,MessageChain.create([Plain(qqkandian(key))]))
    if str(accout) in message.asDisplay():
        if 'help' in message.asDisplay().replace(f'@{accout}',''):
            await app.sendGroupMessage(group,MessageChain.create([Plain('1.cos图一张\n2.随机妹子图一张\n3.爱情公寓名言\n4.毒鸡汤\n5.笑话\n6.绕口令\n')]))
        elif '1' in message.asDisplay().replace(f'@{accout}',''):
            mes=await  app.sendGroupMessage(group,MessageChain.create([At(member.id),Image.fromNetworkAddress(cos())]))
            # time.sleep(4)
            # await app.revokeMessage(mes)
        elif '2' in message.asDisplay().replace(f'@{accout}',''):
            mes=await  app.sendGroupMessage(group,MessageChain.create([At(member.id),Image.fromNetworkAddress(meizi())]))
            # time.sleep(4)
            # await app.revokeMessage(mes)
        elif '3' in message.asDisplay().replace(f'@{accout}',''):
            await  app.sendGroupMessage(group,MessageChain.create([At(member.id),Plain(lovehouse())]))
        elif '4' in message.asDisplay().replace(f'@{accout}',''):
            await  app.sendGroupMessage(group,MessageChain.create([At(member.id),Plain(dujitang())]))
        elif '5' in message.asDisplay().replace(f'@{accout}',''):
            await  app.sendGroupMessage(group,MessageChain.create([At(member.id),Plain(xiaohua())]))
        elif '6' in message.asDisplay().replace(f'@{accout}',''):
            await  app.sendGroupMessage(group,MessageChain.create([At(member.id),Plain(raokouling())]))
        elif '点歌' in message.asDisplay():
            mname = message.asDisplay().split('点歌')[-1]
            res = vipmusic(mname)
            await app.sendGroupMessage(group, MessageChain.create([At(member.id),Plain(f'{res}(可下载)')]))
        else:
            await app.sendGroupMessage(group,MessageChain.create([At(member.id),Plain(f'{getchat(message)}')]))


@bcc.receiver("FriendRecallEvent")
async def recal_listener(message: FriendRecallEvent, app: GraiaMiraiApplication):
    a = await app.messageFromId(message.messageId)
    await app.sendFriendMessage(message.authorId, MessageChain.join(MessageChain.create([Plain('你刚刚撤回了:\n\n')]),a.messageChain.asSendable()))

@bcc.receiver('GroupRecallEvent')
async def group_recall(message: GroupRecallEvent, app: GraiaMiraiApplication, group: Group):
    mess = await app.messageFromId(message.messageId)
    member = await app.getMember(group.id, message.authorId)
    await app.sendFriendMessage(1653490853, MessageChain.join(
        MessageChain.create([Plain(f'{member.name}({message.authorId}) 刚刚在  {group.name}  撤回了:\n\n')]),
        mess.messageChain.asSendable()))

@bcc.receiver('NewFriendRequestEvent')
async def new_friend(event:NewFriendRequestEvent):
    await event.accept()
@bcc.receiver('MemberJoinRequestEvent')
async def menber_join(event:MemberJoinRequestEvent):
    await event.accept()
@bcc.receiver('BotInvitedJoinGroupRequestEvent')
async def menber_invite_join(event:BotInvitedJoinGroupRequestEvent):
    await event.accept()


# @sche.schedule(timers.every_custom_seconds(3))
# async def t(app: GraiaMiraiApplication):
#     await app.sendFriendMessage(2043467698, MessageChain.create([Plain(f'来张图{random.random()}')]))

app.launch_blocking()

可以获取机器人所在的群聊发送的闪照和群友撤回的消息,其他的一些接口挺有趣的就加上去了(虽然没什么用)

这篇关于基于mirai的pythonqq机器人(graia的使用)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!