示例#1
0
def main():
    print("""==============================
              _           _
             | |         | |
  _   _  ___ | |__   ___ | |_
 | | | |/ _ \| '_ \ / _ \| __|
 | |_| | (_) | |_) | (_) | |_
  \__, |\___/|_.__/ \___/ \__|
   __/ |
  |___/
==============================""")
    print("正在初始化...")

    if os.path.exists('yobot_config.json'):
        basedir = "."
    else:
        basedir = "./yobot_data"
    if os.path.exists(os.path.join(basedir, "yobot_config.json")):
        try:
            with open(os.path.join(basedir, "yobot_config.json"),
                      "r",
                      encoding="utf-8-sig") as f:
                config = json.load(f)
        except json.JSONDecodeError as e:
            print('配置文件格式错误,请检查配置文件。三秒后关闭')
            time.sleep(3)
            raise e from e
        token = config.get("access_token", None)
        if token is None:
            print("警告:没有设置access_token,这会直接暴露机器人接口")
            print("详见https://yobot.win/usage/access-token/")
    else:
        token = None

    try:
        tzlocal.get_localzone()
    except:
        print("无法获取系统时区,请将系统时区设置为北京/上海时区")
        sys.exit()

    cqbot = CQHttp(access_token=token, enable_http_post=False)
    sche = AsyncIOScheduler()
    bot = yobot.Yobot(
        data_path=basedir,
        scheduler=sche,
        quart_app=cqbot.server_app,
        bot_api=cqbot._api,
    )
    host = bot.glo_setting.get("host", "0.0.0.0")
    port = bot.glo_setting.get("port", 9222)

    @cqbot.on_message
    async def handle_msg(context):
        if context["message_type"] == "group" or context[
                "message_type"] == "private":
            reply = await bot.proc_async(context)
        else:
            reply = None
        if isinstance(reply, str) and reply != "":
            return {'reply': reply, 'at_sender': False}
        else:
            return None

    async def send_it(func):
        if asyncio.iscoroutinefunction(func):
            to_sends = await func()
        else:
            to_sends = func()
        if to_sends is None:
            return
        for kwargs in to_sends:
            await asyncio.sleep(5)
            await cqbot.send_msg(**kwargs)

    jobs = bot.active_jobs()
    if jobs:
        for trigger, job in jobs:
            sche.add_job(func=send_it,
                         args=(job, ),
                         trigger=trigger,
                         coalesce=True,
                         max_instances=1,
                         misfire_grace_time=60)
        sche.start()

    print("初始化完成,启动服务...")

    cqbot.run(
        host=host,
        port=port,
        debug=False,
        use_reloader=False,
        loop=asyncio.get_event_loop(),
    )
示例#2
0
def main():
    print("""==============================
              _           _
             | |         | |
  _   _  ___ | |__   ___ | |_
 | | | |/ _ \| '_ \ / _ \| __|
 | |_| | (_) | |_) | (_) | |_
  \__, |\___/|_.__/ \___/ \__|
   __/ |
  |___/
==============================""")
    print("正在初始化...")

    if os.path.exists("yobot_config.json"):
        with open("yobot_config.json", "r") as f:
            config = json.load(f)
        token = config.get("access_token", None)
        if token is None:
            print("*************************************************")
            print("警告:没有设置access_token,这会直接暴露机器人接口")
            print("这意味着允许机器人执行任何人的请求,造成安全隐患")
            print("请在yobot_config.json文件中修改access_token项")
            print("并使其与httpapi中的access_token保持一致")
            print("*************************************************")
            # input("(按回车继续)")
    else:
        token = None

    cqbot = CQHttp(access_token=token, enable_http_post=False)
    sche = AsyncIOScheduler()
    bot = yobot.Yobot(
        data_path=".",
        scheduler=sche,
        quart_app=cqbot.server_app,
        bot_api=cqbot._api,
    )
    host = bot.glo_setting.get("host", "0.0.0.0")
    port = bot.glo_setting.get("port", 9222)

    @cqbot.on_message
    async def handle_msg(context):
        if context["message_type"] == "group" or context[
                "message_type"] == "private":
            reply = await bot.proc_async(context)
        else:
            reply = None
        if isinstance(reply, str) and reply != "":
            return {'reply': reply, 'at_sender': False}
        else:
            return None

    async def send_it(func):
        if asyncio.iscoroutinefunction(func):
            to_sends = await func()
        else:
            to_sends = func()
        if to_sends is None:
            return
        tasks = [cqbot.send_msg(**kwargs) for kwargs in to_sends]
        await asyncio.gather(*tasks)

    jobs = bot.active_jobs()
    if jobs:
        for trigger, job in jobs:
            sche.add_job(func=send_it,
                         args=(job, ),
                         trigger=trigger,
                         coalesce=True,
                         max_instances=1,
                         misfire_grace_time=60)
        sche.start()

    print("初始化完成,启动服务...")

    cqbot.run(
        host=host,
        port=port,
        debug=False,
        use_reloader=False,
        loop=asyncio.get_event_loop(),
    )
