bc: Update plugin bc v1.3 (#21)

This commit is contained in:
Pentacene 2024-03-15 20:26:32 +08:00 committed by GitHub
parent 7e14c2232e
commit c3ac15017f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 86 additions and 84 deletions

150
bc.py
View File

@ -7,107 +7,109 @@
# \_| \___|_| |_|\__\__,_|\___\___|_| |_|\___| # \_| \___|_| |_|\__\__,_|\___\___|_| |_|\___|
# #
from asyncio import sleep from datetime import datetime
from sys import executable from sys import executable
import urllib.request import urllib.request
from telethon.tl.custom.message import Message from pyrogram import Client
from pagermaid import version
from pagermaid.listener import listener from pagermaid.listener import listener
from pagermaid.utils import execute, alias_command, pip_install from pagermaid.utils import Message, pip_install
pip_install("python-binance", alias="binance") pip_install("binance-connector", alias="binance")
pip_install("xmltodict") pip_install("xmltodict")
from binance.client import Client from binance.spot import Spot
from binance.error import ClientError
import xmltodict import xmltodict
API = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml" API = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
CURRENCIES = []
DATA = {}
BINANCE_API_KEY = '8PDfQ2lSIyHPWdNAHNIaIoNy3MiiMuvgwYADbmtsKo867B0xnIhIGjPULsOtvMRk'
BINANCE_API_SECRET = 'tbUiyZ94l0zpYOlKs3eO1dvLNMOSbOb2T1T0eT0I1eogH9Fh8Htvli05eZ1iDvra'
def init() -> list:
def init() -> None:
""" INIT """ """ INIT """
with urllib.request.urlopen(API) as response: with urllib.request.urlopen(API) as response:
result = response.read() result = response.read()
try: currencies = []
global CURRENCIES, DATA data = {}
rate_data = xmltodict.parse(result) rate_data = xmltodict.parse(result)
rate_data = rate_data['gesmes:Envelope']['Cube']['Cube']['Cube'] rate_data = rate_data['gesmes:Envelope']['Cube']['Cube']['Cube']
for i in rate_data: for i in rate_data:
CURRENCIES.append(i['@currency']) currencies.append(i['@currency'])
DATA[i['@currency']] = float(i['@rate']) data[i['@currency']] = float(i['@rate'])
CURRENCIES.sort() currencies.sort()
except Exception as e: return [currencies, data]
raise e
@listener(is_plugin=True, outgoing=True, command=alias_command("bc"), @listener(is_plugin=True, outgoing=True, command=alias_command("bc"),
description="coins", description="coins",
parameters="<num> <coin1> <coin2>") parameters="<num> <coin1> <coin2>")
async def coin(context: Message) -> None: async def coin(context: Message) -> None:
""" coin change """ """coin change"""
init() currencies, data = init()
action = context.arguments.split() binanceclient = Spot()
binanceclient = Client(BINANCE_API_KEY, BINANCE_API_SECRET) nowtimestamp = binanceclient.time()
if len(action) < 3: nowtime = datetime.fromtimestamp(float(nowtimestamp['serverTime'])/1000)
await context.edit('输入错误.\n-bc 数量 币种1 币种2') if len(context.parameter) == 0:
btc_usdt_data = binanceclient.klines("BTCUSDT", "1m")[:1][0]
eth_usdt_data = binanceclient.klines("ETHUSDT", "1m")[:1][0]
await context.edit((
f'{nowtime.strftime("%Y-%m-%d %H:%M:%S")} UTC\n'
f'**1 BTC** = {btc_usdt_data[1]} USDT '
f'\n'
f'**1 ETH** = {eth_usdt_data[1]} USDT '))
return
if len(context.parameter) < 3:
await context.edit('输入错误.\nbc 数量 币种1 币种2')
return return
else:
prices = binanceclient.get_all_tickers()
try: try:
number = float(action[0]) number = float(context.parameter[0])
except ValueError: except ValueError:
await context.edit('输入错误.\n-bc 数量 币种1 币种2') await context.edit('输入错误.\nbc 数量 币种1 币种2')
return return
_from = action[1].upper().strip() _from = context.parameter[1].upper().strip()
_to = action[2].upper().strip() _to = context.parameter[2].upper().strip()
front_text = ''
text = ''
rear_text = ''
price = 0.0
_to_USD_rate = 0.0
if (CURRENCIES.count(_from) != 0) and (CURRENCIES.count(_to) != 0):
# both are real currency # both are real currency
text = f'{action[0]} {action[1].upper().strip()} = {float(action[0])*DATA[_to]/DATA[_from]:.2f} {action[2].upper().strip()}' if (currencies.count(_from) != 0) and (currencies.count(_to) != 0):
await context.edit((
f'{context.parameter[0]} {context.parameter[1].upper().strip()} ='
f'{number * data[_to] / data[_from]:.2f} '
f'{context.parameter[2].upper().strip()}'))
return
else: # from real currency to crypto
if CURRENCIES.count(_from) != 0: if currencies.count(_from) != 0:
# from virtual currency to real currency usd_number = number * data["USD"] / data[_from]
number = number * DATA["USD"] / DATA[_from] try:
_from = 'USDT' x_usdt_data = binanceclient.klines(f"{_to}USDT", "1m")[:1][0]
front_text = f'{action[0]} {action[1]} = \n' except ClientError:
await context.edit(f'Cannot find coinpair {_to}USDT')
return
await context.edit((
f'{context.parameter[0]} **{_from}** = '
f'{1 / float(x_usdt_data[1]) * usd_number:.8f} **{_to}**\n'
f'{context.parameter[0]} **{_from}** = '
f'{usd_number:.2f} **USD**'))
return
if CURRENCIES.count(_to) != 0: # from crypto to real currency
# from real currency to virtual currency if currencies.count(_to) != 0:
_to_USD_rate = DATA[_to] / DATA["USD"] usd_number = number * data[_to] / data["USD"]
_to = 'USDT' try:
x_usdt_data = binanceclient.klines(f"{_from}USDT", "1m")[:1][0]
except ClientError:
await context.edit(f'Cannot find coinpair {_from}USDT')
return
await context.edit((
f'{context.parameter[0]} **{_from}** = '
f'{float(x_usdt_data[1]) * usd_number:.2f} **{_to}**\n'
f'{context.parameter[0]} **{_from}** = '
f'{float(x_usdt_data[1]):.2f} **USD**'))
return
for _a in prices: # both crypto
if _a['symbol'] == str(f'{_from}{_to}'): try:
price = _a['price'] from_to_data = binanceclient.klines(f"{_from}{_to}", "1m")[:1][0]
if _to == 'USDT': except ClientError:
if action[2].upper().strip() == 'USDT': await context.edit(f'Cannot find coinpair {_from}{_to}')
rear_text = f'\n= {number * float(price) * DATA["CNY"]/DATA["USD"]:.2f} CNY' return
else: await context.edit((
rear_text = f'\n= {number * float(price) * _to_USD_rate:.2f} {action[2].upper().strip()}' f'{context.parameter[0]} **{_from}** = '
if float(price) < 1: f'{float(from_to_data[1]) * number} **{_to}**\n'))
text = f'{number} {_from} = {number * float(price):.8f} {_to}'
else:
text = f'{number} {_from} = {number * float(price):.2f} {_to}'
break
elif _a['symbol'] == str(f'{_to}{_from}'):
price = 1 / float(_a['price'])
text = f'{number} {_from} = {number * float(price):.8f} {_to}'
break
else:
price = None
if price is None:
text = f'Cannot find coinpair {action[1].upper().strip()}{action[2].upper().strip()} or {action[2].upper().strip()}{action[1].upper().strip()}'
await context.edit(f'{front_text}{text}{rear_text}')

View File

@ -432,10 +432,10 @@
}, },
{ {
"name": "bc", "name": "bc",
"version": "1.232", "version": "1.3",
"section": "chat", "section": "chat",
"maintainer": "Pentacene", "maintainer": "Pentacene",
"size": "8.0 kb", "size": "4.14 kb",
"supported": true, "supported": true,
"des-short": "查询含虚拟货币在内的货币价格", "des-short": "查询含虚拟货币在内的货币价格",
"des": "命令bc 数量 货币1 货币2" "des": "命令bc 数量 货币1 货币2"