mirror of
https://github.com/Xtao-Labs/iShotaBot.git
synced 2024-11-25 18:03:36 +00:00
✨ 支持 exchange 汇率查询
This commit is contained in:
parent
40432a1164
commit
994cf694a7
59
defs/exchange.py
Normal file
59
defs/exchange.py
Normal file
@ -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} = <b>{round(num * rate_data[TO.lower()], 2)} {TO}</b>\n'
|
||||||
|
f'Rate: <b>{round(1.0 * rate_data[TO.lower()], 6)}</b>')
|
||||||
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
|
return '请求 API 发送错误。'
|
||||||
|
|
||||||
|
|
||||||
|
exchange_client = Exchange()
|
@ -2,10 +2,15 @@ from configparser import RawConfigParser
|
|||||||
from typing import Union
|
from typing import Union
|
||||||
from distutils.util import strtobool
|
from distutils.util import strtobool
|
||||||
|
|
||||||
|
# [pyrogram]
|
||||||
|
api_id: int = 0
|
||||||
|
api_hash: str = ""
|
||||||
# [Basic]
|
# [Basic]
|
||||||
ipv6: Union[bool, str] = "False"
|
ipv6: Union[bool, str] = "False"
|
||||||
config = RawConfigParser()
|
config = RawConfigParser()
|
||||||
config.read("config.ini")
|
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)
|
ipv6 = config.get("basic", "ipv6", fallback=ipv6)
|
||||||
try:
|
try:
|
||||||
ipv6 = strtobool(ipv6)
|
ipv6 = strtobool(ipv6)
|
||||||
|
8
init.py
8
init.py
@ -2,7 +2,8 @@ import logging
|
|||||||
|
|
||||||
import httpx
|
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 pyrogram import Client
|
||||||
from logging import getLogger, INFO, ERROR, StreamHandler, basicConfig
|
from logging import getLogger, INFO, ERROR, StreamHandler, basicConfig
|
||||||
from coloredlogs import ColoredFormatter
|
from coloredlogs import ColoredFormatter
|
||||||
@ -21,6 +22,9 @@ root_logger.addHandler(logging_handler)
|
|||||||
basicConfig(level=INFO)
|
basicConfig(level=INFO)
|
||||||
logs.setLevel(INFO)
|
logs.setLevel(INFO)
|
||||||
logger = logging.getLogger("iShotaBot")
|
logger = logging.getLogger("iShotaBot")
|
||||||
|
|
||||||
|
if not scheduler.running:
|
||||||
|
scheduler.start()
|
||||||
# Init client
|
# Init client
|
||||||
|
|
||||||
|
|
||||||
@ -30,7 +34,7 @@ class UserMe:
|
|||||||
|
|
||||||
|
|
||||||
user_me = 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 = {
|
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"
|
"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"
|
||||||
}
|
}
|
||||||
|
40
modules/exchange.py
Normal file
40
modules/exchange.py
Normal file
@ -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('支持货币: <code>' + ', '.join(exchange_client.currencies) + '</code>')
|
@ -5,7 +5,7 @@ from defs.guess import guess_str
|
|||||||
from init import user_me
|
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}"]))
|
filters.command(["guess", f"guess@{user_me.username}"]))
|
||||||
async def guess_command(_: Client, message: Message):
|
async def guess_command(_: Client, message: Message):
|
||||||
msg = await message.reply('正在查询中...')
|
msg = await message.reply('正在查询中...')
|
||||||
|
@ -10,3 +10,5 @@ mutagen
|
|||||||
playwright
|
playwright
|
||||||
uvicorn
|
uvicorn
|
||||||
jinja2
|
jinja2
|
||||||
|
apscheduler
|
||||||
|
pytz
|
||||||
|
25
scheduler.py
Normal file
25
scheduler.py
Normal file
@ -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)
|
Loading…
Reference in New Issue
Block a user