Created
February 14, 2019 09:53
-
-
Save drizzt/be7bf310b35513974ebe2a8c4d5a4098 to your computer and use it in GitHub Desktop.
Revisions
-
drizzt created this gist
Feb 14, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,77 @@ #!/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()