Skip to content

Instantly share code, notes, and snippets.

@drizzt
Created February 14, 2019 09:53
Show Gist options
  • Save drizzt/be7bf310b35513974ebe2a8c4d5a4098 to your computer and use it in GitHub Desktop.
Save drizzt/be7bf310b35513974ebe2a8c4d5a4098 to your computer and use it in GitHub Desktop.

Revisions

  1. drizzt created this gist Feb 14, 2019.
    77 changes: 77 additions & 0 deletions grinbot.py
    Original 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()