From 994cf694a7d1e56c89aad5d82042839cf5918817 Mon Sep 17 00:00:00 2001 From: xtaodada Date: Sun, 2 Oct 2022 23:14:06 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20=E6=94=AF=E6=8C=81=20exchange=20?= =?UTF-8?q?=E6=B1=87=E7=8E=87=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- defs/exchange.py | 59 +++++++++++++++++++++++++++++++++++++++++++++ defs/glover.py | 5 ++++ init.py | 8 ++++-- modules/exchange.py | 40 ++++++++++++++++++++++++++++++ modules/guess.py | 2 +- requirements.txt | 2 ++ scheduler.py | 25 +++++++++++++++++++ 7 files changed, 138 insertions(+), 3 deletions(-) create mode 100644 defs/exchange.py create mode 100644 modules/exchange.py create mode 100644 scheduler.py diff --git a/defs/exchange.py b/defs/exchange.py new file mode 100644 index 0000000..e495d98 --- /dev/null +++ b/defs/exchange.py @@ -0,0 +1,59 @@ +from init import request + + +class Exchange: + API = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.json" + + def __init__(self): + self.inited = False + self.data = {} + self.currencies = [] + + async def refresh(self): + try: + req = await request.get(self.API) + data = req.json() + self.currencies.clear() + for key in list(enumerate(data)): + self.currencies.append(key[1].upper()) + self.currencies.sort() + self.inited = True + except Exception: + pass + + async def check_ex(self, message): + tlist = message.text.split() + if not 2 < len(tlist) < 5: + return 'help' + elif len(tlist) == 3: + num = 1.0 + FROM = tlist[1].upper().strip() + TO = tlist[2].upper().strip() + else: + try: + num = float(tlist[1]) + if len(str(int(num))) > 10: + return 'ValueBig' + if len(str(num)) > 15: + return 'ValueSmall' + except ValueError: + return 'ValueError' + FROM = tlist[2].upper().strip() + TO = tlist[3].upper().strip() + if self.currencies.count(FROM) == 0: + return 'FromError' + if self.currencies.count(TO) == 0: + return 'ToError' + endpoint = f"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/" \ + f"{FROM.lower()}/{TO.lower()}.json" + try: + req = await request.get(endpoint) + rate_data = req.json() + return (f'{num} {FROM} = {round(num * rate_data[TO.lower()], 2)} {TO}\n' + f'Rate: {round(1.0 * rate_data[TO.lower()], 6)}') + except Exception as e: + print(e) + return '请求 API 发送错误。' + + +exchange_client = Exchange() diff --git a/defs/glover.py b/defs/glover.py index 7c9d412..0257af5 100644 --- a/defs/glover.py +++ b/defs/glover.py @@ -2,10 +2,15 @@ from configparser import RawConfigParser from typing import Union from distutils.util import strtobool +# [pyrogram] +api_id: int = 0 +api_hash: str = "" # [Basic] ipv6: Union[bool, str] = "False" config = RawConfigParser() config.read("config.ini") +api_id = config.getint("pyrogram", "api_id", fallback=api_id) +api_hash = config.get("pyrogram", "api_hash", fallback=api_hash) ipv6 = config.get("basic", "ipv6", fallback=ipv6) try: ipv6 = strtobool(ipv6) diff --git a/init.py b/init.py index 6f570ec..032f857 100644 --- a/init.py +++ b/init.py @@ -2,7 +2,8 @@ import logging import httpx -from defs.glover import ipv6 +from defs.glover import api_id, api_hash, ipv6 +from scheduler import scheduler from pyrogram import Client from logging import getLogger, INFO, ERROR, StreamHandler, basicConfig from coloredlogs import ColoredFormatter @@ -21,6 +22,9 @@ root_logger.addHandler(logging_handler) basicConfig(level=INFO) logs.setLevel(INFO) logger = logging.getLogger("iShotaBot") + +if not scheduler.running: + scheduler.start() # Init client @@ -30,7 +34,7 @@ class UserMe: user_me = UserMe() -bot = Client("bot", ipv6=ipv6, plugins=dict(root="modules")) +bot = Client("bot", api_id=api_id, api_hash=api_hash, ipv6=ipv6, plugins=dict(root="modules")) headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.72 Safari/537.36" } diff --git a/modules/exchange.py b/modules/exchange.py new file mode 100644 index 0000000..5517b0d --- /dev/null +++ b/modules/exchange.py @@ -0,0 +1,40 @@ +from pyrogram import Client, filters +from pyrogram.enums import ChatType +from pyrogram.types import Message + +from defs.exchange import exchange_client +from scheduler import scheduler +from init import user_me + + +@scheduler.scheduled_job("cron", hour="8", id="exchange.refresh") +async def exchange_refresh() -> None: + await exchange_client.refresh() + + +@Client.on_message(filters.incoming & + filters.command(["exchange", f"exchange@{user_me.username}"])) +async def exchange_command(_: Client, message: Message): + if not exchange_client.inited: + await exchange_client.refresh() + if not exchange_client.inited: + return await message.reply("获取汇率数据出现错误!") + text = await exchange_client.check_ex(message) + if text == 'help': + text = '该指令可用于查询汇率。\n使用方式举例:\n/exchange USD CNY - 1 USD 等于多少 CNY\n' \ + '/exchange 11 CNY USD - 11 CNY 等于多少 USD' + elif text == 'ValueError': + text = '金额不合法' + elif text == 'ValueBig': + text = '我寻思你也没这么多钱啊。' + elif text == 'ValueSmall': + text = '小数点后的数字咋这么多?' + elif text == 'FromError': + text = '不支持的起源币种。' + elif text == 'ToError': + text = '不支持的目标币种。' + else: + return await message.reply(text) + reply_ = await message.reply(text) + if message.chat.type == ChatType.PRIVATE: + await reply_.reply('支持货币: ' + ', '.join(exchange_client.currencies) + '') diff --git a/modules/guess.py b/modules/guess.py index 2c3fcb6..f887f6e 100644 --- a/modules/guess.py +++ b/modules/guess.py @@ -5,7 +5,7 @@ from defs.guess import guess_str from init import user_me -@Client.on_message(filters.incoming & filters.group & +@Client.on_message(filters.incoming & filters.command(["guess", f"guess@{user_me.username}"])) async def guess_command(_: Client, message: Message): msg = await message.reply('正在查询中...') diff --git a/requirements.txt b/requirements.txt index ea173f4..edc18e0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,3 +10,5 @@ mutagen playwright uvicorn jinja2 +apscheduler +pytz diff --git a/scheduler.py b/scheduler.py new file mode 100644 index 0000000..15901ca --- /dev/null +++ b/scheduler.py @@ -0,0 +1,25 @@ +import contextlib +import datetime + +import pytz +from apscheduler.schedulers.asyncio import AsyncIOScheduler +from pyrogram.types import Message + +scheduler = AsyncIOScheduler(timezone="Asia/ShangHai") + + +async def delete_message(message: Message) -> bool: + with contextlib.suppress(Exception): + await message.delete() + return True + return False + + +def add_delete_message_job(message: Message, delete_seconds: int = 60): + scheduler.add_job( + delete_message, "date", + id=f"{message.chat.id}|{message.id}|delete_message", + name=f"{message.chat.id}|{message.id}|delete_message", + args=[message], + run_date=datetime.datetime.now(pytz.timezone("Asia/Shanghai")) + datetime.timedelta(seconds=delete_seconds), + replace_existing=True)