return msg @bot.on_notice('group_increase') # 上面这句等价于 @bot.on('notice.group_increase') async def handle_group_increase(context): info = await bot.get_group_member_info(group_id=context['group_id'], user_id=context['user_id']) nickname = info['nickname'] name = nickname if nickname else '新人' await bot.send( context, message='欢迎【{}】加入本群~\n友情提示:{}可以免费下载CSDN资源哦!\n-help 查看帮助'.format( name, config.default_qq_name), at_sender=False, auto_escape=True) ''' @bot.on_request('group', 'friend') # 上面这句等价于 @bot.on('request.group', 'request.friend') async def handle_group_request(context): if context['message'] != 'some-secret': # 验证信息不符,拒绝 return {'approve': False, 'reason': '你填写的验证信息有误'} return {'approve': True} ''' if __name__ == '__main__': bot.run(host='127.0.0.1', port=8800)
def mixin_dict(): global d minutes = 0 while True: # 1 分钟更新一次 minutes = minutes + 1 if minutes % 60 == 0: print('%s hours pass' % (minutes / 60)) ld_dict = ld.load_search_info() d = {**ld_dict} time.sleep(60) t1 = threading.Thread(target=mixin_dict, name='loop') t1.start() # docker的配置 HOST = '172.18.0.1' PORT = 12399 # 这里是coolq接收到qq信息,然后发送到这个python服务的端口。 # 所以也就是这个python服务,接收到这个消息的端口 # 在 coolq 的docker容器里,这个是在 */coolq/app/io.github.richardchien.coolqhttpapi/config/(qq号).ini 里配置的 # 由于容器不能通过 127.0.0.1 直接访问宿主机的端口,因此,需要通过执行 ip addr show docker0 命令来查看宿主机的端口 # 举例来说,我的server执行这个命令,获得的宿主机的 ip 是 172.18.0.1 (即,容器访问 172.18.0.1 这个地址是访问宿主机) # 于是修改那个ini配置文件:post_url = http://172.18.0.1:34519 # 这里的host可以保持要和那个ip地址保持一样,port也是 bot.run(host=HOST, port=PORT)
"9222", convert=lambda x: int(x), check=str.isdigit) default_config = { "host": host, "port": port, "run-as": "python", "super-admin": [], "black-list": [], "setting-restrict": 3, "auto_update": True, "update-time": "3:30", "show_jjc_solution": "url", "gacha_on": True, "preffix_on": False, "preffix_string": "", "zht_in": False, "zht_out": False } with open("yobot_config.json", "w") as f: json.dump(default_config, f) jobs = bot.active_jobs() if jobs: sche = AsyncIOScheduler() for trigger, job in jobs: sche.add_job(send_it, trigger=trigger, args=(job, )) sche.start() rcnb.run(host=host, port=port)
def main(): import sys cur_dir = os.path.split(os.path.realpath(__file__))[0] sys.path.append(os.path.realpath(os.path.join(cur_dir, 'lib'))) sys.path.append(cur_dir) import logging from quart.logging import default_handler import const const.workpath = os.path.join(cur_dir, '..') const.cachepath = os.path.join(const.workpath, 'cache') const.datapath = os.path.join(const.workpath, 'data') const.user_profile_path = os.path.join(const.datapath, 'user_profile') const.asset_card_path = os.path.join(const.datapath, 'image', 'assets', 'cards') const.asset_card_thumb_path = os.path.join(const.datapath, 'image', 'assets', 'cards', 'thumb') const.asset_event_path = os.path.join(const.datapath, 'image', 'assets', 'events') const.asset_gacha_path = os.path.join(const.datapath, 'image', 'assets', 'gachas') const.asset_resource_path = os.path.join(const.datapath, 'image', 'assets', 'res') if not os.path.exists(const.user_profile_path): os.makedirs(const.user_profile_path) if not os.path.exists(const.asset_card_path): os.makedirs(const.asset_card_path) if not os.path.exists(const.asset_card_thumb_path): os.makedirs(const.asset_card_thumb_path) if not os.path.exists(const.asset_gacha_path): os.makedirs(const.asset_gacha_path) if not os.path.exists(const.asset_resource_path): os.makedirs(const.asset_resource_path) logger_handler = logging.FileHandler(os.path.realpath(os.path.join(const.workpath, 'log/app.log'))) logger_handler.setFormatter(logging.Formatter('[%(asctime)s] %(levelname)s in %(module)s: %(message)s')) cq_server = CQHttp(enable_http_post=False) cq_server.logger.removeHandler(default_handler) cq_server.logger.addHandler(logger_handler) cq_server.logger.setLevel(logging.INFO) cq_server.logger.info('begin create bot') if not os.path.exists(const.datapath): cq_server.logger.warn(f'running without data') os.mkdir(const.datapath) def handle_trace(*exc_info): def on_trace_back(type, value, tb): import linecache stacks = [] localvars = [] try: while tb: f = tb.tb_frame c = f.f_code linecache.checkcache(c.co_filename) line = linecache.getline(c.co_filename, f.f_lineno, f.f_globals) stacks.append('File "%s", in %s\n > %d: %s' % (c.co_filename, c.co_name, f.f_lineno, line.strip() if line else "N/A")) f.f_locals.pop("__builtins__", None) localvars.append('\n'.join((("\t%19s : %s" % (n, repr(v)[:128])) for n, v in f.f_locals.items()))) tb = tb.tb_next except Exception as e: stacks.append(str(e)) stacks.append("%s" % type.__name__) localvars.append(" > %s" % str(value)) trace = "\n".join(("%s\n%s" % (s, l) for s, l in zip(stacks, localvars))) return trace cq_server.logger.error("Unhandled exception: %s", on_trace_back(*exc_info)) sys.excepthook = handle_trace bot = create_bot(cq_server) if not bot: return import socket ip_address = socket.gethostbyname(socket.gethostname()) cq_server.logger.info('bot created, bind success %s', bot.__class__.__name__) cq_server.run(host=ip_address, port=8080, debug=False)
pic_url = await daemon_reids._pool.get(getted_pid) pic_url = pic_url.decode('utf-8') infos = await daemon_reids._pool.hget("informations", getted_pid) splited = infos.decode('utf-8').split('$`$~') title, author = splited[0], splited[1] rvalue = os.system( f'wget --header="Referer: https://www.pixiv.net" -P {CWD_PATH} {pic_url}' ) if rvalue == 0: pic_infos[getted_pid] = (title, author) with open(os.path.join(CWD_PATH, 'pic_infos.pickle'), 'wb') as fa: pickle.dump(pic_infos, fa) await asyncio.sleep(2) else: await asyncio.sleep(120) async def tuling_everyday(): global tuling_count while True: await asyncio.sleep(86400) tuling_count = 0 loop = asyncio.get_event_loop() loop.create_task(download_pics()) loop.create_task(tuling_everyday()) bot.run(host='172.18.0.4', port=8700)
return '\n' + '-' * 56 @bot.on_notice('group_increase') # 上面这句等价于 @bot.on('notice.group_increase') async def handle_group_increase(context): info = await bot.get_group_member_info(group_id=context['group_id'], user_id=context['user_id']) nickname = info['nickname'] name = nickname if nickname else '新人' await bot.send( context, message='欢迎【{}】加入本群~\n友情提示:{}可以免费下载CSDN资源哦!\n-help 查看帮助'.format( name, config.default_qq_name), at_sender=False, auto_escape=True) ''' @bot.on_request('group') # 上面这句等价于 @bot.on('request.group', 'request.friend') async def handle_group_request(context): if context['message'] == 'Psyduck~': return {'approve': True} # 验证信息不符,拒绝 return {'approve': False, 'reason': '请输入正确的入群口令'} ''' if __name__ == '__main__': bot.run(host='127.0.0.1', port=config.psyduck_port)
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(), )
await bot.send(context, f'暂无数据') return if context['message'][:4] == '世界查询': zones = {} r = get_session() data = get_country(r) for i in data: zones[i[ "continents"]] = zones.get(i["continents"], '') + \ f'{i["provinceName"]} 确诊:{i["confirmedCount"]} 治愈:{i["curedCount"]} 死亡:{i["deadCount"]}\n' if context['message'][4:] in zones: await bot.send(context, zones[context['message'][4:]]) return else: message = f'可用地区\n' for i in zones.keys(): message += f'{i} ' await bot.send(context, message) return if context['message'] == '辟谣': r = get_session() data = get_rumor(r) message = '' for i in data: message += f'★{i["title"]}\n※{i["mainSummary"]}\n✧{i["body"]}\n' message += "更多信息请到丁香园网站查询" await bot.send(context, message) bot.run(host='127.0.0.1', port=6700)
try: xhup_msg = cq_2_xhup(context) await xhup_club_ws.send(json.dumps(xhup_msg)) except websockets.ConnectionClosed as e: logger.warning(e) logger.warning("后端连接断开,三秒后自动重连") await asyncio.sleep(3) xhup_club_ws = await get_xhup_club_ws() else: logger.info("后端尚未连接,现在尝试连接。") xhup_club_ws = await get_xhup_club_ws() # @bot.on_notice('group_increase') # async def handle_group_increase(context): # await bot.send(context, message='欢迎新人~', # at_sender=True, auto_escape=True) if __name__ == '__main__': # obtain the event loop from asyncio loop = asyncio.get_event_loop() # 先连接上 xhup-club-api 后端 loop.run_until_complete(get_xhup_club_ws()) # 后台跑这个任务,将 xhup 消息转发给 CoolQ loop.create_task(handle_xhup_club_event()) # 启动 aiocqhttp bot.run(host=BotConfig.HOST, port=BotConfig.PORT)
bot = CQHttp(enable_http_post=False) @bot.on_message() async def handle_msg(context): # 判断群号,不复读个别破群 group_id = context.get('group_id') # 判断QQ号,不复读个别幺儿 sender_qq = context.get('user_id') if group_id in [617166836]: return "" if group_id in [140399496]: return "" # 不复读狗栀 if sender_qq in [1400525500]: return "" message = context['message'] # 增加对/斜眼笑等表情的处理 await bot.send( context, emoji.emoji2cq(message).replace('吗', "").replace('?', '!').replace('?', '!')) # await bot.send(context, context['message'].replace('吗', "").replace('?', '!').replace('?', '!')) bot.run(host='127.0.0.1', port=9898) # 今儿居然就加上了复读表情! # 此项目已抛弃,改用java
import time from aiocqhttp import CQHttp bot = CQHttp(api_root="http://usf.lietxia.bid:5700") @bot.on_message() async def handle_msg(context): return_text = "" if context["message"] == "你好": return_text = "你也好" if context["message"] == "今天": return_text = time.asctime(time.localtime(time.time())) return {"reply": return_text} @bot.on_notice("group_increase") async def handle_group_increase(context): await bot.send(context, message="欢迎新人~", at_sender=True, auto_escape=True) return @bot.on_request("group", "friend") async def handle_request(context): return {"approve": True} bot.run(host="0.0.0.0", port=8080)
except BaseException as e: print('cmd', e) reply_msg = '' if reply_msg: G.cmd_stats[matched_cmd] = time.time() bot.logger.info('Msg processed by matched cmd: {}'.format( cfg.bot_commands[matched_cmd][CB_FUNC].__name__)) resp_json = { 'reply': reply_msg, 'at_sender': cfg.bot_commands[matched_cmd][F_AT] } if resp_json: return resp_json else: return if __name__ == '__main__': # add tasks for func, job_time in cfg.scheduled_tasks: G.scheduler.add_job(func, trigger='cron', args=(G, bot), **job_time) def _start_scheduler(): # use configure to make sure scheduler get the correct event loop G.scheduler.configure(cfg.scheduler_opt) G.scheduler.start() bot.server_app.before_serving(_start_scheduler) bot.run(host=cfg.host, port=cfg.port, debug=True)
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)
import db_helper from aiocqhttp import CQHttp bot = CQHttp(access_token='123', secret='abc') @bot.on_message # 上面这句等价于 @bot.on('message') async def handle_msg(context): n = 1 group_id = 747776374 lst = await bot.call_action(action='get_group_member_list', group_id=group_id) for a in db_helper.find_all('', 0, 100000): if a.qq_group == '-1': for b in lst: if str(b['user_id']) == a.qq_num: a.qq_group = str(group_id) a.save() print('save (%s) ==> %d' % (a.id, n)) n += 1 bot.run(host='127.0.0.1', port=8761)
await asyncio.sleep(0.8) await privite_hello(event.user_id) @bot.on_request('group') async def _(event): return def load_corpus(): global CORPUS, TRIGGER, REFUSE, BOOK CORPUS = Path('Chi-Corpus/common.txt').read_text('utf-8').splitlines() CORPUS = list(filter(lambda c: '?' not in c, CORPUS)) TRIGGER = Path('Chi-Corpus/trigger.txt').read_text('utf-8').splitlines() REFUSE = Path('Chi-Corpus/refuse.txt').read_text('utf-8').splitlines() BOOK = Path('answers.txt').read_text('utf-8').splitlines() def start_in(msg, leading_list): for i in leading_list: if msg.startswith(i): return True return False if __name__ == '__main__': load_corpus() bot.run(host='localhost', port=52311)
names = [ icon_map[item["rarity"]] + " " + item["rarity"] + ": " + item["name"] for item in contet["item"] ] # names = [item["rarity"] + ": " + item["name"] for item in contet["item"]] await bot.send(context, '恭喜你获得:\r\n' + '\r\n'.join(names), at_sender=True) print(contet) for i in contet["collection"]: await bot.send(context, '恭喜你集齐套装[' + i + ']', at_sender=True) elif resp.status == 404: await bot.send(context, "抱歉,您的抽奖次数不足", at_sender=True) else: await bot.send(context, "抱歉,抽奖服务好像挂了唉!") except ApiError as e: print(e) await bot.send(context, "抱歉,抽奖服务好像挂了唉!!") except Exception as e: print(e) await bot.send(context, "抱歉,抽奖服务好像挂了唉!!!") if __name__ == '__main__': bot.run(host='localhost', port=8888) print(bot)
ret = group_message_handler[context["group_id"]](context) else: print("Unknown message type. Please check.") return if isinstance(ret, dict) and "reply" in ret: return ret elif ret is None: return elif isinstance(ret, list): await sendmessages(ret) async def sendmessages(messages): coros = [] for context, message in messages: # Debug: 去除QQ号后面添加的id # if "user_id" in context: # context["user_id"] = context["user_id"] // 10 coros.append(bot.send(context, message)) await asyncio.gather(*coros) if __name__ == "__main__": try: bot.run(host="127.0.0.1", port=8090) except KeyboardInterrupt: print("Exit.")
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(), )
return { 'reply': context['message'], 'at_sender': False } # 返回给 HTTP API 插件,走快速回复途径 @bot.on_notice('group_increase') # 上面这句等价于 @bot.on('notice.group_increase') async def handle_group_increase(context): info = await bot.get_group_member_info(group_id=context['group_id'], user_id=context['user_id']) nickname = info['nickname'] name = nickname if nickname else '新人' await bot.send(context, message='欢迎{}~'.format(name), at_sender=True, auto_escape=True) @bot.on_request('group', 'friend') # 上面这句等价于 @bot.on('request.group', 'request.friend') async def handle_group_request(context): if context['message'] != 'some-secret': # 验证信息不符,拒绝 return {'approve': False, 'reason': '你填写的验证信息有误'} return {'approve': True} if __name__ == '__main__': bot.run(host='127.0.0.1', port=8080)
at_user = False context = self.extra if self.stype == SessionType.GROUP: if reciever: context['user_id'] = reciever.uid at_user = True context['message_type'] = 'group' context['group_id'] = self.handle elif self.stype == SessionType.FRIEND or self.stype == SessionType.TEMPORARY: context['message_type'] = 'private' context['user_id'] = self.handle import asyncio newLoop = asyncio.new_event_loop() asyncio.set_event_loop(newLoop) loop = asyncio.get_event_loop() loop.run_until_complete( CQBot.send(context, message=message, at_sender=at_user)) loop.close() if __name__ == '__main__': import sys if len(sys.argv) == 1 or sys.argv[1] == 'start': meiri.Run() CQBot.run(host='127.0.0.1', port=8080) elif sys.argv[1] == 'stop': meiri.Stop() elif sys.argv[1] == 'restart': meiri.Stop() meiri.Run()
return {'approve': True} async def send_early_msg(): await asyncio.sleep(int(random.random() * 60 * 60) + 900) time_format = "%Y-%m-%d %H:%M:%S" bj_offset = timezone(timedelta(hours=8)) bj_datetime = datetime.now(bj_offset) re = random.choice(REPLY['on_early']) for group_id in SETTINGS['MEMTION_GROUP']: await bot.send({'group_id': group_id}, message=re) async def send_new_day_msg(): for group_id in SETTINGS['MEMTION_GROUP']: re = random.choice(REPLY['on_new_day']) await bot.send({'group_id': group_id}, message=re) def sche(): scheduler = AsyncIOScheduler() # TODO: fit for all environments with different timezone, this is for 0 timezone scheduler.add_job(send_early_msg, 'cron', hour="3", minute="0") scheduler.add_job(send_new_day_msg, 'cron', hour="0", minute="0") scheduler.start() if __name__ == '__main__': sche() bot.run(host='0.0.0.0', port=8090)
return "没有查询到你关于该群的屏蔽记录" shield.delete("{group}_{user}".format(group=group, user=context['user_id'])) return "已撤销你关于该群的callall屏蔽." commands = { "callme": callme, "call": call, "play_list": play_list, "leave": leave, "callall": callall, "shield": shielder, "unshield": unshield } @bot.on_message() async def handle_msg(context): if context["message"].split(" ")[0][0] == "/": if context["message"].split(" ")[0][1:] in commands: return { "reply": await commands[context["message"].split(" ")[0][1:]](context), 'at_sender': False } bot.run("localhost", 8695)