#!/usr/bin/env python3 import os import aiohttp import logging from collections import defaultdict import time from telethon.sync import TelegramClient from telethon.sessions import MemorySession from telethon import events COIN_URL = 'https://www.coingecko.com/price_charts/7340/usd/max.json' api_id = int(os.environ.get('TG_API_ID')) api_hash = os.environ.get('TG_API_HASH') bot_token = os.environ.get('TG_BOT_TOKEN') logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) logger.info("Starting...") # Cooldown def cooldown(timeout): def wrapper(function): last_called = defaultdict(int) async def wrapped(event, *args, **kwargs): current_time = time.time() if current_time - last_called[event.chat_id] < timeout: return last_called[event.chat_id] = current_time return await function(event, *args, **kwargs) return wrapped return wrapper client = TelegramClient(MemorySession(), api_id, api_hash).start( bot_token=bot_token) client.session.save_entities = False # /price @client.on(events.NewMessage(pattern=r"(?i)/price(@\w+)?$")) @cooldown(300) async def price_handler(event): async with aiohttp.ClientSession() as session: async with session.get(COIN_URL) as resp: if resp.status >= 300: await event.respond("Server Error") return await event.respond("1 GRIN = **{:.2f}$**".format( (await resp.json())['stats'][-1][1])) # /blocks @client.on(events.NewMessage(pattern=r"(?i)/blocks(@\w+)?$")) @cooldown(300) async def blocks_handler(event): async with aiohttp.ClientSession() as session: async with session.get(os.environ.get('GRIN_API_URL') + '/v1/status') as resp: if resp.status >= 300: await event.respond("Server Error") return j = await resp.json(content_type=None) await event.respond(f"Chain Height = {j['tip']['height']:,}\n" f"Network Difficulty = " + f"{j['tip']['total_difficulty']:,}") try: logger.info("Started") client.run_until_disconnected() finally: client.disconnect()