Loading... 我的qq机器人平时是用Screen挂在服务器上 ### 1.让机器人把中文翻译成日语 <img src="https://pic.imgdb.cn/item/61a5dac72ab3f51d91dc1dd2.jpg" alt="" width="540" height="282" align="bottom" /> 写这个小东西的原因是,我是一个虚假の二次元,有的时候讲话要用到の之类的东西来连接,又不想每次都打开手机浏览器百度;加上我的一个朋友的老师时不时让他们用英语做专业课作业,而她也是个不爱用手机浏览器和翻译软件的家伙,所以就拜托我。。。 这是个中译日的,改几行就变成了中译英和英译中的 这里使用了腾讯翻译的接口,用到的几个配置项要写在bot的env文件中 ``` #jp translater tencentcloud_common_region="" tencentcloud_common_secretid="" tencentcloud_common_secretkey="" ``` code: ```python from binascii import b2a_base64 from copy import deepcopy from hashlib import sha1 from hmac import new from random import randint from sys import maxsize, version_info from time import time from aiohttp import request from loguru import logger from nonebot import get_driver from nonebot.rule import Rule from nonebot.adapters import Bot, Event from nonebot.adapters.cqhttp.event import * from nonebot.exception import ActionFailed from nonebot.permission import * from nonebot.plugin import on_command from nonebot.typing import T_State from nonebot.matcher import * from nonebot.adapters.cqhttp.permission import * try: import ujson as json except ImportError: import json config=get_driver().config translater = on_command("日语") async def getReqSign(params: dict) -> str: commom = { 'Action': 'TextTranslate', 'Region': f'{config.tencentcloud_common_region}', 'Timestamp': int(time()), 'Nonce': randint(1, maxsize), 'SecretId': f'{config.tencentcloud_common_secretid}', 'Version': '2018-03-21', } params.update(commom) sign_str = 'POSTtmt.tencentcloudapi.com/?' sign_str += '&'.join('%s=%s' % (k, params[k]) for k in sorted(params)) secret_key = config.tencentcloud_common_secretkey if version_info[0] > 2: sign_str = bytes(sign_str, 'utf-8') secret_key = bytes(secret_key, 'utf-8') hashed = new(secret_key, sign_str, sha1) signature = b2a_base64(hashed.digest())[:-1] if version_info[0] > 2: signature = signature.decode() return signature @translater.handle() async def translate(bot:Bot,event:Event,state:T_State): if event.get_session_id() not in ['2096691198']: await translater.finish("只有SUPERUSER可以在私聊中使用此功能") sourcetext=event.get_message() if not sourcetext: message="翻译格式:#日语 待翻译的内容" await translater.finish(message) endpoint = 'https://tmt.tencentcloudapi.com' params = { 'Source': 'zh', 'SourceText': sourcetext, 'Target': 'ja', 'ProjectId': 0, } params['Signature'] = await getReqSign(params) async with request( 'POST', endpoint, data=params ) as resp: code = resp.status if code != 200: message = '网络异常,请稍后再试' await translater.finish(message) data = json.loads(await resp.read())['Response'] message = data['TargetText'] await translater.finish(message) ``` ### 2.企鹅银行 <img src="https://pic.imgdb.cn/item/61a5dcce2ab3f51d91dd37fa.jpg" alt="" width="540" height="762" align="bottom" /> 写这个是因为。。这是我和我的朋友用来请客吃饭的过家家游戏。对方答应请你吃饭/喝茶/玩乐就会变成你的企鹅银行账户资产。 美中不足的是触发一次事件的session保持的时间有点短,想做什么操作都得迅速点,否则就得再#bank_user召唤一次 包含了: `__init__.py` ```python from nonebot import get_driver from nonebot.plugin import on_command from nonebot.matcher import * from nonebot.adapters import Bot, Event from nonebot.typing import T_State import sqlite3 import os from .create_initial_database import create_database import time config = get_driver().config bank_manager = f'{config.bank_manager}' bank_user = f'{config.bank_user}' # 管理员事件响应器 manager = on_command('bank_manager', priority=1) @manager.handle() async def manager_welcome(bot: Bot, event: Event, state: T_State): if event.get_session_id() != bank_manager: await manager.finish('Permission denied.') if not os.path.exists('./database.db'): create_database() # 打印管理员菜单 state['menu'] = ''' ===================== 欢迎使用Penguin Bank管理员面板 --------------------- Version 1.0可以处理以下业务: 1.查询用户资产 2.变动用户资产 3.删除一项资产名目 4.查看可消费项目列表 5.编辑或增加一条可消费项目 6.删除一条可消费项目 7.查看银行业务日志(暂未开通) ===================== 请输入对应序号处理业务> ''' @manager.got("task", prompt='{menu}') async def manager_task_handle(bot: Bot, event: Event, state: T_State): task_id = state['task'] if task_id == '1': # 查看资产 conn = sqlite3.connect('./database.db') c = conn.cursor() c.execute("INSERT INTO LOG (TIME,IDENTITY,CLASS) \ VALUES(?,?,?)", (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 1, 5)) cursor = c.execute("SELECT NAME,AMOUNT FROM ASSETS") if len(list(cursor)) == 0: conn.commit() conn.close() await manager.finish('用户还没有资产') else: message_send = '币种'.ljust(12)+'数目'.ljust(12) cursor = c.execute("SELECT NAME,AMOUNT FROM ASSETS") for row in cursor: message_send += '\n' + ('%s' % (row[0])).ljust(12) + ('%d' % (row[1])).ljust(12) conn.commit() conn.close() await manager.finish(message_send) elif task_id == '2': # 变动资产 message_send = '用户现有资产:' conn = sqlite3.connect('./database.db') c = conn.cursor() cursor = c.execute("SELECT NAME,AMOUNT FROM ASSETS") if len(list(cursor)) == 0: message_send += '\n用户还没有资产' await manager.send(message_send) else: message_send += '\n'+'币种'.ljust(12)+'数目'.ljust(12) cursor = c.execute("SELECT NAME,AMOUNT FROM ASSETS") for row in cursor: message_send += '\n' + ('%s' % (row[0])).ljust(12) + ('%d' % (row[1])).ljust(12) await manager.send(message_send) conn.close() state['notes'] = "增加资产条目或变动资产数目请输入:“币种 数目”" elif task_id=='3': #删除一项资产条目 message_send = '' conn = sqlite3.connect('./database.db') c = conn.cursor() cursor = c.execute("SELECT NAME FROM ASSETS") if len(list(cursor)) == 0: message_send += '用户还没有资产呢...' await manager.send(message_send) else: message_send += '用户现有资产有:\n'+'币种'.ljust(12) cursor = c.execute("SELECT NAME FROM ASSETS") for row in cursor: message_send += '\n' + \ ('%s' % (row[0])).ljust(12) await manager.send(message_send) conn.close() state['notes']='输入要删除的名目' elif task_id == '4': #查看可消费项目列表 conn = sqlite3.connect('./database.db') c = conn.cursor() c.execute("INSERT INTO LOG (TIME,IDENTITY,CLASS) \ VALUES(?,?,?)", (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 1, 8)) cursor = c.execute("SELECT NAME,PRICE,CURRENCY FROM GOODS") if len(list(cursor)) == 0: conn.commit() conn.close() await manager.finish('用户还没有可消费项目') else: message_send = '项目'.ljust(12)+'价格'.ljust(12)+'货币种类'.ljust(12) cursor = c.execute("SELECT NAME,PRICE,CURRENCY FROM GOODS") for row in cursor: message_send += '\n' + \ ('%s' % (row[0])).ljust(12) + ('%d' % (row[1])).ljust(12)+('%s'%(row[2])).ljust(12) conn.commit() conn.close() await manager.finish(message_send) elif task_id == '5': #编辑或增加一条可消费项目 message_send = '用户可消费项目:' conn = sqlite3.connect('./database.db') c = conn.cursor() cursor = c.execute("SELECT NAME,PRICE,CURRENCY FROM GOODS") if len(list(cursor)) == 0: message_send += '\n用户还没有可消费项目' await manager.send(message_send) else: message_send += '\n'+'项目'.ljust(12)+'价格'.ljust(12)+'货币种类'.ljust(12) cursor = c.execute("SELECT NAME,PRICE,CURRENCY FROM GOODS") for row in cursor: message_send += '\n' + \ ('%s' % (row[0])).ljust(12) + ('%d' % (row[1])).ljust(12)+('%s'%(row[2])).ljust(12) await manager.send(message_send) currency_class='' cursor=c.execute("SELECT NAME FROM ASSETS") for row in cursor: currency_class+='%s '%row[0] conn.close() state['notes'] = "编辑或增加一条可消费项目请输入:“项目名称 价格 货币种类”\n可用的货币种类:%s"%currency_class elif task_id == '6': #删除一条可消费项目 message_send = '' conn = sqlite3.connect('./database.db') c = conn.cursor() cursor = c.execute("SELECT NAME FROM GOODS") if len(list(cursor)) == 0: message_send += '用户还没有资产呢...' await manager.send(message_send) else: message_send += '现有的可消费项目有:' cursor = c.execute("SELECT NAME FROM GOODS") for row in cursor: message_send += '\n' + \ ('%s' % (row[0])).ljust(12) await manager.send(message_send) conn.close() state['notes'] = '输入要删除的项目名称' elif task_id == '7': #查看银行业务日志 await manager.finishi('LOG数据库存在,但暂未开通查询功能⁽⁽꜀(:3꜂ ꜆)꜄⁾⁾') @manager.got("stage2_message", prompt='{notes}') async def user_stage2_handle(bot: Bot, event: Event, state: T_State): task_id = state['task'] if task_id == '2': #变动资产第二阶段 if len(state['stage2_message'].split()) != 2 or state['stage2_message'].split()[1].isdigit() == False: await manager.finish('请输入正确格式的参数') name = state['stage2_message'].split()[0] amount = int(state['stage2_message'].split()[1]) conn = sqlite3.connect('./database.db') c = conn.cursor() cursor = c.execute("SELECT * FROM ASSETS WHERE NAME=?", (name,)) if len(list(cursor)) == 0: c.execute("INSERT INTO ASSETS \ VALUES(?,?)", (name, amount)) message='新增 ' else: c.execute("UPDATE ASSETS SET AMOUNT=? WHERE NAME=?", (amount, name)) message='' message_send = '用户现有资产:\n'+'币种'.ljust(12)+'数目'.ljust(12) cursor = c.execute("SELECT NAME,AMOUNT FROM ASSETS") for row in cursor: message_send += '\n' + \ ('%s' % (row[0])).ljust(12) + ('%d' % (row[1])).ljust(12) await manager.send(message_send) message+='币种:%s,数目:%d'%(name,amount) c.execute("INSERT INTO LOG (TIME,IDENTITY,CLASS,MESSAGE) \ VALUES(?,?,?,?)", (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 1, 6,message)) conn.commit() conn.close() await manager.finish() elif task_id=='3': #删除资产条目第二阶段 if len(state['stage2_message'].split()) != 1: await manager.finish('请输入正确的参数数量') conn = sqlite3.connect('./database.db') c = conn.cursor() cursor = c.execute("SELECT * FROM ASSETS WHERE NAME=?", (state['stage2_message'].split()[0],)) if len(list(cursor)) == 0: await manager.finish('资产名目不存在哦...') name = state['stage2_message'].split()[0] c.execute("DELETE FROM ASSETS WHERE NAME=?",(name,)) message=name c.execute("INSERT INTO LOG (TIME,IDENTITY,CLASS,MESSAGE) \ VALUES(?,?,?,?)", (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 1, 7, message)) conn.commit() conn.close() await manager.finish("删除成功") elif task_id=='5': #变动消费项第二阶段 if len(state['stage2_message'].split()) != 3 or state['stage2_message'].split()[1].isdigit() == False: await manager.finish('请输入正确格式的参数') conn = sqlite3.connect('./database.db') c = conn.cursor() cursor = c.execute("SELECT * FROM ASSETS WHERE NAME=?", (state['stage2_message'].split()[2],)) if len(list(cursor)) == 0: await manager.finish('币种不存在') name = state['stage2_message'].split()[0] price = int(state['stage2_message'].split()[1]) currency = state['stage2_message'].split()[2] cursor = c.execute("SELECT * FROM GOODS WHERE NAME=?", (name,)) if len(list(cursor)) == 0: c.execute("INSERT INTO GOODS \ VALUES(?,?,?)", (name, price,currency)) message='新增' else: c.execute("UPDATE ASSETS SET PRICE=?,CURRENCY=? WHERE NAME=?", (price,currency, name)) message='' message_send = '用户可消费项目:\n'+'项目'.ljust(12)+'价格'.ljust(12)+'货币种类'.ljust(12) message+='可消费项目:%s ,价格:%d,货币种类:%s'%(name,price,currency) cursor = c.execute("SELECT NAME,PRICE,CURRENCY FROM GOODS") for row in cursor: message_send += '\n' + \ ('%s' % (row[0])).ljust(12) + ('%d' % (row[1])).ljust(12)+('%s' % (row[2])).ljust(12) await manager.send(message_send) c.execute("INSERT INTO LOG (TIME,IDENTITY,CLASS,MESSAGE) \ VALUES(?,?,?,?)", (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 1, 9, message)) conn.commit() conn.close() await manager.finish() elif task_id == '6': #删除可消费项第二阶段 if len(state['stage2_message'].split()) != 1: await manager.finish('请输入正确的参数数量') conn = sqlite3.connect('./database.db') c = conn.cursor() cursor = c.execute("SELECT * FROM GOODS WHERE NAME=?", (state['stage2_message'].split()[0],)) if len(list(cursor)) == 0: await manager.finish('消费项不存在哦...') name = state['stage2_message'].split()[0] c.execute("DELETE FROM GOODS WHERE NAME=?", (name,)) message = name c.execute("INSERT INTO LOG (TIME,IDENTITY,CLASS,MESSAGE) \ VALUES(?,?,?,?)", (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 1, 10, message)) conn.commit() conn.close() await manager.finish("删除成功") # 用户事件响应器 user = on_command('bank', priority=2) @user.handle() async def user_welcome(bot: Bot, event: Event, state: T_State): if event.get_session_id() != bank_user: await manager.finish('Permission denied.') if not os.path.exists('./database.db'): create_database() # 打印用户菜单 state['menu'] = ''' ===================== 欢迎使用Penguin Bank客户面板(≧ω≦)/ --------------------- Version 1.0版本提供以下业务: 1.查询资产 2.查看可消费项目列表 3.申请消费(*需要管理员审批通过后办理) 4.给管理员留言(可许愿白嫖) ===================== 请输入对应序号办理业务> ''' @user.got("task_id", prompt='{menu}') async def user_task_handle(bot: Bot, event: Event, state: T_State): task_id = state['task_id'] if task_id == '1': # 查询资产 conn = sqlite3.connect('./database.db') c = conn.cursor() c.execute("INSERT INTO LOG (TIME,IDENTITY,CLASS) \ VALUES(?,?,?)", (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 2, 1)) cursor = c.execute("SELECT NAME,AMOUNT FROM ASSETS") if len(list(cursor)) == 0: conn.commit() conn.close() await manager.finish('还没有资产哦_(:з」∠)_') else: message_send = '币种'.ljust(12)+'数目'.ljust(12) cursor = c.execute("SELECT NAME,AMOUNT FROM ASSETS") for row in cursor: message_send += '\n' + \ ('%s' % (row[0])).ljust(12) + ('%d' % (row[1])).ljust(12) conn.commit() conn.close() await manager.finish(message_send) elif task_id == '2': #查看可消费项目列表 conn = sqlite3.connect('./database.db') c = conn.cursor() c.execute("INSERT INTO LOG (TIME,IDENTITY,CLASS) \ VALUES(?,?,?)", (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 2, 2)) cursor = c.execute("SELECT NAME,PRICE,CURRENCY FROM GOODS") if len(list(cursor)) == 0: conn.commit() conn.close() await manager.finish('还没有可消费项目哦_(:з」∠)_') else: message_send = '项目'.ljust(12)+'价格'.ljust(12)+'货币种类'.ljust(12) cursor = c.execute("SELECT NAME,PRICE,CURRENCY FROM GOODS") for row in cursor: message_send += '\n' + \ ('%s' % (row[0])).ljust(12) + ('%d' %(row[1])).ljust(12)+('%s' % (row[2])).ljust(12) conn.commit() conn.close() await manager.finish(message_send) elif task_id == '3': #申请消费 conn = sqlite3.connect('./database.db') c = conn.cursor() cursor = c.execute("SELECT NAME FROM GOODS") if len(list(cursor)) == 0: conn.commit() conn.close() await manager.finish('还没有可消费项目哦_(:з」∠)_') else: message_send = '现在有以下项目可供消费(≧ω≦)/' cursor = c.execute("SELECT NAME,PRICE,CURRENCY FROM GOODS") for row in cursor: message_send += '\n' + ('%s' % (row[0])).ljust(12) await user.send(message_send) conn.commit() conn.close() state['notes']='请输入想消费的项目名称:' elif task_id == '4': #留言 state['notes'] = '请输入留言内容:' @user.got("stage2_message", prompt='{notes}') async def user_stage2_handle(bot: Bot, event: Event, state: T_State): task_id = state['task_id'] if task_id == '3': if len(state['stage2_message'].split()) != 1: await manager.finish('请输入正确的参数数量') conn = sqlite3.connect('./database.db') c = conn.cursor() cursor = c.execute("SELECT * FROM GOODS WHERE NAME=?", (state['stage2_message'].split()[0],)) if len(list(cursor)) == 0: await manager.finish('消费项不存在哦...') name = state['stage2_message'].split()[0] timestamp = int(time.time()) request_id = timestamp % 1000000 message = '申请消费'+' '+name message_send = ''' 收到一条来自用户的申请(≧ω≦)/ request_id: %s message: %s 输入: #approval %s 对本条消息进行审批 ''' % (str(request_id), message, str(request_id)) await bot.call_api("send_msg", user_id=bank_manager, message=message_send) c.execute("INSERT INTO TODO (ID,CLASS,MESSAGE) \ VALUES (?, ?, ? )", (request_id, 3, name)) c.execute("INSERT INTO LOG (TIME,IDENTITY,CLASS,MESSAGE) \ VALUES(?,?,?,?)", (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 2, 3, str(request_id)+' '+name)) conn.commit() conn.close() await user.finish() elif task_id == '4': message_send = '【企鹅银行】这是一条来自用户的留言:\n'+'[%s]' % time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime())+'“'+state['stage2_message']+'”' await bot.call_api("send_msg", user_id=bank_manager, message=message_send) conn = sqlite3.connect('./database.db') c = conn.cursor() c.execute("INSERT INTO LOG (TIME,IDENTITY,CLASS,MESSAGE) \ VALUES(?,?,?,?)", (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 2, 4, state['stage2_message'])) conn.commit() conn.close() await user.finish() #处理用户申请部分 approval=on_command('approval',priority=3) @approval.handle() async def approval_welcome(bot: Bot, event: Event, state: T_State): if event.get_session_id() != bank_manager: await manager.finish('Permission denied.') request_id = str(event.get_message()) state['request_id']=request_id conn = sqlite3.connect('./database.db') c = conn.cursor() #默认TODO表的CLASS为3(消费) cursor=c.execute("SELECT MESSAGE FROM TODO WHERE ID=?",(request_id,)) for row in cursor: state['name']=row[0] await approval.send(state['name']) cursor=c.execute("SELECT PRICE,CURRENCY FROM GOODS WHERE NAME=?",(state['name'],)) for row in cursor: state['price']=row[0] state['currency']=row[1] cursor=c.execute("SELECT AMOUNT FROM ASSETS WHERE NAME=?",(state['currency'],)) for row in cursor: state['amount']=int(row[0]) state['notes']='%s 的参考价格为:%d,\n货币种类为:%s'%(state['name'],state['price'],state['currency']) state['notes']+='\n用户的该币种剩余数量:%s'%(state['amount']) await approval.send(state['notes']) state['notes']='是否同意审批:y/n' conn.close() @approval.got("task_message",prompt='{notes}') async def approval_handle(bot: Bot, event: Event, state: T_State): #state['task_message']=str(state['task_message']) if state['task_message']!='y' and state['task_message']!='n': await approval.finish('请输入正确的内容') if state['task_message']=='y': state['notes']='请输入扣费数目:' elif state['task_message']=='n': conn = sqlite3.connect('./database.db') c = conn.cursor() c.execute("INSERT INTO LOG(TIME,IDENTITY,CLASS,MESSAGE)\ VALUES(?,?,?,?)", (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 1, 11, state['request_id']+' '+'n')) conn.commit() conn.close() message_send = '消费申请 request_id:%s %s 未通过' % (state['request_id'], state['name']) await bot.call_api("send_msg", user_id=bank_user, message=message_send) await approval.finish('审批流程结束') @approval.got("costs", prompt='{notes}') async def approval_stage2_handle(bot: Bot, event: Event, state: T_State): state['costs']=int(state['costs']) if state['costs']>state['amount']: await approval.finish('用户该币种余额不足') else: conn = sqlite3.connect('./database.db') c = conn.cursor() c.execute("UPDATE ASSETS SET AMOUNT=? WHERE NAME=?",(state['amount']-state['costs'], state['currency'])) c.execute("INSERT INTO LOG(TIME,IDENTITY,CLASS,MESSAGE)\ VALUES(?,?,?,?)", (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 1, 11, state['request_id']+' '+'y'+' '+str(state['costs']))) conn.commit() conn.close() message_send = '消费申请 request_id:%s %s 通过\n' % (state['request_id'], state['name']) message_send += '%s余额:%d' % (state['name'],state['amount']-state['costs']) await bot.call_api("send_msg", user_id=bank_user, message=message_send) message_send='审批流程结束,用户申请 %s 成功,记得及时兑现哦'%(state['name']) await approval.finish(message_send) ``` 和 `create_initial_database.py` ```python import sqlite3 def create_database(): conn=sqlite3.connect('./database.db') c = conn.cursor() c.execute('''CREATE TABLE ASSETS (NAME TEXT PRIMARY KEY NOT NULL, AMOUNT INT NOT NULL);''') c.execute('''CREATE TABLE GOODS (NAME TEXT PRIMARY KEY NOT NULL, PRICE INT NOT NULL, CURRENCY TEXT NOT NULL, FOREIGN KEY(CURRENCY) REFERENCES ASSETS(NAME));''') c.execute('''CREATE TABLE TODO (ID TEXT PRIMARY KEY NOT NULL, CLASS INT NOT NULL, MESSAGE TEXT );''') c.execute('''CREATE TABLE LOG (TIME TEXT PRIMARY KEY NOT NULL, IDENTITY INT, CLASS INT NOT NULL, MESSAGE TEXT );''') conn.commit() conn.close() #CLASS #MESSAGE #用户行为(IDENTITY 1) #1 查询资产 #2 查看可消费项目列表 #3 申请消费 审批编号+消费项目 #4 留言 留言内容 #管理员行为(IDENTITY 2) #5 查询用户资产 #6 变动用户资产 标注如何变动 #7 删除一项资产名目 删除的内容 #8 查看可消费项目列表 #9 编辑或增加一条可消费项目 记录把什么变为什么/增加的内容 #10 删除一条可消费项目 删除的内容 #11 审批 编号+y or n+扣费量 #12 查看银行业务日志 #审批 y or n,扣费量 ``` 同样需要在bot的env文件中添加配置信息: ``` #qie_bank bank_manager="" #qq号 bank_user="" ``` 最后修改:2021 年 12 月 01 日 01 : 14 AM © 允许规范转载
20 条评论
文章的确不错啊https://www.cscnn.com/
不错不错,我喜欢看 www.jiwenlaw.com
看的我热血沸腾啊https://www.ea55.com/
想想你的文章写的特别好https://www.237fa.com/
看的我热血沸腾啊https://www.jiwenlaw.com/
555
555
555
1
1
555
1
555
555
555