示例#3
0
文件: main.py 项目: Adpex/yobot
import asyncio
import json
import os
import sys

from aiocqhttp import CQHttp
from apscheduler.schedulers.asyncio import AsyncIOScheduler

import yobot

rcnb = CQHttp(access_token='your-token', enable_http_post=False)

bot = yobot.Yobot()


@rcnb.on_message
async def handle_msg(context):
    if context["message_type"] == "group" or context[
            "message_type"] == "private":
        reply = bot.proc(context)
    else:
        reply = None
    if reply != "" and reply is not None:
        return {'reply': reply, 'at_sender': False}
    else:
        return None


async def send_it(func):
    to_sends = func()
    tasks = [rcnb.send_msg(**kwargs) for kwargs in to_sends]
示例#4
0
def main():
    print("正在初始化...")

    bot = yobot.Yobot()

    with open("yobot_config.json", "r") as f:
        config = json.load(f)
    host = config.get("host", "127.0.0.1")
    port = config.get("port", 9222)
    token = config.get("access_token", None)

    rcnb = CQHttp(access_token=token,
                  enable_http_post=False)

    @rcnb.on_message
    async def handle_msg(context):
        if context["message_type"] == "group" or context["message_type"] == "private":
            reply = bot.proc(context)
        else:
            reply = None
        if reply != "" and reply is not None:
            return {'reply': reply,
                    'at_sender': False}
        else:
            return None

    async def send_it(func):
        if asyncio.iscoroutinefunction(func):
            to_sends = await func()
        else:
            to_sends = func()
        if to_sends is None:
            return
        tasks = [rcnb.send_msg(**kwargs) for kwargs in to_sends]
        await asyncio.gather(*tasks)

    # # 如果要使用WebHook,可以用如下方法
    # # WehHook的端口号与机器人端口号相同
    # app = rcnb.server_app

    # from quart import request
    # @app.route("/webhook",  # webhook路径
    #            methods=['POST', 'GET'],  # 允许get和post
    #            host="0.0.0.0")  # 允许所有网络访问
    # async def webhook():
    #     if request.method = "GET":
    #         return("use post!")
    #     data = await request.get_data()  # 如果方式是post,获取post内容
    #     text = data.decode("utf-8")  # 将post解码为字符串
    #     await rcnb.send_msg(message_type="private",  # 私聊发送消息
    #                         user_id=123456789,  # QQ号
    #                         # group_id=123456789, # 如果message_type是"group"则用group_id
    #                         message="text")  # 内容

    jobs = bot.active_jobs()
    if jobs:
        sche = AsyncIOScheduler()
        for trigger, job in jobs:
            sche.add_job(func=send_it,
                         args=(job,),
                         trigger=trigger,
                         coalesce=True,
                         max_instances=1,
                         misfire_grace_time=60)
        sche.start()

    print("初始化完成,启动服务...")

    rcnb.run(host=host, port=port)