64 lines
2.5 KiB
Python
64 lines
2.5 KiB
Python
"""
|
||
This plugin provides a command to fetch the current Bitcoin price.
|
||
"""
|
||
import logging
|
||
import aiohttp
|
||
import simplematrixbotlib as botlib
|
||
from plugins.common import html_escape
|
||
|
||
BITCOIN_API_URL = "https://api.bitcointicker.co/trades/bitstamp/btcusd/60/"
|
||
|
||
async def handle_command(room, message, bot, prefix, config):
|
||
match = botlib.MessageMatch(room, message, bot, prefix)
|
||
if match.is_not_from_this_bot() and match.prefix() and match.command("btc"):
|
||
logging.info("Received !btc command")
|
||
try:
|
||
headers = {
|
||
'Accept-Encoding': 'gzip, deflate',
|
||
'User-Agent': 'FunguyBot/1.0'
|
||
}
|
||
async with aiohttp.ClientSession() as session:
|
||
async with session.get(BITCOIN_API_URL, headers=headers, timeout=10) as response:
|
||
response.raise_for_status()
|
||
data = await response.json()
|
||
|
||
if not data or len(data) == 0:
|
||
await bot.api.send_text_message(room.room_id, "No Bitcoin price data available.")
|
||
return
|
||
|
||
latest_trade = data[-1]
|
||
price = latest_trade.get('price')
|
||
if price is None:
|
||
await bot.api.send_text_message(room.room_id, "Could not extract Bitcoin price from API response.")
|
||
return
|
||
|
||
try:
|
||
price_float = float(price)
|
||
price_formatted = f"${price_float:,.2f}"
|
||
except (ValueError, TypeError):
|
||
price_formatted = f"${price}"
|
||
|
||
message_text = f"<strong>₿ BTC/USD</strong>"
|
||
message_text += f"<strong> Current Price:</strong> {price_formatted}"
|
||
message_text += ", <em>bitcointicker.co</em>"
|
||
|
||
await bot.api.send_markdown_message(room.room_id, message_text)
|
||
logging.info(f"Sent Bitcoin price: {price_formatted}")
|
||
|
||
except aiohttp.ClientError as e:
|
||
await bot.api.send_text_message(room.room_id, f"Error fetching Bitcoin price: {e}")
|
||
logging.error(f"Error fetching Bitcoin price: {e}")
|
||
except Exception as e:
|
||
await bot.api.send_text_message(room.room_id, "An unexpected error occurred.")
|
||
logging.error(f"Unexpected error in Bitcoin plugin: {e}", exc_info=True)
|
||
|
||
__version__ = "1.0.1"
|
||
__author__ = "Funguy Bot"
|
||
__description__ = "Current Bitcoin price"
|
||
__help__ = """
|
||
<details>
|
||
<summary><strong>!btc</strong> – Current Bitcoin price</summary>
|
||
<p>Fetches the latest BTC/USD price from bitcointicker.co.</p>
|
||
</details>
|
||
"""
|