GraiaProject / Application

一个设计精巧, 协议实现完备的, 基于 mirai-api-http 的即时聊天软件自动化框架.
https://graia-document.vercel.app/
GNU Affero General Public License v3.0
438 stars 63 forks source link

如何加入自己写的异步任务 #37

Closed SerinaNya closed 4 years ago

SerinaNya commented 4 years ago

现有 githublistener.py,可独立运行

from typing import Callable, List
import asyncio

import requests
import settings

async def event_handler(repo: str, req, Send):
    etag = None
    while True:
        if etag:
            req.headers.update({'If-None-Match': etag})
        _event = req.get(
            f'http://api.github.com.xiaojin233.cn/repos/{repo}/events?per_page=1')
        # Send(_event.status_code)
        hasXPollInterval = 'X-Poll-Interval' in _event.headers
        etag = _event.headers['ETag']
        x_poll_interval: int = int(
            _event.headers['X-Poll-Interval']) if hasXPollInterval else 60
        if _event.status_code == 200 and etag:
            _j = _event.json()
            for i in _j:
                thisType = i['type']
                if thisType == 'IssuesEvent':
                    await issuesOpend(repo, i['payload'], Send)
                elif thisType == 'PushEvent':
                    await pushEvent(repo, i, Send)
        await asyncio.sleep(x_poll_interval)

async def issuesOpend(repo: str, payload: dict, Send):
    this = payload['issue']
    if payload['action'] == 'opened':
        _number = this['number']
        _title = this['title']
        await Send(f'[{repo}] #{_number} {_title}')

async def pushEvent(repo: str, event: dict, Send):
    _operator = event['actor']['display_login']
    _commitsNumber = len(event['payload']['commits'])
    if _commitsNumber == 1:
        _desc = event['payload']['commits'][0]['message']
        await Send(
            f'[{repo}] {_operator} pushed {_commitsNumber} commit:\n{_desc}')
    else:
        await Send(f'[{repo}] {_operator} pushed {_commitsNumber} commits.')

req = requests.session()
req.headers.update({'Authorization': f'token {settings.github_access_token}'})
req.headers.update({'Accept': 'application/vnd.github.v3+json'})

def githubListener(send_func):
    l = list()
    loop = asyncio.get_event_loop()
    for repo in settings.github_listen_repos:
        l.append(event_handler(repo, req, send_func))
    loop.run_until_complete(asyncio.wait(l))

if __name__ == "__main__":
    async def s(m):
        print(m)
    githubListener(s)

我试图在 main.py 中调用它

# GitHub Listener
async def _send(message: str):
    await app.sendGroupMessage(settings.specialqq.commspt_group, MessageChain.create([Plain(message)]))
githubListener(_send)

但我知道这不行,因此来求教。我的目的是使这 2 个异步任务合并为一个任务运行(也就是一起运行了啦)

SerinaNya commented 4 years ago

oh,我解决了